@ohos-ports/polarsignals-pprof 0.1.3-beta.0

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 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 [yyyy] [name of copyright owner]
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,64 @@
1
+ # @polarsignals/pprof
2
+
3
+ Node.js profiling library that automatically uploads heap profiles to Polar Signals.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @polarsignals/pprof
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```javascript
14
+ const { heapProfiler, monitorOutOfMemory } = require('@polarsignals/pprof');
15
+
16
+ // Start heap profiling
17
+ heapProfiler.start(512 * 1024, 64); // 512KB sampling, stack depth 64
18
+
19
+ // Monitor for out-of-memory events and auto-upload profiles
20
+ monitorOutOfMemory({
21
+ exportOptions: {
22
+ labels: { service: 'my-app', version: '1.0.0' },
23
+ },
24
+ });
25
+
26
+ // Resolve frames locally against .map files; skips server-side resolution.
27
+ const profile = await heapProfiler.encodedProfile({
28
+ localSourceMapRoots: [process.cwd()],
29
+ });
30
+ ```
31
+
32
+ `endpoint`, `projectId`, and `token` fall back to `POLARSIGNALS_SERVER_URL`,
33
+ `POLARSIGNALS_PROJECT_ID`, and `POLARSIGNALS_TOKEN` env vars respectively, so
34
+ typical deployments don't need to set them in code.
35
+
36
+ ## `exportOptions`
37
+
38
+ | Field | Type | Default | Description |
39
+ | ------------ | ------------------------ | ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
40
+ | Field | Type | Default | Description |
41
+ | --------------------- | ------------------------ | ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
42
+ | `endpoint` | `string` | `https://api.polarsignals.com/api/parca/profilestore` | Profile-store base URL. |
43
+ | `projectId` | `string` | `$POLARSIGNALS_PROJECT_ID` | Polar Signals project UUID. |
44
+ | `labels` | `Record<string, string>` | — | Extra series labels attached to the profile (e.g. `service`, `version`). |
45
+ | `headers` | `Record<string, string>` | — | Extra HTTP headers added to the upload request. |
46
+ | `timeout` | `number` | `30000` | Request timeout in ms. |
47
+ | `localSourceMapRoots` | `string[]` | — | If set, the OOM upload-worker resolves frames against `.map` files in these dirs and skips server-side resolution. The same option is available on `heapProfiler.encodedProfile` — see below. |
48
+
49
+ The bearer token is read exclusively from `POLARSIGNALS_TOKEN` env var.
50
+
51
+ ## `heapProfiler.encodedProfile(options?)`
52
+
53
+ Returns a gzipped pprof Buffer for ad-hoc serving (e.g. a `/debug/pprof/allocs` endpoint).
54
+
55
+ | Field | Type | Default | Description |
56
+ | --------------------- | ---------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
57
+ | `localSourceMapRoots` | `string[]` | — | If set, the lib walks these directories for `.map` files and resolves frames locally at encode time, skipping server-side resolution. If omitted, frames are encoded for server-side resolution. |
58
+
59
+ ## Features
60
+
61
+ - Automatic heap profile collection
62
+ - Out-of-memory monitoring with automatic profile upload
63
+ - Background upload process to ensure profiles are saved even during crashes
64
+ - Configurable labels for profile metadata
package/debug-ids.js ADDED
@@ -0,0 +1,39 @@
1
+ const fs = require('node:fs');
2
+
3
+ const DEBUG_ID_RE =
4
+ /\/\/# debugId=([0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})/i;
5
+
6
+ // `//# debugId=<uuid>` is appended at the end of the bundle; tail-read it.
7
+ const TAIL_BYTES = 256;
8
+
9
+ // Per-file debugId cache; lazy, null for non-bundle files.
10
+ const debugIdCache = new Map();
11
+
12
+ function readTail(fd, fileSize) {
13
+ const length = Math.min(TAIL_BYTES, fileSize);
14
+ const buf = Buffer.alloc(length);
15
+ fs.readSync(fd, buf, 0, length, fileSize - length);
16
+ return buf.toString('utf8');
17
+ }
18
+
19
+ function debugIdFor(filePath) {
20
+ if (debugIdCache.has(filePath)) return debugIdCache.get(filePath);
21
+ let debugId = null;
22
+ let fd;
23
+ try {
24
+ fd = fs.openSync(filePath, 'r');
25
+ const { size } = fs.fstatSync(fd);
26
+ const m = readTail(fd, size).match(DEBUG_ID_RE);
27
+ if (m) debugId = m[1];
28
+ } catch {
29
+ // ignore unreadable files (node: internals, deleted files, etc.)
30
+ } finally {
31
+ if (fd !== undefined) {
32
+ try { fs.closeSync(fd); } catch { /* ignore */ }
33
+ }
34
+ }
35
+ debugIdCache.set(filePath, debugId);
36
+ return debugId;
37
+ }
38
+
39
+ module.exports = { debugIdFor };
package/index.d.ts ADDED
@@ -0,0 +1,33 @@
1
+ import type { heap } from "@datadog/pprof"
2
+
3
+
4
+ export type ExportOptions = {
5
+ endpoint?: string
6
+ projectId?: string
7
+ labels?: Record<string, string>
8
+ headers?: Record<string, string>
9
+ timeout?: number
10
+ localSourceMapRoots?: string[]
11
+ }
12
+
13
+ export type EncodeOptions = {
14
+ /**
15
+ * Directories to walk for `.map` files. When set, frames are resolved
16
+ * locally at encode time and server-side resolution is skipped. When
17
+ * omitted (default), frames are encoded for server-side resolution.
18
+ */
19
+ localSourceMapRoots?: string[]
20
+ }
21
+
22
+ export const heapProfiler: typeof heap & {
23
+ encodedProfile(options?: EncodeOptions): Promise<Buffer>
24
+ }
25
+
26
+ export function encodedProfileFromTree(
27
+ rootNode: unknown,
28
+ options?: EncodeOptions,
29
+ ): Promise<Buffer>
30
+
31
+ export function monitorOutOfMemory(args: {
32
+ exportOptions: ExportOptions
33
+ }): void
package/index.js ADDED
@@ -0,0 +1,100 @@
1
+ const path = require('node:path');
2
+ const { SourceMapper, encode, heap } = require('@ohos-ports/datadog-pprof');
3
+ const { Mapping } = require('pprof-format');
4
+ const { debugIdFor } = require('./debug-ids');
5
+
6
+ // pprof Line has no column field. Encode V8's column as a `:L#<line>:C#<col>`
7
+ // suffix on the function name via the serializer's source-mapper hook.
8
+ const COLUMN_ENCODING_SOURCE_MAPPER = {
9
+ // Only called for frames with line > 0 and defined column (per isGeneratedLocation).
10
+ mappingInfo(loc) {
11
+ // Only applied to bundles with a //# debugId= marker.
12
+ if (!loc.file || debugIdFor(loc.file) === null) return loc;
13
+ const baseName = loc.name || 'anonymous';
14
+ return {
15
+ ...loc,
16
+ name: `${baseName}:L#${loc.line}:C#${loc.column}`,
17
+ };
18
+ },
19
+ };
20
+
21
+ // Tag JS frames with a v8js Mapping + build_id so consumers can resolve them
22
+ // against the matching sourcemap.
23
+ function addBuildIdMappings(profile) {
24
+ const st = profile.stringTable;
25
+ const v8jsFilenameId = st.dedup('v8js');
26
+ const pathToMappingId = new Map();
27
+ let nextId = profile.mapping.length + 1;
28
+
29
+ for (const fn of profile.function) {
30
+ const fname = st.strings[Number(fn.filename)];
31
+ if (!fname || pathToMappingId.has(fname)) continue;
32
+ const debugId = debugIdFor(fname);
33
+ if (debugId === null) continue;
34
+ profile.mapping.push(
35
+ new Mapping({
36
+ id: nextId,
37
+ filename: v8jsFilenameId,
38
+ buildId: st.dedup(debugId),
39
+ }),
40
+ );
41
+ pathToMappingId.set(fname, nextId);
42
+ nextId++;
43
+ }
44
+ if (pathToMappingId.size === 0) return;
45
+
46
+ // Assign the mapping to the correct location references.
47
+ for (const loc of profile.location) {
48
+ const firstLine = loc.line[0];
49
+ if (!firstLine) continue;
50
+ const fn = profile.function[Number(firstLine.functionId) - 1];
51
+ if (!fn) continue;
52
+ const mid = pathToMappingId.get(st.strings[Number(fn.filename)]);
53
+ if (mid != null) loc.mappingId = mid;
54
+ }
55
+ }
56
+
57
+ // Returns { mapper, injectBuildIds } depending on whether the caller wants
58
+ // local sourcemap resolution or server-side resolution.
59
+ async function pickEncodeMode(options) {
60
+ if (options?.localSourceMapRoots) {
61
+ return {
62
+ mapper: await SourceMapper.create(options.localSourceMapRoots),
63
+ injectBuildIds: false,
64
+ };
65
+ }
66
+ return { mapper: COLUMN_ENCODING_SOURCE_MAPPER, injectBuildIds: true };
67
+ }
68
+
69
+ async function finalize(profile, injectBuildIds) {
70
+ if (injectBuildIds) addBuildIdMappings(profile);
71
+ return encode(profile);
72
+ }
73
+
74
+ module.exports = {
75
+ heapProfiler: {
76
+ ...heap,
77
+ async encodedProfile(options) {
78
+ const { mapper, injectBuildIds } = await pickEncodeMode(options);
79
+ return finalize(await heap.profile('', mapper), injectBuildIds);
80
+ },
81
+ },
82
+ async encodedProfileFromTree(rootNode, options) {
83
+ const { mapper, injectBuildIds } = await pickEncodeMode(options);
84
+ return finalize(heap.convertProfile(rootNode, undefined, mapper), injectBuildIds);
85
+ },
86
+ monitorOutOfMemory(config = {}) {
87
+ heap.monitorOutOfMemory(
88
+ 0,
89
+ 0,
90
+ false,
91
+ [
92
+ process.execPath,
93
+ path.join(__dirname, 'upload-worker.js'),
94
+ JSON.stringify(config.exportOptions),
95
+ ],
96
+ null, // no callback, just the above export command
97
+ 0, // not async
98
+ );
99
+ },
100
+ };
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "@ohos-ports/polarsignals-pprof",
3
+ "version": "0.1.3-beta.0",
4
+ "description": "Node.js profiling library that automatically uploads heap profiles to Polar Signals",
5
+ "main": "index.js",
6
+ "files": [
7
+ "*.js",
8
+ "*.ts"
9
+ ],
10
+ "scripts": {
11
+ "test": "echo \"Error: no test specified\" && exit 1",
12
+ "publish:ci": "lerna publish --yes --no-verify-access"
13
+ },
14
+ "keywords": [
15
+ "profiling",
16
+ "pprof",
17
+ "heap",
18
+ "memory",
19
+ "performance",
20
+ "polar-signals",
21
+ "observability"
22
+ ],
23
+ "author": "Polar Signals",
24
+ "license": "Apache-2.0",
25
+ "repository": {
26
+ "type": "git",
27
+ "url": "https://github.com/ohos-ports/ohos-ports.git",
28
+ "directory": "ports/polarsignals-pprof/0.1.3"
29
+ },
30
+ "bugs": {
31
+ "url": "https://github.com/ohos-ports/ohos-ports/issues"
32
+ },
33
+ "homepage": "https://github.com/polarsignals/pprof-nodejs#readme",
34
+ "publishConfig": {
35
+ "access": "public",
36
+ "registry": "https://registry.npmjs.org/"
37
+ },
38
+ "packageManager": "pnpm@10.33.0",
39
+ "dependencies": {
40
+ "@ohos-ports/datadog-pprof": "^5.17.0-beta.0",
41
+ "pprof-format": "^2.2.1"
42
+ },
43
+ "devDependencies": {
44
+ "@types/node": "^24.7.2",
45
+ "lerna": "9.0.7",
46
+ "typescript": "^5.9.3"
47
+ },
48
+ "optionalDependencies": {
49
+ "express": "^4.21.2"
50
+ }
51
+ }
@@ -0,0 +1,152 @@
1
+ #!/usr/bin/env node
2
+
3
+ // Separate process for uploading profiles to Parca
4
+ // This runs independently of the main process to ensure uploads complete
5
+ // even if the main process crashes due to OOM
6
+
7
+ const fs = require('fs');
8
+ const http = require('http');
9
+ const https = require('https');
10
+ const { URL } = require('url');
11
+ const { encodedProfileFromTree } = require('./index');
12
+
13
+ async function uploadProfile (profilePath, config) {
14
+ try {
15
+ // Read the profile data and metadata
16
+ if (!fs.existsSync(profilePath)) {
17
+ return { success: false, error: 'Profile file not found' };
18
+ }
19
+
20
+ const profileDataJSON = JSON.parse(fs.readFileSync(profilePath));
21
+ const encodedProfile = await encodedProfileFromTree(profileDataJSON, {
22
+ localSourceMapRoots: config.localSourceMapRoots,
23
+ });
24
+
25
+ // Prepare Parca WriteRaw request
26
+ const defaultLabels = [
27
+ { name: '__name__', value: 'memory' }
28
+ ];
29
+
30
+ const customLabels = Object.entries(config.labels || {}).map(([name, value]) => ({
31
+ name,
32
+ value: String(value)
33
+ }));
34
+
35
+ const requestPayload = {
36
+ series: [{
37
+ labels: {
38
+ labels: [...defaultLabels, ...customLabels]
39
+ },
40
+ samples: [{
41
+ raw_profile: encodedProfile.toString('base64')
42
+ }]
43
+ }],
44
+ normalized: false
45
+ };
46
+
47
+ const payloadJson = JSON.stringify(requestPayload);
48
+ const endpoint = config.endpoint
49
+ ?? process.env.POLARSIGNALS_SERVER_URL
50
+ ?? 'https://api.polarsignals.com/api/parca/profilestore';
51
+ const projectId = config.projectId ?? process.env.POLARSIGNALS_PROJECT_ID;
52
+ const bearerToken = process.env.POLARSIGNALS_TOKEN;
53
+ const url = new URL(endpoint);
54
+ const isHttps = url.protocol === 'https:';
55
+ const client = isHttps ? https : http;
56
+
57
+ const headers = {
58
+ 'Content-Type': 'application/json',
59
+ 'Content-Length': Buffer.byteLength(payloadJson).toString(),
60
+ ...(bearerToken ? { 'Authorization': `Bearer ${bearerToken}` } : {}),
61
+ ...(projectId ? { 'Grpc-Metadata-projectid': projectId } : {}),
62
+ ...config.headers,
63
+ };
64
+
65
+ return new Promise((resolve) => {
66
+ const req = client.request({
67
+ hostname: url.hostname,
68
+ port: url.port || (isHttps ? 443 : 80),
69
+ path: `${url.pathname}/profiles/writeraw`,
70
+ method: 'POST',
71
+ headers,
72
+ timeout: config.timeout || 30000, // Longer timeout for worker
73
+ }, (res) => {
74
+ let responseData = '';
75
+
76
+ res.on('data', (chunk) => {
77
+ responseData += chunk;
78
+ });
79
+
80
+ res.on('end', () => {
81
+ const success = res.statusCode >= 200 && res.statusCode < 300;
82
+
83
+ if (success) {
84
+ // Clean up files after successful upload
85
+ try {
86
+ fs.unlinkSync(profilePath);
87
+ } catch (cleanupError) {
88
+ }
89
+ }
90
+
91
+ resolve({
92
+ success,
93
+ statusCode: res.statusCode,
94
+ error: success ? undefined : `HTTP ${res.statusCode}: ${res.statusMessage}`,
95
+ responseData
96
+ });
97
+ });
98
+ });
99
+
100
+ req.on('error', (error) => {
101
+ resolve({
102
+ success: false,
103
+ error: error.message
104
+ });
105
+ });
106
+
107
+ req.on('timeout', () => {
108
+ req.destroy();
109
+ resolve({
110
+ success: false,
111
+ error: 'Request timeout'
112
+ });
113
+ });
114
+
115
+ req.write(payloadJson);
116
+ req.end();
117
+ });
118
+
119
+ } catch (error) {
120
+ return {
121
+ success: false,
122
+ error: error.message
123
+ };
124
+ }
125
+ }
126
+
127
+ // Main worker execution
128
+ async function main() {
129
+ const args = process.argv.slice(2);
130
+
131
+ if (args.length < 2) {
132
+ process.exit(1);
133
+ }
134
+
135
+ const configJson = args[0];
136
+ const profilePath = args[1];
137
+
138
+ try {
139
+ const config = JSON.parse(configJson);
140
+
141
+ const result = await uploadProfile(profilePath, config);
142
+
143
+ process.exit(result.success ? 0 : 1);
144
+
145
+ } catch (error) {
146
+ process.exit(1);
147
+ }
148
+ }
149
+
150
+ if (require.main === module) {
151
+ main();
152
+ }