@crawlee/otel 4.0.0-beta.156

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.
package/LICENSE.md 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 2018 Apify Technologies s.r.o.
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,153 @@
1
+ <h1 align="center">
2
+ <a href="https://crawlee.dev">
3
+ <picture>
4
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/apify/crawlee/master/website/static/img/crawlee-dark.svg?sanitize=true" />
5
+ <img alt="Crawlee" src="https://raw.githubusercontent.com/apify/crawlee/master/website/static/img/crawlee-light.svg?sanitize=true" width="500" />
6
+ </picture>
7
+ </a>
8
+ <br />
9
+ <small>A web scraping and browser automation library</small>
10
+ </h1>
11
+
12
+ <p align="center">
13
+ <a href="https://trendshift.io/repositories/5179" target="_blank"><img src="https://trendshift.io/api/badge/repositories/5179" alt="apify%2Fcrawlee | Trendshift" width="250" height="55"/></a>
14
+ </p>
15
+
16
+ <p align="center">
17
+ <a href="https://www.npmjs.com/package/@crawlee/core" rel="nofollow"><img src="https://img.shields.io/npm/v/@crawlee/core.svg" alt="NPM latest version" data-canonical-src="https://img.shields.io/npm/v/@crawlee/core/next.svg" /></a>
18
+ <a href="https://www.npmjs.com/package/@crawlee/core" rel="nofollow"><img src="https://img.shields.io/npm/dm/@crawlee/core.svg" alt="Downloads" data-canonical-src="https://img.shields.io/npm/dm/@crawlee/core.svg" /></a>
19
+ <a href="https://discord.gg/jyEM2PRvMU" rel="nofollow"><img src="https://img.shields.io/discord/801163717915574323?label=discord" alt="Chat on discord" data-canonical-src="https://img.shields.io/discord/801163717915574323?label=discord" /></a>
20
+ <a href="https://github.com/apify/crawlee/actions/workflows/test-ci.yml"><img src="https://github.com/apify/crawlee/actions/workflows/test-ci.yml/badge.svg?branch=master" alt="Build Status" /></a>
21
+ </p>
22
+
23
+ Crawlee covers your crawling and scraping end-to-end and **helps you build reliable scrapers. Fast.**
24
+
25
+ Your crawlers will appear human-like and fly under the radar of modern bot protections even with the default configuration. Crawlee gives you the tools to crawl the web for links, scrape data, and store it to disk or cloud while staying configurable to suit your project's needs.
26
+
27
+ Crawlee is available as the [`crawlee`](https://www.npmjs.com/package/crawlee) NPM package.
28
+
29
+ > 👉 **View full documentation, guides and examples on the [Crawlee project website](https://crawlee.dev)** 👈
30
+
31
+ > Do you prefer 🐍 Python instead of JavaScript? [👉 Checkout Crawlee for Python 👈](https://github.com/apify/crawlee-python).
32
+
33
+ ## Installation
34
+
35
+ We recommend visiting the [Introduction tutorial](https://crawlee.dev/js/docs/introduction) in Crawlee documentation for more information.
36
+
37
+ > Crawlee requires **Node.js 16 or higher**.
38
+
39
+ ### With Crawlee CLI
40
+
41
+ The fastest way to try Crawlee out is to use the **Crawlee CLI** and choose the **Getting started example**. The CLI will install all the necessary dependencies and add boilerplate code for you to play with.
42
+
43
+ ```bash
44
+ npx crawlee create my-crawler
45
+ ```
46
+
47
+ ```bash
48
+ cd my-crawler
49
+ npm start
50
+ ```
51
+
52
+ ### Manual installation
53
+ If you prefer adding Crawlee **into your own project**, try the example below. Because it uses `PlaywrightCrawler` we also need to install [Playwright](https://playwright.dev). It's not bundled with Crawlee to reduce install size.
54
+
55
+ ```bash
56
+ npm install crawlee playwright
57
+ ```
58
+
59
+ ```js
60
+ import { PlaywrightCrawler, Dataset } from 'crawlee';
61
+
62
+ // PlaywrightCrawler crawls the web using a headless
63
+ // browser controlled by the Playwright library.
64
+ const crawler = new PlaywrightCrawler({
65
+ // Use the requestHandler to process each of the crawled pages.
66
+ async requestHandler({ request, page, enqueueLinks, log }) {
67
+ const title = await page.title();
68
+ log.info(`Title of ${request.loadedUrl} is '${title}'`);
69
+
70
+ // Save results as JSON to ./storage/datasets/default
71
+ await Dataset.pushData({ title, url: request.loadedUrl });
72
+
73
+ // Extract links from the current page
74
+ // and add them to the crawling queue.
75
+ await enqueueLinks();
76
+ },
77
+ // Uncomment this option to see the browser window.
78
+ // headless: false,
79
+ });
80
+
81
+ // Add first URL to the queue and start the crawl.
82
+ await crawler.run(['https://crawlee.dev']);
83
+ ```
84
+
85
+ By default, Crawlee stores data to `./storage` in the current working directory. You can override this directory via Crawlee configuration. For details, see [Configuration guide](https://crawlee.dev/js/docs/guides/configuration), [Request storage](https://crawlee.dev/js/docs/guides/request-storage) and [Result storage](https://crawlee.dev/js/docs/guides/result-storage).
86
+
87
+ ### Installing pre-release versions
88
+
89
+ We provide automated beta builds for every merged code change in Crawlee. You can find them in the npm [list of releases](https://www.npmjs.com/package/crawlee?activeTab=versions). If you want to test new features or bug fixes before we release them, feel free to install a beta build like this:
90
+
91
+ ```bash
92
+ npm install crawlee@next
93
+ ```
94
+
95
+ If you also use the [Apify SDK](https://github.com/apify/apify-sdk-js), you need to specify dependency overrides in your `package.json` file so that you don't end up with multiple versions of Crawlee installed:
96
+
97
+ ```json
98
+ {
99
+ "overrides": {
100
+ "apify": {
101
+ "@crawlee/core": "$crawlee",
102
+ "@crawlee/types": "$crawlee",
103
+ "@crawlee/utils": "$crawlee"
104
+ }
105
+ }
106
+ }
107
+ ```
108
+
109
+ ## 🛠 Features
110
+
111
+ - Single interface for **HTTP and headless browser** crawling
112
+ - Persistent **queue** for URLs to crawl (breadth & depth first)
113
+ - Pluggable **storage** of both tabular data and files
114
+ - Automatic **scaling** with available system resources
115
+ - Integrated **proxy rotation** and session management
116
+ - Lifecycles customizable with **hooks**
117
+ - **CLI** to bootstrap your projects
118
+ - Configurable **routing**, **error handling** and **retries**
119
+ - **Dockerfiles** ready to deploy
120
+ - Written in **TypeScript** with generics
121
+
122
+ ### 👾 HTTP crawling
123
+
124
+ - Zero config **HTTP2 support**, even for proxies
125
+ - Automatic generation of **browser-like headers**
126
+ - Replication of browser **TLS fingerprints**
127
+ - Integrated fast **HTML parsers**. Cheerio and JSDOM
128
+ - Yes, you can scrape **JSON APIs** as well
129
+
130
+ ### 💻 Real browser crawling
131
+
132
+ - JavaScript **rendering** and **screenshots**
133
+ - **Headless** and **headful** support
134
+ - Zero-config generation of **human-like fingerprints**
135
+ - Automatic **browser management**
136
+ - Use **Playwright** and **Puppeteer** with the same interface
137
+ - **Chrome**, **Firefox**, **Webkit** and many others
138
+
139
+ ## Usage on the Apify platform
140
+
141
+ Crawlee is open-source and runs anywhere, but since it's developed by [Apify](https://apify.com), it's easy to set up on the Apify platform and run in the cloud. Visit the [Apify SDK website](https://sdk.apify.com) to learn more about deploying Crawlee to the Apify platform.
142
+
143
+ ## Support
144
+
145
+ If you find any bug or issue with Crawlee, please [submit an issue on GitHub](https://github.com/apify/crawlee/issues). For questions, you can ask on [Stack Overflow](https://stackoverflow.com/questions/tagged/apify), in GitHub Discussions or you can join our [Discord server](https://discord.com/invite/jyEM2PRvMU).
146
+
147
+ ## Contributing
148
+
149
+ Your code contributions are welcome, and you'll be praised to eternity! If you have any ideas for improvements, either submit an issue or create a pull request. For contribution guidelines and the code of conduct, see [CONTRIBUTING.md](https://github.com/apify/crawlee/blob/master/CONTRIBUTING.md).
150
+
151
+ ## License
152
+
153
+ This project is licensed under the Apache License 2.0 - see the [LICENSE.md](https://github.com/apify/crawlee/blob/master/LICENSE.md) file for details.
package/constants.d.ts ADDED
@@ -0,0 +1,55 @@
1
+ import { SeverityNumber } from '@opentelemetry/api-logs';
2
+ import type { LoggerMethodDefinition } from './internal-types.js';
3
+ import type { ClassMethodToInstrument, CrawleeInstrumentationConfig } from './types.js';
4
+ export declare const PACKAGE_NAME = "@crawlee/otel";
5
+ /** Used when the package version cannot be determined at runtime. */
6
+ export declare const UNKNOWN_PACKAGE_VERSION = "0.0.0";
7
+ /**
8
+ * Versions of the instrumented Crawlee packages this instrumentation knows how to patch. Methods that are missing
9
+ * in the resolved version are skipped with a warning instead of breaking the module load.
10
+ *
11
+ * Spelled out rather than written as `^4.0.0`, because a caret range never matches a prerelease and every published
12
+ * Crawlee v4 is one (`4.0.0-beta.x`, `4.0.0-rc.x`). The explicit `-0` bounds admit prereleases of 4.0.0 itself, and
13
+ * `includePrerelease` on the module definitions extends that to prereleases of later v4 minors.
14
+ *
15
+ * `@opentelemetry/instrumentation` only consults this when the loader hands it the module's base directory, which the
16
+ * ESM hook does not do - so today a wrong range here would not stop anything from being patched. It is still declared
17
+ * correctly rather than left as documentation: the range is what decides whether a module is patched as soon as a base
18
+ * directory is available, and being silently skipped is not a failure mode worth leaving armed.
19
+ */
20
+ export declare const SUPPORTED_CRAWLEE_VERSIONS: string[];
21
+ export declare const baseConfig: CrawleeInstrumentationConfig;
22
+ export declare const requestHandlingInstrumentationMethods: ClassMethodToInstrument[];
23
+ /**
24
+ * Maps Apify log levels to OpenTelemetry severity numbers.
25
+ * See https://github.com/apify/apify-shared-js/blob/83d46cf72a338ff671f89dcbc2b0db7dd571e29f/packages/log/src/log_consts.ts#L1
26
+ *
27
+ * ```typescript
28
+ * export enum LogLevel {
29
+ * // Turns off logging completely
30
+ * OFF = 0,
31
+ * // For unexpected errors in Apify system
32
+ * ERROR = 1 = SeverityNumber.ERROR,
33
+ * // For situations where error is caused by user (e.g. Meteor.Error), i.e. when the error is not
34
+ * // caused by Apify system, avoid the word "ERROR" to simplify searching in log
35
+ * SOFT_FAIL = 2 = SeverityNumber.WARN,
36
+ * WARNING = 3 = SeverityNumber.WARN,
37
+ * INFO = 4 = SeverityNumber.INFO,
38
+ * DEBUG = 5 = SeverityNumber.DEBUG,
39
+ * // for performance stats
40
+ * PERF = 6 = SeverityNumber.DEBUG,
41
+ * }
42
+ * ```
43
+ */
44
+ export declare const apifyLogLevelMap: Record<number, SeverityNumber>;
45
+ /** Human readable Apify log level names, emitted as the `severityText` of the forwarded log records. */
46
+ export declare const apifyLogLevelNameMap: Record<number, string>;
47
+ /**
48
+ * The logging methods to instrument, with the level each logs at.
49
+ *
50
+ * These live on `BaseCrawleeLogger.prototype`, which every Crawlee logger derives from, so patching them forwards logs
51
+ * from any logger implementation - the default Apify one as well as a Winston, Pino or hand-written adapter. Each of
52
+ * them dispatches straight to the abstract `logWithLevel`, which the adapter implements, so a call is only seen once.
53
+ * `warningOnce` and `deprecated` are covered through `warning`.
54
+ */
55
+ export declare const loggerMethods: LoggerMethodDefinition[];
package/constants.js ADDED
@@ -0,0 +1,198 @@
1
+ import { SpanKind } from '@opentelemetry/api';
2
+ import { SeverityNumber } from '@opentelemetry/api-logs';
3
+ import { ATTR_HTTP_REQUEST_METHOD, ATTR_URL_FULL } from '@opentelemetry/semantic-conventions';
4
+ export const PACKAGE_NAME = '@crawlee/otel';
5
+ /** Used when the package version cannot be determined at runtime. */
6
+ export const UNKNOWN_PACKAGE_VERSION = '0.0.0';
7
+ /**
8
+ * Versions of the instrumented Crawlee packages this instrumentation knows how to patch. Methods that are missing
9
+ * in the resolved version are skipped with a warning instead of breaking the module load.
10
+ *
11
+ * Spelled out rather than written as `^4.0.0`, because a caret range never matches a prerelease and every published
12
+ * Crawlee v4 is one (`4.0.0-beta.x`, `4.0.0-rc.x`). The explicit `-0` bounds admit prereleases of 4.0.0 itself, and
13
+ * `includePrerelease` on the module definitions extends that to prereleases of later v4 minors.
14
+ *
15
+ * `@opentelemetry/instrumentation` only consults this when the loader hands it the module's base directory, which the
16
+ * ESM hook does not do - so today a wrong range here would not stop anything from being patched. It is still declared
17
+ * correctly rather than left as documentation: the range is what decides whether a module is patched as soon as a base
18
+ * directory is available, and being silently skipped is not a failure mode worth leaving armed.
19
+ */
20
+ export const SUPPORTED_CRAWLEE_VERSIONS = ['>=4.0.0-0 <5.0.0-0'];
21
+ export const baseConfig = {
22
+ enabled: true,
23
+ requestHandlingInstrumentation: true,
24
+ logInstrumentation: true,
25
+ customInstrumentation: [],
26
+ };
27
+ /**
28
+ * Extracts span attributes from a Crawlee crawling context. Uses the stable OpenTelemetry semantic conventions where
29
+ * they exist, so that traces stay comparable with other instrumented HTTP clients.
30
+ */
31
+ function requestAttributes(crawlingContext) {
32
+ const request = crawlingContext?.request;
33
+ // The context shape depends on the installed Crawlee version, so never assume the request is there.
34
+ if (!request) {
35
+ return {};
36
+ }
37
+ return {
38
+ 'crawlee.request.id': request.id,
39
+ [ATTR_URL_FULL]: request.url,
40
+ [ATTR_HTTP_REQUEST_METHOD]: request.method,
41
+ 'crawlee.request.retry_count': request.retryCount,
42
+ };
43
+ }
44
+ export const requestHandlingInstrumentationMethods = [
45
+ {
46
+ moduleName: '@crawlee/basic',
47
+ className: 'BasicCrawler',
48
+ methodName: 'run',
49
+ spanName: 'crawlee.crawler.run',
50
+ spanOptions() {
51
+ return {
52
+ attributes: {
53
+ 'crawlee.crawler.type': this.constructor.name,
54
+ },
55
+ };
56
+ },
57
+ },
58
+ {
59
+ moduleName: '@crawlee/basic',
60
+ className: 'BasicCrawler',
61
+ methodName: 'handleRequest',
62
+ spanName: 'crawlee.crawler.handleRequest',
63
+ // `handleRequest(crawlingContext, requestSource, request)`
64
+ spanOptions(crawlingContext) {
65
+ return { attributes: requestAttributes(crawlingContext) };
66
+ },
67
+ },
68
+ {
69
+ moduleName: '@crawlee/basic',
70
+ className: 'BasicCrawler',
71
+ methodName: 'runRequestHandler',
72
+ spanName: 'crawlee.crawler.runRequestHandler',
73
+ spanOptions(crawlingContext) {
74
+ return { attributes: requestAttributes(crawlingContext) };
75
+ },
76
+ },
77
+ {
78
+ // `AdaptivePlaywrightCrawler` replaces `runRequestHandler` outright instead of calling `super`, so the
79
+ // `BasicCrawler` patch above never fires for it. `BrowserCrawler` does call `super`, which is why it needs
80
+ // no entry of its own.
81
+ moduleName: '@crawlee/playwright',
82
+ className: 'AdaptivePlaywrightCrawler',
83
+ methodName: 'runRequestHandler',
84
+ spanName: 'crawlee.crawler.runRequestHandler',
85
+ spanOptions(crawlingContext) {
86
+ return { attributes: requestAttributes(crawlingContext) };
87
+ },
88
+ },
89
+ {
90
+ moduleName: '@crawlee/basic',
91
+ className: 'BasicCrawler',
92
+ methodName: 'requestFunctionErrorHandler',
93
+ spanName: 'crawlee.crawler.requestFunctionErrorHandler',
94
+ // `requestFunctionErrorHandler(error, crawlingContext, request, source)`
95
+ spanOptions(_error, crawlingContext) {
96
+ return { attributes: requestAttributes(crawlingContext) };
97
+ },
98
+ },
99
+ {
100
+ moduleName: '@crawlee/basic',
101
+ className: 'BasicCrawler',
102
+ methodName: 'handleFailedRequestHandler',
103
+ spanName: 'crawlee.crawler.handleFailedRequestHandler',
104
+ spanOptions(crawlingContext) {
105
+ return { attributes: requestAttributes(crawlingContext) };
106
+ },
107
+ },
108
+ {
109
+ moduleName: '@crawlee/http',
110
+ className: 'HttpCrawler',
111
+ methodName: 'makeHttpRequest',
112
+ spanName: 'crawlee.http.makeHttpRequest',
113
+ spanOptions(crawlingContext) {
114
+ // An outbound HTTP call, so a client span rather than the default internal one.
115
+ return { kind: SpanKind.CLIENT, attributes: requestAttributes(crawlingContext) };
116
+ },
117
+ },
118
+ {
119
+ moduleName: '@crawlee/browser',
120
+ className: 'BrowserCrawler',
121
+ methodName: 'navigate',
122
+ spanName: 'crawlee.browser.navigate',
123
+ spanOptions(crawlingContext) {
124
+ // The browser navigation is the outbound call here.
125
+ return { kind: SpanKind.CLIENT, attributes: requestAttributes(crawlingContext) };
126
+ },
127
+ },
128
+ ];
129
+ /**
130
+ * Maps Apify log levels to OpenTelemetry severity numbers.
131
+ * See https://github.com/apify/apify-shared-js/blob/83d46cf72a338ff671f89dcbc2b0db7dd571e29f/packages/log/src/log_consts.ts#L1
132
+ *
133
+ * ```typescript
134
+ * export enum LogLevel {
135
+ * // Turns off logging completely
136
+ * OFF = 0,
137
+ * // For unexpected errors in Apify system
138
+ * ERROR = 1 = SeverityNumber.ERROR,
139
+ * // For situations where error is caused by user (e.g. Meteor.Error), i.e. when the error is not
140
+ * // caused by Apify system, avoid the word "ERROR" to simplify searching in log
141
+ * SOFT_FAIL = 2 = SeverityNumber.WARN,
142
+ * WARNING = 3 = SeverityNumber.WARN,
143
+ * INFO = 4 = SeverityNumber.INFO,
144
+ * DEBUG = 5 = SeverityNumber.DEBUG,
145
+ * // for performance stats
146
+ * PERF = 6 = SeverityNumber.DEBUG,
147
+ * }
148
+ * ```
149
+ */
150
+ export const apifyLogLevelMap = {
151
+ 1: SeverityNumber.ERROR,
152
+ 2: SeverityNumber.WARN,
153
+ 3: SeverityNumber.WARN,
154
+ 4: SeverityNumber.INFO,
155
+ 5: SeverityNumber.DEBUG,
156
+ 6: SeverityNumber.DEBUG,
157
+ };
158
+ /** Human readable Apify log level names, emitted as the `severityText` of the forwarded log records. */
159
+ export const apifyLogLevelNameMap = {
160
+ 1: 'ERROR',
161
+ 2: 'SOFT_FAIL',
162
+ 3: 'WARNING',
163
+ 4: 'INFO',
164
+ 5: 'DEBUG',
165
+ 6: 'PERF',
166
+ };
167
+ /**
168
+ * The logging methods to instrument, with the level each logs at.
169
+ *
170
+ * These live on `BaseCrawleeLogger.prototype`, which every Crawlee logger derives from, so patching them forwards logs
171
+ * from any logger implementation - the default Apify one as well as a Winston, Pino or hand-written adapter. Each of
172
+ * them dispatches straight to the abstract `logWithLevel`, which the adapter implements, so a call is only seen once.
173
+ * `warningOnce` and `deprecated` are covered through `warning`.
174
+ */
175
+ export const loggerMethods = [
176
+ { methodName: 'error', level: 1, read: (args) => readMessageAndData(args) },
177
+ {
178
+ methodName: 'exception',
179
+ level: 1,
180
+ // `exception(exception, message, data)` - the error comes first.
181
+ read: (args) => ({
182
+ message: String(args[1] ?? ''),
183
+ data: { ...args[2], exception: args[0] },
184
+ }),
185
+ },
186
+ { methodName: 'softFail', level: 2, read: (args) => readMessageAndData(args) },
187
+ { methodName: 'warning', level: 3, read: (args) => readMessageAndData(args) },
188
+ { methodName: 'info', level: 4, read: (args) => readMessageAndData(args) },
189
+ { methodName: 'debug', level: 5, read: (args) => readMessageAndData(args) },
190
+ { methodName: 'perf', level: 6, read: (args) => readMessageAndData(args) },
191
+ ];
192
+ /** The shape shared by every logging method except `exception`: `(message, data?)`. */
193
+ function readMessageAndData(args) {
194
+ return {
195
+ message: String(args[0] ?? ''),
196
+ data: args[1],
197
+ };
198
+ }
package/index.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ export { CrawleeInstrumentation } from './instrumentation.js';
2
+ export type * from './types.js';
3
+ export { wrapWithSpan } from './wrapWithSpan.js';
package/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { CrawleeInstrumentation } from './instrumentation.js';
2
+ export { wrapWithSpan } from './wrapWithSpan.js';
@@ -0,0 +1,37 @@
1
+ import type { TracerProvider } from '@opentelemetry/api';
2
+ import type { InstrumentationModuleDefinition } from '@opentelemetry/instrumentation';
3
+ import { InstrumentationBase } from '@opentelemetry/instrumentation';
4
+ import type { CrawleeInstrumentationConfig } from './types.js';
5
+ export declare class CrawleeInstrumentation extends InstrumentationBase<CrawleeInstrumentationConfig> {
6
+ constructor(config?: CrawleeInstrumentationConfig);
7
+ /**
8
+ * Shares the tracer with the exported `wrapWithSpan` helper, so that manually wrapped handlers end up in the same
9
+ * instrumentation scope as the automatic spans.
10
+ *
11
+ * This has to happen here rather than in the constructor. The constructor can only reach the tracer of the global
12
+ * API, and that is not necessarily the one this instrumentation ends up using - a `tracerProvider` passed to
13
+ * `registerInstrumentations` is never registered globally, and a duplicated `@opentelemetry/api` in the dependency
14
+ * tree has its own global. Handing over a tracer from the wrong provider silences every span, including the
15
+ * automatic ones, and because it is not `undefined` it also shadows the fallback in `wrapWithSpan`.
16
+ */
17
+ setTracerProvider(tracerProvider: TracerProvider): void;
18
+ protected init(): InstrumentationModuleDefinition[];
19
+ private instantiateModuleDefinitions;
20
+ /**
21
+ * Resolves the prototype holding the method to patch, warning instead of throwing when the class or the method
22
+ * is not there - a missing internal method must not break loading of the instrumented module.
23
+ */
24
+ private getPrototype;
25
+ /** Mirrors {@link getPrototype}: only methods that were actually patched are restored. */
26
+ private unwrapIfWrapped;
27
+ private applyClassMethodPatch;
28
+ private getLogPatch;
29
+ /**
30
+ * Emits one Crawlee log call as an OpenTelemetry log record.
31
+ *
32
+ * Everything here - reading the arguments, stringifying the message, handing the record to the SDK - runs inside
33
+ * the application's own call to `log.info()` and friends, so a failure anywhere in it is reported and dropped
34
+ * rather than raised.
35
+ */
36
+ private forwardLogRecord;
37
+ }
@@ -0,0 +1,167 @@
1
+ import { SeverityNumber } from '@opentelemetry/api-logs';
2
+ import { InstrumentationBase, InstrumentationNodeModuleDefinition, isWrapped } from '@opentelemetry/instrumentation';
3
+ import { ATTR_CODE_FUNCTION_NAME } from '@opentelemetry/semantic-conventions';
4
+ import { apifyLogLevelMap, apifyLogLevelNameMap, baseConfig, loggerMethods, PACKAGE_NAME, requestHandlingInstrumentationMethods, SUPPORTED_CRAWLEE_VERSIONS, } from './constants.js';
5
+ import { buildLogAttributes, buildModuleDefinitions, getPackageVersion } from './utilities.js';
6
+ import { resolveSpanName, resolveSpanOptions, setSharedTracer, wrapWithSpan } from './wrapWithSpan.js';
7
+ /**
8
+ * Builds a module definition for one of the instrumented Crawlee packages.
9
+ *
10
+ * `InstrumentationNodeModuleDefinition` does not take `includePrerelease` through its constructor, but
11
+ * `InstrumentationBase` reads it off the definition when it decides whether to patch a resolved module version, so it
12
+ * is set here. Without it, {@link SUPPORTED_CRAWLEE_VERSIONS} would only cover prereleases of `4.0.0` and every
13
+ * `4.x.0-beta` would go uninstrumented.
14
+ */
15
+ function crawleeModuleDefinition(moduleName, patch, unpatch) {
16
+ const definition = new InstrumentationNodeModuleDefinition(moduleName, SUPPORTED_CRAWLEE_VERSIONS, patch, unpatch);
17
+ definition.includePrerelease = true;
18
+ return definition;
19
+ }
20
+ export class CrawleeInstrumentation extends InstrumentationBase {
21
+ constructor(config = {}) {
22
+ // Each flag is resolved on its own rather than by spreading `config` over `baseConfig`: a spread lets an
23
+ // explicit `undefined` - which is what `{ logInstrumentation: options.logs }` produces when `options.logs`
24
+ // is not set - overwrite the default with nothing and quietly disable the feature.
25
+ super(PACKAGE_NAME, getPackageVersion(), {
26
+ ...config,
27
+ enabled: config.enabled ?? baseConfig.enabled,
28
+ requestHandlingInstrumentation: config.requestHandlingInstrumentation ?? baseConfig.requestHandlingInstrumentation,
29
+ logInstrumentation: config.logInstrumentation ?? baseConfig.logInstrumentation,
30
+ customInstrumentation: config.customInstrumentation ?? baseConfig.customInstrumentation,
31
+ });
32
+ }
33
+ /**
34
+ * Shares the tracer with the exported `wrapWithSpan` helper, so that manually wrapped handlers end up in the same
35
+ * instrumentation scope as the automatic spans.
36
+ *
37
+ * This has to happen here rather than in the constructor. The constructor can only reach the tracer of the global
38
+ * API, and that is not necessarily the one this instrumentation ends up using - a `tracerProvider` passed to
39
+ * `registerInstrumentations` is never registered globally, and a duplicated `@opentelemetry/api` in the dependency
40
+ * tree has its own global. Handing over a tracer from the wrong provider silences every span, including the
41
+ * automatic ones, and because it is not `undefined` it also shadows the fallback in `wrapWithSpan`.
42
+ */
43
+ setTracerProvider(tracerProvider) {
44
+ super.setTracerProvider(tracerProvider);
45
+ setSharedTracer(this.tracer);
46
+ }
47
+ init() {
48
+ const methodsToInstrument = [...(this.getConfig().customInstrumentation ?? [])];
49
+ if (this.getConfig().requestHandlingInstrumentation) {
50
+ methodsToInstrument.push(...requestHandlingInstrumentationMethods);
51
+ }
52
+ const moduleDefinitions = buildModuleDefinitions(methodsToInstrument);
53
+ const definitions = this.instantiateModuleDefinitions(moduleDefinitions);
54
+ if (this.getConfig().logInstrumentation) {
55
+ definitions.push(crawleeModuleDefinition('@crawlee/core', (moduleExports) => {
56
+ for (const method of loggerMethods) {
57
+ const prototype = this.getPrototype(moduleExports, '@crawlee/core', 'BaseCrawleeLogger', method.methodName);
58
+ if (prototype) {
59
+ this._wrap(prototype, method.methodName, this.getLogPatch(method));
60
+ }
61
+ }
62
+ return moduleExports;
63
+ }, (moduleExports) => {
64
+ for (const method of loggerMethods) {
65
+ this.unwrapIfWrapped(moduleExports?.BaseCrawleeLogger?.prototype, method.methodName);
66
+ }
67
+ return moduleExports;
68
+ }));
69
+ }
70
+ return definitions;
71
+ }
72
+ instantiateModuleDefinitions(moduleDefinitions) {
73
+ return moduleDefinitions.map((definition) => {
74
+ return crawleeModuleDefinition(definition.moduleName, (moduleExports) => {
75
+ for (const patch of definition.classMethodPatches) {
76
+ const prototype = this.getPrototype(moduleExports, definition.moduleName, patch.className, patch.methodName);
77
+ if (prototype) {
78
+ this._wrap(prototype, patch.methodName, this.applyClassMethodPatch(patch));
79
+ }
80
+ }
81
+ return moduleExports;
82
+ }, (moduleExports) => {
83
+ for (const patch of definition.classMethodPatches) {
84
+ this.unwrapIfWrapped(moduleExports?.[patch.className]?.prototype, patch.methodName);
85
+ }
86
+ return moduleExports;
87
+ });
88
+ });
89
+ }
90
+ /**
91
+ * Resolves the prototype holding the method to patch, warning instead of throwing when the class or the method
92
+ * is not there - a missing internal method must not break loading of the instrumented module.
93
+ */
94
+ getPrototype(moduleExports, moduleName, className, methodName) {
95
+ const prototype = moduleExports?.[className]?.prototype;
96
+ if (typeof prototype?.[methodName] !== 'function') {
97
+ this._diag.warn(`Skipping instrumentation of ${moduleName}: ${className}.${methodName} was not found. ` +
98
+ `The installed version of ${moduleName} is probably not supported by ${PACKAGE_NAME}.`);
99
+ return undefined;
100
+ }
101
+ return prototype;
102
+ }
103
+ /** Mirrors {@link getPrototype}: only methods that were actually patched are restored. */
104
+ unwrapIfWrapped(prototype, methodName) {
105
+ if (prototype && isWrapped(prototype[methodName])) {
106
+ this._unwrap(prototype, methodName);
107
+ }
108
+ }
109
+ applyClassMethodPatch(patch) {
110
+ const { spanName, spanOptions } = patch;
111
+ const qualifiedName = `${patch.className}.${patch.methodName}`;
112
+ const codeAttributes = { [ATTR_CODE_FUNCTION_NAME]: qualifiedName };
113
+ // Both options are resolved through the guarded helpers, so that a throwing callback costs only what the
114
+ // caller supplied - the span itself, its name and the attributes added here all survive.
115
+ return function wrap(original) {
116
+ return wrapWithSpan(original, {
117
+ spanName(...args) {
118
+ return resolveSpanName(spanName, qualifiedName, this, args);
119
+ },
120
+ spanOptions(...args) {
121
+ const resolved = resolveSpanOptions(spanOptions, this, args);
122
+ return { ...resolved, attributes: { ...codeAttributes, ...resolved.attributes } };
123
+ },
124
+ });
125
+ };
126
+ }
127
+ getLogPatch(method) {
128
+ // oxlint-disable-next-line no-this-alias
129
+ const instrumentation = this;
130
+ return function wrapLog(original) {
131
+ return function wrappedLog(...args) {
132
+ // The application's own logging runs first and its outcome is never affected by the forwarding,
133
+ // which matters most where Crawlee logs from inside a `catch` - `handleFailedRequestHandler`.
134
+ // These methods are synchronous and return void, so keep them that way.
135
+ try {
136
+ original.apply(this, args);
137
+ }
138
+ finally {
139
+ instrumentation.forwardLogRecord(method, args);
140
+ }
141
+ };
142
+ };
143
+ }
144
+ /**
145
+ * Emits one Crawlee log call as an OpenTelemetry log record.
146
+ *
147
+ * Everything here - reading the arguments, stringifying the message, handing the record to the SDK - runs inside
148
+ * the application's own call to `log.info()` and friends, so a failure anywhere in it is reported and dropped
149
+ * rather than raised.
150
+ */
151
+ forwardLogRecord(method, args) {
152
+ try {
153
+ const { message, data } = method.read(args);
154
+ // Crawlee leaves level filtering to the logging library, so everything is forwarded and the
155
+ // OpenTelemetry pipeline decides what to keep.
156
+ this.logger.emit({
157
+ severityNumber: apifyLogLevelMap[method.level] ?? SeverityNumber.UNSPECIFIED,
158
+ severityText: apifyLogLevelNameMap[method.level],
159
+ body: message,
160
+ attributes: buildLogAttributes(data),
161
+ });
162
+ }
163
+ catch (err) {
164
+ this._diag.warn(`Failed to forward a Crawlee log record to OpenTelemetry: ${err}`);
165
+ }
166
+ }
167
+ }
@@ -0,0 +1,39 @@
1
+ import type { ClassMethodToInstrument } from './types.js';
2
+ /** The patches of one instrumented module, as produced by {@link buildModuleDefinitions}. */
3
+ export interface ModuleDefinition {
4
+ moduleName: string;
5
+ classMethodPatches: ClassMethodPatchDefinition[];
6
+ }
7
+ /**
8
+ * A {@link ClassMethodToInstrument} that has already been grouped under its module, so the module name would be
9
+ * redundant. Derived from the public type rather than restated, so the fields and their documentation have one home.
10
+ */
11
+ export type ClassMethodPatchDefinition = Omit<ClassMethodToInstrument, 'moduleName'>;
12
+ /**
13
+ * The fields of a Crawlee `Request` this instrumentation reads.
14
+ *
15
+ * Deliberately structural rather than imported from `@crawlee/core`: the instrumented Crawlee version is resolved at
16
+ * runtime and may not be the one this package was compiled against, so every field is treated as optional.
17
+ */
18
+ export interface RequestLike {
19
+ id?: string;
20
+ url?: string;
21
+ method?: string;
22
+ retryCount?: number;
23
+ }
24
+ /** The part of a Crawlee crawling context this instrumentation reads. */
25
+ export interface CrawlingContextLike {
26
+ request?: RequestLike;
27
+ }
28
+ /** One of the logging methods `BaseCrawleeLogger` provides, and how to read a log record out of a call to it. */
29
+ export interface LoggerMethodDefinition {
30
+ /** The method on `BaseCrawleeLogger.prototype` to patch. */
31
+ methodName: string;
32
+ /** The Crawlee log level this method logs at. */
33
+ level: number;
34
+ /** Pulls the message and the structured data out of the call arguments, which differ per method. */
35
+ read: (args: unknown[]) => {
36
+ message: string;
37
+ data?: Record<string, unknown>;
38
+ };
39
+ }
@@ -0,0 +1 @@
1
+ export {};
package/package.json ADDED
@@ -0,0 +1,56 @@
1
+ {
2
+ "name": "@crawlee/otel",
3
+ "version": "4.0.0-beta.156",
4
+ "description": "OpenTelemetry instrumentation for Crawlee",
5
+ "engines": {
6
+ "node": ">=22.0.0"
7
+ },
8
+ "type": "module",
9
+ "exports": {
10
+ ".": "./index.js",
11
+ "./package.json": "./package.json"
12
+ },
13
+ "keywords": [
14
+ "apify",
15
+ "api",
16
+ "otel",
17
+ "opentelemetry"
18
+ ],
19
+ "author": {
20
+ "name": "Apify",
21
+ "email": "support@apify.com",
22
+ "url": "https://apify.com"
23
+ },
24
+ "contributors": [],
25
+ "license": "Apache-2.0",
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "git+https://github.com/apify/crawlee"
29
+ },
30
+ "bugs": {
31
+ "url": "https://github.com/apify/crawlee/issues"
32
+ },
33
+ "homepage": "https://crawlee.dev",
34
+ "publishConfig": {
35
+ "access": "public"
36
+ },
37
+ "dependencies": {
38
+ "@opentelemetry/instrumentation": "^0.210.0",
39
+ "@opentelemetry/semantic-conventions": "^1.39.0"
40
+ },
41
+ "peerDependencies": {
42
+ "@opentelemetry/api": "^1.3.0",
43
+ "@opentelemetry/api-logs": "^0.210.0"
44
+ },
45
+ "devDependencies": {
46
+ "@opentelemetry/api": "^1.9.0",
47
+ "@opentelemetry/api-logs": "^0.210.0",
48
+ "semver": "^7.7.0"
49
+ },
50
+ "scripts": {
51
+ "build": "pnpm clean && pnpm compile && pnpm copy",
52
+ "clean": "rimraf ./dist",
53
+ "compile": "tsc -p tsconfig.build.json",
54
+ "copy": "tsx ../../scripts/copy.ts"
55
+ }
56
+ }
package/types.d.ts ADDED
@@ -0,0 +1,25 @@
1
+ import type { SpanOptions } from '@opentelemetry/api';
2
+ import type { InstrumentationConfig } from '@opentelemetry/instrumentation';
3
+ export interface CrawleeInstrumentationConfig extends InstrumentationConfig {
4
+ requestHandlingInstrumentation?: boolean;
5
+ logInstrumentation?: boolean;
6
+ customInstrumentation?: ClassMethodToInstrument[];
7
+ }
8
+ /** One class method to wrap in a span, and the module that has to be loaded for it to exist. */
9
+ export interface ClassMethodToInstrument {
10
+ /** The Crawlee package the class is exported from, for example `@crawlee/basic`. */
11
+ moduleName: string;
12
+ /** The class name to patch. */
13
+ className: string;
14
+ /** The method name to patch. */
15
+ methodName: string;
16
+ /**
17
+ * The name of the span. Defaults to `className.methodName`.
18
+ *
19
+ * When given a function, it is called with the arguments of the patched method, and `this` is the instance the
20
+ * method was called on. The arguments are `any` because they are whatever the patched method receives.
21
+ */
22
+ spanName?: string | ((this: any, ...args: any[]) => string);
23
+ /** The attributes of the span. Follows the same calling convention as {@link ClassMethodToInstrument.spanName}. */
24
+ spanOptions?: SpanOptions | ((this: any, ...args: any[]) => SpanOptions);
25
+ }
package/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/utilities.d.ts ADDED
@@ -0,0 +1,18 @@
1
+ import type { LogAttributes } from '@opentelemetry/api-logs';
2
+ import type { ModuleDefinition } from './internal-types.js';
3
+ import type { ClassMethodToInstrument } from './types.js';
4
+ export declare function getPackageVersion(): string;
5
+ /**
6
+ * Turns the structured `data` of a Crawlee log call into OpenTelemetry log attributes.
7
+ *
8
+ * Crawlee folds a logged error into `data`, so any `Error` value found there is mapped onto the semantic convention
9
+ * attributes - its own properties are not enumerable and would otherwise be dropped.
10
+ */
11
+ export declare function buildLogAttributes(data?: unknown): LogAttributes;
12
+ /**
13
+ * Groups the methods to instrument by the module that owns them, dropping duplicates.
14
+ *
15
+ * The first definition of a method wins. `CrawleeInstrumentation` passes `customInstrumentation` ahead of the built-in
16
+ * list, so configuring a method that is already instrumented overrides the built-in span rather than being ignored.
17
+ */
18
+ export declare function buildModuleDefinitions(methodsToInstrument: ClassMethodToInstrument[]): ModuleDefinition[];
package/utilities.js ADDED
@@ -0,0 +1,88 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { createRequire } from 'node:module';
3
+ import { diag } from '@opentelemetry/api';
4
+ import { ATTR_EXCEPTION_MESSAGE, ATTR_EXCEPTION_STACKTRACE, ATTR_EXCEPTION_TYPE, } from '@opentelemetry/semantic-conventions';
5
+ import { PACKAGE_NAME, UNKNOWN_PACKAGE_VERSION } from './constants.js';
6
+ let packageFile;
7
+ function getPackageJson() {
8
+ if (!packageFile) {
9
+ try {
10
+ // The package is ESM, so `require` has to be recreated from the module URL.
11
+ const packageFilePath = createRequire(import.meta.url).resolve(`${PACKAGE_NAME}/package.json`);
12
+ packageFile = JSON.parse(readFileSync(packageFilePath, 'utf8'));
13
+ }
14
+ catch (err) {
15
+ // The version is only reported as the instrumentation scope version, so a failure here must not be fatal.
16
+ diag.warn(`Could not determine the ${PACKAGE_NAME} version: ${err}`);
17
+ packageFile = { version: UNKNOWN_PACKAGE_VERSION };
18
+ }
19
+ }
20
+ return packageFile;
21
+ }
22
+ export function getPackageVersion() {
23
+ return getPackageJson().version;
24
+ }
25
+ /**
26
+ * Turns the structured `data` of a Crawlee log call into OpenTelemetry log attributes.
27
+ *
28
+ * Crawlee folds a logged error into `data`, so any `Error` value found there is mapped onto the semantic convention
29
+ * attributes - its own properties are not enumerable and would otherwise be dropped.
30
+ */
31
+ export function buildLogAttributes(data) {
32
+ const attributes = {};
33
+ if (typeof data !== 'object' || data === null || Array.isArray(data)) {
34
+ if (data !== undefined) {
35
+ attributes['crawlee.log.data'] = String(data);
36
+ }
37
+ return attributes;
38
+ }
39
+ for (const [key, value] of Object.entries(data)) {
40
+ if (value instanceof Error) {
41
+ attributes[ATTR_EXCEPTION_TYPE] = value.name;
42
+ attributes[ATTR_EXCEPTION_MESSAGE] = value.message;
43
+ if (value.stack) {
44
+ attributes[ATTR_EXCEPTION_STACKTRACE] = value.stack;
45
+ }
46
+ }
47
+ else {
48
+ attributes[key] = value;
49
+ }
50
+ }
51
+ return attributes;
52
+ }
53
+ /**
54
+ * Groups the methods to instrument by the module that owns them, dropping duplicates.
55
+ *
56
+ * The first definition of a method wins. `CrawleeInstrumentation` passes `customInstrumentation` ahead of the built-in
57
+ * list, so configuring a method that is already instrumented overrides the built-in span rather than being ignored.
58
+ */
59
+ export function buildModuleDefinitions(methodsToInstrument) {
60
+ const definitions = [];
61
+ for (const method of methodsToInstrument) {
62
+ let definition = definitions.find((d) => d.moduleName === method.moduleName);
63
+ if (!definition) {
64
+ if (!method.moduleName.startsWith('@crawlee/')) {
65
+ diag.warn(`Module ${method.moduleName} is not a valid Crawlee module. Skipping.`);
66
+ continue;
67
+ }
68
+ definition = {
69
+ moduleName: method.moduleName,
70
+ classMethodPatches: [],
71
+ };
72
+ definitions.push(definition);
73
+ }
74
+ if (!definition.classMethodPatches.find((p) => p.className === method.className && p.methodName === method.methodName)) {
75
+ definition.classMethodPatches.push({
76
+ className: method.className,
77
+ methodName: method.methodName,
78
+ spanName: method.spanName,
79
+ spanOptions: method.spanOptions,
80
+ });
81
+ }
82
+ else {
83
+ diag.warn(`Method ${method.className}.${method.methodName} is instrumented more than once. Keeping the first ` +
84
+ `definition, which is the \`customInstrumentation\` entry when one exists for the method.`);
85
+ }
86
+ }
87
+ return definitions;
88
+ }
@@ -0,0 +1,33 @@
1
+ import type { SpanOptions, Tracer } from '@opentelemetry/api';
2
+ /**
3
+ * Points the exported {@link wrapWithSpan} at a tracer, or back at the global API when passed `undefined`.
4
+ *
5
+ * @internal
6
+ */
7
+ export declare function setSharedTracer(tracer: Tracer | undefined): void;
8
+ /**
9
+ * Wraps a function with OpenTelemetry span instrumentation.
10
+ *
11
+ * `Args` and `Return` are separate generics so that the argument types flow through to the `spanName` and `spanOptions`
12
+ * callbacks. They are inferred from the wrapped function, so annotate its parameters when assigning the result to an
13
+ * option whose type is a union - `requestHandler` accepts both a router and a plain handler, and TypeScript cannot
14
+ * infer parameter types through a union of function types:
15
+ *
16
+ * ```ts
17
+ * requestHandler: wrapWithSpan(async ({ request }: CheerioCrawlingContext) => { ... })
18
+ * ```
19
+ *
20
+ * Synchronous functions stay synchronous, asynchronous ones keep their span open until the returned promise settles.
21
+ *
22
+ * The wrapper forwards its own `this` to the wrapped function, so a method keeps working when wrapped. An arrow
23
+ * function still ignores it, as arrow functions always take `this` from where they were defined.
24
+ */
25
+ export declare function wrapWithSpan<Args extends unknown[], Return>(fn: (...args: Args) => Return, options?: {
26
+ spanName?: string | ((...args: Args) => string);
27
+ spanOptions?: SpanOptions | ((...args: Args) => SpanOptions);
28
+ tracer?: Tracer;
29
+ }): (...args: Args) => Return;
30
+ /** @internal Shared with `CrawleeInstrumentation`, which supplies a class qualified default. */
31
+ export declare function resolveSpanName<Args extends unknown[]>(spanName: string | ((...args: Args) => string) | undefined, fallback: string, thisArg: unknown, args: Args): string;
32
+ /** @internal Shared with `CrawleeInstrumentation`, which merges its own attributes into the resolved options. */
33
+ export declare function resolveSpanOptions<Args extends unknown[]>(spanOptions: SpanOptions | ((...args: Args) => SpanOptions) | undefined, thisArg: unknown, args: Args): SpanOptions;
@@ -0,0 +1,111 @@
1
+ import { diag, SpanStatusCode, trace } from '@opentelemetry/api';
2
+ import { PACKAGE_NAME } from './constants.js';
3
+ import { getPackageVersion } from './utilities.js';
4
+ /**
5
+ * The tracer `CrawleeInstrumentation` hands over once it knows which provider it ended up with, so that manually
6
+ * wrapped handlers share the instrumentation scope of the automatic spans.
7
+ *
8
+ * Module level state, because `wrapWithSpan` is called from user code that holds no reference to the instrumentation.
9
+ */
10
+ let sharedTracer;
11
+ /**
12
+ * Points the exported {@link wrapWithSpan} at a tracer, or back at the global API when passed `undefined`.
13
+ *
14
+ * @internal
15
+ */
16
+ export function setSharedTracer(tracer) {
17
+ sharedTracer = tracer;
18
+ }
19
+ /**
20
+ * Wraps a function with OpenTelemetry span instrumentation.
21
+ *
22
+ * `Args` and `Return` are separate generics so that the argument types flow through to the `spanName` and `spanOptions`
23
+ * callbacks. They are inferred from the wrapped function, so annotate its parameters when assigning the result to an
24
+ * option whose type is a union - `requestHandler` accepts both a router and a plain handler, and TypeScript cannot
25
+ * infer parameter types through a union of function types:
26
+ *
27
+ * ```ts
28
+ * requestHandler: wrapWithSpan(async ({ request }: CheerioCrawlingContext) => { ... })
29
+ * ```
30
+ *
31
+ * Synchronous functions stay synchronous, asynchronous ones keep their span open until the returned promise settles.
32
+ *
33
+ * The wrapper forwards its own `this` to the wrapped function, so a method keeps working when wrapped. An arrow
34
+ * function still ignores it, as arrow functions always take `this` from where they were defined.
35
+ */
36
+ export function wrapWithSpan(fn, options) {
37
+ return function (...args) {
38
+ // Resolving the tracer lazily lets `CrawleeInstrumentation` hand over its tracer at any point. When no
39
+ // instrumentation is registered, we fall back to the global API, which returns a tracer that either
40
+ // delegates to the globally registered provider or is a no-op - so wrapping never fails on its own.
41
+ const tracer = options?.tracer ?? sharedTracer ?? trace.getTracer(PACKAGE_NAME, getPackageVersion());
42
+ const spanName = resolveSpanName(options?.spanName, fn.name || 'anonymous', this, args);
43
+ const spanOptions = resolveSpanOptions(options?.spanOptions, this, args);
44
+ return tracer.startActiveSpan(spanName, spanOptions, (span) => {
45
+ let result;
46
+ try {
47
+ result = fn.apply(this, args);
48
+ }
49
+ catch (err) {
50
+ recordError(span, err);
51
+ span.end();
52
+ throw err;
53
+ }
54
+ // Only defer ending the span when the wrapped function is actually asynchronous, so that wrapping
55
+ // a synchronous function does not silently turn it into a promise-returning one.
56
+ if (!isPromiseLike(result)) {
57
+ span.end();
58
+ return result;
59
+ }
60
+ return Promise.resolve(result).then((value) => {
61
+ span.end();
62
+ return value;
63
+ }, (err) => {
64
+ recordError(span, err);
65
+ span.end();
66
+ throw err;
67
+ });
68
+ });
69
+ };
70
+ }
71
+ /** @internal Shared with `CrawleeInstrumentation`, which supplies a class qualified default. */
72
+ export function resolveSpanName(spanName, fallback, thisArg, args) {
73
+ if (typeof spanName === 'function') {
74
+ return callSpanOption(spanName, fallback, thisArg, args, 'spanName');
75
+ }
76
+ return spanName ?? fallback;
77
+ }
78
+ /** @internal Shared with `CrawleeInstrumentation`, which merges its own attributes into the resolved options. */
79
+ export function resolveSpanOptions(spanOptions, thisArg, args) {
80
+ if (typeof spanOptions === 'function') {
81
+ return callSpanOption(spanOptions, {}, thisArg, args, 'spanOptions');
82
+ }
83
+ return spanOptions ?? {};
84
+ }
85
+ /**
86
+ * Calls a `spanName` or `spanOptions` callback supplied by the caller.
87
+ *
88
+ * These run inside the call path of the wrapped function, so a mistake in one must not turn into a failure of the
89
+ * function being instrumented - the span is created with the default instead.
90
+ */
91
+ function callSpanOption(callback, fallback, thisArg, args, optionName) {
92
+ try {
93
+ return callback.apply(thisArg, args);
94
+ }
95
+ catch (err) {
96
+ diag.warn(`The ${optionName} callback of a ${PACKAGE_NAME} span threw, using the default instead: ${err}`);
97
+ return fallback;
98
+ }
99
+ }
100
+ function isPromiseLike(value) {
101
+ return typeof value?.then === 'function';
102
+ }
103
+ function recordError(span, err) {
104
+ span.recordException(err);
105
+ // Per the OpenTelemetry specification, instrumentation only sets the status on failure and leaves successful
106
+ // spans `UNSET` - marking them `OK` would prevent consumers from overriding the status themselves.
107
+ span.setStatus({
108
+ code: SpanStatusCode.ERROR,
109
+ message: err instanceof Error ? err.message : String(err),
110
+ });
111
+ }