├── .gitignore ├── .npmignore ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── instrumenter.js ├── package-lock.json ├── package.json └── replay.js /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | 9 | # Diagnostic reports (https://nodejs.org/api/report.html) 10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 11 | 12 | # Runtime data 13 | pids 14 | *.pid 15 | *.seed 16 | *.pid.lock 17 | 18 | # Directory for instrumented libs generated by jscoverage/JSCover 19 | lib-cov 20 | 21 | # Coverage directory used by tools like istanbul 22 | coverage 23 | 24 | # nyc test coverage 25 | .nyc_output 26 | 27 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 28 | .grunt 29 | 30 | # Bower dependency directory (https://bower.io/) 31 | bower_components 32 | 33 | # node-waf configuration 34 | .lock-wscript 35 | 36 | # Compiled binary addons (https://nodejs.org/api/addons.html) 37 | build/Release 38 | dist/ 39 | 40 | # Dependency directories 41 | node_modules/ 42 | jspm_packages/ 43 | 44 | # TypeScript v1 declaration files 45 | typings/ 46 | 47 | # Optional npm cache directory 48 | .npm 49 | 50 | # Optional eslint cache 51 | .eslintcache 52 | 53 | # Optional REPL history 54 | .node_repl_history 55 | 56 | # Output of 'npm pack' 57 | *.tgz 58 | 59 | # Yarn Integrity file 60 | .yarn-integrity 61 | 62 | # dotenv environment variables file 63 | .env 64 | .env.test 65 | 66 | # parcel-bundler cache (https://parceljs.org/) 67 | .cache 68 | 69 | # next.js build output 70 | .next 71 | 72 | # nuxt.js build output 73 | .nuxt 74 | 75 | # vuepress build output 76 | .vuepress/dist 77 | 78 | # Serverless directories 79 | .serverless/ 80 | 81 | # FuseBox cache 82 | .fusebox/ 83 | 84 | # DynamoDB Local files 85 | .dynamodb/ 86 | .DS_Store 87 | 88 | 89 | # IDE 90 | .vscode 91 | 92 | # local secrets 93 | awsCredentials.json 94 | agent-internal.json 95 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | 9 | # Diagnostic reports (https://nodejs.org/api/report.html) 10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 11 | 12 | # Runtime data 13 | pids 14 | *.pid 15 | *.seed 16 | *.pid.lock 17 | 18 | # Directory for instrumented libs generated by jscoverage/JSCover 19 | lib-cov 20 | 21 | # Coverage directory used by tools like istanbul 22 | coverage 23 | 24 | # nyc test coverage 25 | .nyc_output 26 | 27 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 28 | .grunt 29 | 30 | # Bower dependency directory (https://bower.io/) 31 | bower_components 32 | 33 | # node-waf configuration 34 | .lock-wscript 35 | 36 | # Compiled binary addons (https://nodejs.org/api/addons.html) 37 | build/Release 38 | dist/ 39 | 40 | # Dependency directories 41 | node_modules/ 42 | jspm_packages/ 43 | 44 | # TypeScript v1 declaration files 45 | typings/ 46 | 47 | # Optional npm cache directory 48 | .npm 49 | 50 | # Optional eslint cache 51 | .eslintcache 52 | 53 | # Optional REPL history 54 | .node_repl_history 55 | 56 | # Output of 'npm pack' 57 | *.tgz 58 | 59 | # Yarn Integrity file 60 | .yarn-integrity 61 | 62 | # dotenv environment variables file 63 | .env 64 | .env.test 65 | 66 | # parcel-bundler cache (https://parceljs.org/) 67 | .cache 68 | 69 | # next.js build output 70 | .next 71 | 72 | # nuxt.js build output 73 | .nuxt 74 | 75 | # vuepress build output 76 | .vuepress/dist 77 | 78 | # Serverless directories 79 | .serverless/ 80 | 81 | # FuseBox cache 82 | .fusebox/ 83 | 84 | # DynamoDB Local files 85 | .dynamodb/ 86 | .DS_Store 87 | 88 | 89 | # IDE 90 | .vscode 91 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Contributions are much appreciated! 🙏 4 | 5 | Feel to contribute: 6 | 7 | 1. Suppport ❤️ - By starring ⭐️ our repo 8 | 1. Code, Documentation - By raising PRs 9 | 1. Bug reports, feature requests - By Filing issues 10 | 11 | # Setup 12 | 13 | ## Install the repos in sibling dirs 14 | 15 | ``` 16 | git clone git@github.com:Code-Parrot-ai/opentelemetry-js-contrib.git 17 | git clone git@github.com:Code-Parrot-ai/opentelemetry-js.git 18 | ``` 19 | 20 | In each of the above sibling dirs, run: 21 | 22 | ``` 23 | npm i 24 | ``` 25 | 26 | For ease of development you should `npm link ` to the local packages. Like, I had to do 27 | 28 | ``` 29 | cd __codeparrot 30 | npm link /Users/vedant/codeparrot/code/opentelemetry-js/experimental/packages/opentelemetry-instrumentation-http 31 | npm link /Users/vedant/codeparrot/code/opentelemetry-js/experimental/packages/opentelemetry-instrumentation-grpc 32 | npm link /Users/vedant/codeparrot/code/opentelemetry-js/experimental/packages/opentelemetry-instrumentation 33 | npm link /Users/vedant/codeparrot/code/opentelemetry-js-contrib/plugins/node/opentelemetry-instrumentation-pg 34 | ``` 35 | 36 | *Also see [this issue](https://github.com/npm/npm/issues/17287#issuecomment-389873586)* 37 | 38 | Check status with `npm ls -g --depth=0 --link=true` 39 | 40 | ``` 41 | npm ls --depth=0 --link=true 42 | /Users/vedant/.nvm/versions/node/v16.19.0/lib 43 | ├── @codeparrot/instrumentation-grpc@0.35.7 -> ./../../../../../code/opentelemetry-js/experimental/packages/opentelemetry-instrumentation-grpc 44 | ├── @codeparrot/instrumentation-http@0.35.6 -> ./../../../../../code/opentelemetry-js/experimental/packages/opentelemetry-instrumentation-http 45 | ├── @codeparrot/instrumentation-pg@0.34.4 -> ./../../../../../code/opentelemetry-js-contrib/plugins/node/opentelemetry-instrumentation-pg 46 | └── @codeparrot/instrumentation@0.35.4 -> ./../../../../../code/opentelemetry-js/experimental/packages/opentelemetry-instrumentation 47 | ``` 48 | 49 | To unlink: 50 | 51 | ``` 52 | npm unlink @codeparrot/instrumentation 53 | npm unlink @codeparrot/instrumentation-grpc 54 | npm unlink @codeparrot/instrumentation-http 55 | npm unlink @codeparrot/instrumentation-pg 56 | npm unlink @codeparrot/js-agent 57 | ``` 58 | 59 | ## Setup export to GCP trace 60 | 61 | Create a local file `./agent-internal.json`. This file is provided by GCP after you have created a **service account** with appropriate permissions. 62 | 63 | This file is ignored in git, but included in the npm package (i.e. during `npm publish`) 64 | 65 | ## Use a sample/real application to test 66 | 67 | Since this ia a library, it can only be tested by requiring the package from a sample application. (More info in [README.md](./README.md)) 68 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 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. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # What is CodeParrot? 2 | 3 | ### Get a change report on response body, latency & error rates of your APIs! 4 | 5 | ![Example Diff](https://storage.googleapis.com/codeparrot-public/example-diff.png) 6 | 7 | An Example Diff 8 | 9 | CodeParrot uses AI and production traffic to generate a **change report**. This report gives you insights on differences in response body for all unique requests coming to your service! 10 | 11 | It works by "recording" production (or staging env) traffic. Our AI figures out the unique API calls from this traffic, and also mocks the downstream dependencies! *Magic right?!* 🤯 12 | 13 | Then for every PR, the above unique API calls are run against the new version of code. Its like- auto-generated functional tests (API calls for a service, with dependencies mocked). 14 | 15 | # Installation 16 | 17 | ## Step 1 - Install the nodeJs "record" agent 18 | 19 | 1. Install the CodeParrot dependency `@codeparrot/js-agent` by running 20 | 21 | ```bash 22 | npm install @codeparrot/js-agent 23 | ``` 24 | 25 | This will add a dependency `"@codeparrot/js-agent": "^1.2.3"`, in your `package.json` 26 | 27 | 2. Update the `node` start app command with `-r @codeparrot/js-agent`, like 28 | 29 | ```json 30 | "scripts": { 31 | "server": "node -r @codeparrot/js-agent index.js" 32 | } 33 | ``` 34 | 35 | This basically `require`’s the code parrot agent package **before** your application code. 36 | 37 | If you are using pm2 to run your application, then the following syantx can help you get started 38 | ```javascript 39 | module.exports = { 40 | apps : [{ 41 | name : "app1", 42 | script : "./app.js", 43 | node_args: "--require @codeparrot/js-agent", 44 | env_production: { 45 | NODE_ENV: "production", 46 | CODE_PARROT_JSON_KEY_FILE: "/path-to-file/agent-file.json",//replace with the path of your agent file 47 | CODE_PARROT_APP_NAME: "test-app-1", 48 | CODE_PARROT_VERSION: "0.0.1", 49 | }, 50 | }] 51 | } 52 | ``` 53 | 54 | ### Set the following env variable: 55 | 56 | ```bash 57 | # set it to your *unique* service name 58 | CODE_PARROT_APP_NAME= 59 | ``` 60 | > **_NOTE:_** The environment variables have to be set before the agent is pre-loaded. For example, if you are using dotenv to load environment variable in your app, then these variables won't be available to the codeparrot js-agent. 61 | 62 | When you start your nodeJS application and see a log line like: 63 | 64 | ``` 65 | @codeparrot/js-agent, v1.2.5 nodejs-agent-<...>gserviceaccount.com 66 | ``` 67 | 68 | CodeParrot record is set up! 🎉 Use your application as normal, and CodeParrot will record the network traffic. 69 | 70 | ## Step 2 - Install GitHub App 71 | 72 | Install the [CodeParrot GitHub App](https://github.com/apps/codeparrot-app) in the repo(s) that already have replay set up. *(It asks for the minimum possible permissions)* 73 | 74 | Then, create 2 new files: 75 | 76 | 1. `codeparrot-replay.Dockerfile` 77 | 2. `codeparrot.sh` 78 | 79 | to run the tests. Every code push, this Dockerfile is built and run. This new Dockerfile is almost as same as your existing one, except that it sets the `CMD` to run `codeparrot.sh` instead of the usual `npm start`. 80 | 81 | > **_NOTE:_** You don't have to provision docker, you just provide the dockerfile, and our github app runs this in cloud so that it is able to generate diff report. The onus is on us. 82 | 83 | `codeparrot.sh` runs your app start command (like `npm start`) in a loop, until all the tests execute. 84 | 85 | Example `codeparrot.sh` : 86 | 87 | ```bash 88 | #!/bin/sh 89 | 90 | while : 91 | do 92 | CODE_PARROT_IS_REPLAY=true npm start && break 93 | echo "Non-zero exit! Restarting replay..." 94 | done 95 | ``` 96 | 97 | Example `codeparrot-replay.Dockerfile` : 98 | 99 | ```bash 100 | # ... existing app setup 101 | 102 | COPY codeparrot.sh ./codeparrot.sh 103 | 104 | CMD ["sh", "./codeparrot.sh"] 105 | ``` 106 | 107 | Now, in every PR, a GitHub "check" with a link to the Change Report will appear: 🎉 108 | 109 | ![GitHub Check](https://storage.googleapis.com/codeparrot-public/Screenshot%20git%20hub%20check.png) 110 | 111 | 112 | # Contributing, Self Setup 113 | 114 | Refer to [CONTRIBUTING.md](./CONTRIBUTING.md) 115 | -------------------------------------------------------------------------------- /instrumenter.js: -------------------------------------------------------------------------------- 1 | const { HttpInstrumentation } = require('@codeparrot/instrumentation-http'); 2 | const opentelemetry = require('@opentelemetry/sdk-node'); 3 | const { PgInstrumentation } = require('@codeparrot/instrumentation-pg'); 4 | const { OTLPTraceExporter } = require('@opentelemetry/exporter-trace-otlp-grpc'); 5 | const { RedisInstrumentation } = require('@opentelemetry/instrumentation-redis-4'); 6 | const { GrpcInstrumentation } = require('@codeparrot/instrumentation-grpc') 7 | const { Resource } = require('@opentelemetry/resources'); 8 | const { SemanticResourceAttributes } = require('@opentelemetry/semantic-conventions'); 9 | const { diag, DiagLogLevel, DiagConsoleLogger } = require('@opentelemetry/api'); 10 | const { ParentBasedSampler, TraceIdRatioBasedSampler } = require('@opentelemetry/sdk-trace-base'); 11 | const { cpSetAttribute } = require('@codeparrot/instrumentation'); 12 | const { BatchSpanProcessor } = require('@opentelemetry/sdk-trace-base'); 13 | 14 | const { env } = require('node:process'); 15 | const { hostname } = require('node:os'); 16 | 17 | const { ReplayRunner, triggerOnReplayComplete, onReplay } = require('./replay'); 18 | 19 | const isReplay = env.CODE_PARROT_IS_REPLAY === 'true'; 20 | const appName = env.CODE_PARROT_APP_NAME || 'nodeJS-app'; 21 | const samplingRatio = env.CODE_PARROT_SAMPLING_RATIO ?? 1.0; 22 | const envName = isReplay ? 'replay' : env.CODE_PARROT_ENV_NAME || 'default'; 23 | const version = env.CODE_PARROT_VERSION; 24 | let jsonKeyFile = env.CODE_PARROT_JSON_KEY_FILE; 25 | 26 | if (!jsonKeyFile) { 27 | console.info(`CODE_PARROT_JSON_KEY_FILE env variable not set. Sending data to common cloud!`); 28 | console.info(`DO NOT USE THIS IN PRODUCTION! Nor with sensitive data!`); 29 | 30 | jsonKeyFile = `${__dirname}/agent-internal.json`; 31 | } 32 | 33 | const collectorGrpcUrl = env.CODE_PARROT_URL || 'http://130.211.117.203:4317'; // jaeger-common 34 | 35 | const namespace = require(jsonKeyFile)['client_email']; 36 | 37 | function getVersion() { 38 | if (version) { 39 | return version; 40 | } 41 | 42 | try { 43 | const { execSync } = require('child_process'); 44 | const gitVersion = execSync('git describe --tags --always').toString().trim(); 45 | return gitVersion; 46 | } catch (e) { 47 | if (isReplay) { 48 | throw e; 49 | } 50 | 51 | console.error(`Failed to get git version: ${e}`); 52 | return 'unknown'; 53 | } 54 | } 55 | 56 | const metadata = JSON.stringify({ 57 | hostname: hostname(), 58 | version: getVersion(), 59 | }); 60 | 61 | 62 | diag.setLogger(new DiagConsoleLogger(), env.CODE_PARROT_DEBUG ? DiagLogLevel.DEBUG : DiagLogLevel.INFO); 63 | 64 | 65 | if (isReplay) { 66 | global.CODE_PARROT_IS_REPLAY = true; 67 | } 68 | 69 | const spanProcessor = new BatchSpanProcessor(new OTLPTraceExporter({ 70 | url: collectorGrpcUrl, 71 | timeoutMillis: 3000, 72 | })); 73 | 74 | const grpcInstrumentation = new GrpcInstrumentation(); 75 | const httpInstrumentation = new HttpInstrumentation({}, isReplay); 76 | const pgInstrumentation = new PgInstrumentation({ 77 | enhancedDatabaseReporting: true, 78 | responseHook: (span, responseInfo) => { 79 | const data = { 80 | rows: responseInfo.data.rows, 81 | 82 | // in case of INSERT, UPDATE, etc., only this field is populated: 83 | rowCount: responseInfo.data.rowCount, 84 | }; 85 | cpSetAttribute(span, 'db.results', JSON.stringify(data)); 86 | } 87 | }); 88 | 89 | 90 | const sdk = new opentelemetry.NodeSDK({ 91 | spanProcessor: spanProcessor, 92 | instrumentations: [ 93 | httpInstrumentation, 94 | pgInstrumentation, 95 | new RedisInstrumentation({ 96 | dbStatementSerializer: (cmdName, cmdArgs) => { 97 | return JSON.stringify({ cmd: cmdName, args: cmdArgs }); 98 | }, 99 | responseHook: (span, cmdName, cmdArgs, response) => { 100 | cpSetAttribute(span, 'db.response', JSON.stringify(response)); 101 | } 102 | }), 103 | grpcInstrumentation, 104 | ], 105 | resource: new Resource({ 106 | //service.namespace 107 | // g.co/r/generic_task/namespace. : 108 | [SemanticResourceAttributes.SERVICE_NAMESPACE]: namespace, 109 | //service.name 110 | // g.co/r/generic_task/job. : 111 | [SemanticResourceAttributes.SERVICE_NAME]: appName, 112 | //service.instance.id 113 | // g.co/r/generic_task/task_id. Used as version: 114 | [SemanticResourceAttributes.SERVICE_INSTANCE_ID]: getVersion(), 115 | //cloud.availability_zone 116 | // g.co/r/generic_task/location. Used as env: 117 | [SemanticResourceAttributes.CLOUD_AVAILABILITY_ZONE]: envName 118 | }), 119 | spanLimits: { 120 | attributeValueLengthLimit: 1024, // 1KB 121 | attributeCountLimit: 100, 122 | }, 123 | sampler: new ParentBasedSampler({ 124 | root: new TraceIdRatioBasedSampler(samplingRatio), 125 | }), 126 | }); 127 | 128 | function start() { 129 | sdk.start(); 130 | console.log(`@codeparrot/js-agent v2.0.3, ${appName}, in ${envName}, ${getVersion()}, to ${collectorGrpcUrl}`); 131 | } 132 | 133 | if (isReplay) { 134 | onReplay(); 135 | const replayDelay = Number(env.CODE_PARROT_REPLAY_DELAY_SECONDS ?? 5) * 1000; 136 | const testWait = Number(env.CODE_PARROT_REPLAY_TEST_WAIT_MS ?? 10); 137 | 138 | setTimeout(async () => { 139 | diag.info(`Replay delay of ${replayDelay}ms is over. Starting replay...`); 140 | const replayRunner = await ReplayRunner.create(jsonKeyFile, namespace, appName, testWait); 141 | httpInstrumentation.setReplayResponseFn(replayRunner.createHttpReplayResponseFn()); 142 | grpcInstrumentation.setReplayResponseFn(replayRunner.createGrpcReplayResponseFn()); 143 | pgInstrumentation.setReplayResponseFn(replayRunner.createPgReplayResponseFn()); 144 | replayRunner.setSpanProcessor(spanProcessor); 145 | await spanProcessor.forceFlush(); 146 | start(); 147 | await replayRunner.runHttpReplay(httpInstrumentation); 148 | await replayRunner.runGrpcReplay(grpcInstrumentation); 149 | await spanProcessor.forceFlush(); 150 | 151 | sdk.shutdown(); 152 | await triggerOnReplayComplete(jsonKeyFile, namespace, appName, metadata, getVersion()); 153 | diag.info(`Replay is over. Exiting...`); 154 | await replayRunner.cleanUp(); 155 | process.exit(0); 156 | }, replayDelay); 157 | } else { 158 | start(); 159 | } 160 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@codeparrot/js-agent", 3 | "version": "2.0.4", 4 | "scripts": { 5 | "test": "echo \"Error: no test specified\" && exit 1" 6 | }, 7 | "dependencies": { 8 | "@codeparrot/instrumentation": "^0.35.7", 9 | "@codeparrot/instrumentation-grpc": "^0.35.14", 10 | "@codeparrot/instrumentation-http": "^0.35.13", 11 | "@codeparrot/instrumentation-pg": "0.34.8", 12 | "@google-cloud/storage": "^6.9.4", 13 | "@opentelemetry/api": "^1.4.0", 14 | "@opentelemetry/exporter-trace-otlp-grpc": "^0.39.1", 15 | "@opentelemetry/instrumentation-redis-4": "^0.34.2", 16 | "@opentelemetry/sdk-node": "^0.35.1", 17 | "@opentelemetry/sdk-trace-base": "^1.9.1" 18 | }, 19 | "description": "Record and replay API traffic", 20 | "main": "instrumenter.js", 21 | "author": "Vedant", 22 | "license": "UNLICENSED", 23 | "publishConfig": { 24 | "access": "public" 25 | }, 26 | "devDependencies": { 27 | "lerna": "^6.6.1", 28 | "pg": "^8.11.1", 29 | "typescript": "^5.0.4" 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /replay.js: -------------------------------------------------------------------------------- 1 | const process = require('node:process'); 2 | const fs = require('fs').promises; 3 | 4 | const { diag } = require('@opentelemetry/api'); 5 | const { logAndThrow } = require('@codeparrot/instrumentation'); 6 | const { Storage } = require('@google-cloud/storage'); 7 | const { JWT } = require('google-auth-library'); 8 | 9 | const REPLAY_FILE = '/tmp/code-parrot-replay.json'; 10 | const HTTP_INDEX_FILE = '/tmp/code-parrot-replay-http-index.txt'; 11 | 12 | function commonCharacters(str1, str2) { 13 | let i = 0; 14 | while (str1[i] === str2[i] && i < str1.length && i < str2.length) { 15 | i++; 16 | } 17 | return i; 18 | } 19 | 20 | module.exports.onReplay = () => { 21 | process.on('exit', (code) => { 22 | diag.info(`About to exit with code: ${code}`); 23 | if (code !== 0) { 24 | console.trace(); 25 | } 26 | }); 27 | } 28 | 29 | module.exports.ReplayRunner = class ReplayRunner { 30 | static async create(jsonKeyFile, namespace, service, testWait) { 31 | let fileContents; 32 | try { 33 | await fs.readFile(HTTP_INDEX_FILE, 'utf8'); // check if file exists 34 | fileContents = await fs.readFile(REPLAY_FILE, 'utf8'); 35 | } catch (error) { 36 | const namespacePrefix = namespace.split('@')[0]; 37 | const filePath = `${namespacePrefix}/default/${service}/`; 38 | 39 | // Lists files in the bucket 40 | const storage = new Storage({ keyFilename: jsonKeyFile }); 41 | const [files, obj, meta] = await storage.bucket('codeparrotai-common') 42 | .getFiles({ prefix: filePath, autoPaginate: false }); 43 | 44 | diag.info(`Fetched Files: ${files.length}`); 45 | const lastFile = await files.sort()[files.length - 1].download(); 46 | fileContents = lastFile.toString('utf8'); 47 | await fs.writeFile(REPLAY_FILE, fileContents); 48 | } 49 | 50 | return new ReplayRunner(JSON.parse(fileContents), testWait); 51 | } 52 | 53 | constructor(json, testWait) { 54 | this.json = json; 55 | this.currentSpan = undefined; 56 | this.testWait = testWait; 57 | } 58 | 59 | setSpanProcessor(spanProcessor) { 60 | this.spanProcessor = spanProcessor; 61 | } 62 | 63 | async runHttpReplay(httpInstrumentation) { 64 | const httpTraces = this.json.traces.filter(trace => trace.spans[0].labels['http.target']); 65 | 66 | let i; 67 | try { 68 | i = Number(await fs.readFile(HTTP_INDEX_FILE, 'utf8')) + 1; 69 | diag.info(`runHttpReplay: http index found! Skipping last test and resuming from ${i}`); 70 | } catch (error) { 71 | i = 0; 72 | } 73 | 74 | diag.info(`http.UpstreamReplay: run(), httpTraces: ${httpTraces.length}`); 75 | for (; i < httpTraces.length; i++) { 76 | const trace = httpTraces[i]; 77 | 78 | diag.info(`runHttpReplay ${i}: --- ${trace.spans[0].labels['/http/method']} ${trace.spans[0].labels['http.target']} : ${trace.traceId} -------->`); 79 | await fs.writeFile(HTTP_INDEX_FILE, i.toString()); 80 | this.currentSpan = trace.spans[0]; 81 | try { 82 | await httpInstrumentation.runReplay(trace); 83 | } catch (error) { 84 | diag.error(`runHttpReplay: continuing after ${error?.stack}`); 85 | } 86 | if (i % 20 === 0) await this.spanProcessor.forceFlush(); 87 | 88 | await new Promise((resolve) => setTimeout(resolve, this.testWait)); 89 | } 90 | } 91 | 92 | async runGrpcReplay(grpcInstrumentation) { 93 | const grpcSpans = this.json.traces.map((trace) => trace.spans[0]) 94 | .filter((topSpan) => topSpan.labels['cp.req.name']); 95 | 96 | diag.info(`gRPC.UpstreamReplay: run(), grpcSpans: ${grpcSpans.length}`); 97 | for (const i in grpcSpans) { 98 | const topSpan = grpcSpans[i]; 99 | diag.info(`runGrpcReplay ${i}: --- ${topSpan.labels['cp.req.name']} : ${topSpan.spanId} -------->`); 100 | this.currentSpan = topSpan; 101 | try { 102 | grpcInstrumentation.runReplay(topSpan); 103 | } catch (error) { 104 | diag.error(`runGrpcReplay: continuing after ${error?.stack}`); 105 | } 106 | await new Promise((resolve) => setTimeout(resolve, this.testWait)); 107 | }; 108 | } 109 | 110 | async cleanUp() { 111 | await fs.unlink(REPLAY_FILE); 112 | await fs.unlink(HTTP_INDEX_FILE); 113 | } 114 | 115 | createHttpReplayResponseFn() { 116 | return (requestUrl, method, requestBodyStr) => { 117 | // in downstream http, both URL and target include query params. 118 | const childSpans = this.currentSpan?.children 119 | ?.filter(span => span.labels['/http/url']?.substring(0, 50) === requestUrl.substring(0, 50)) 120 | || []; 121 | 122 | if (childSpans.length === 0) { 123 | diag.error(`createHttpReplayResponseFn: Could not find span for requestUrl: ${requestUrl}. Returning empty response.`); 124 | return [200, undefined, undefined, 'cp-no-matching-span-id']; 125 | } 126 | 127 | diag.info(`createHttpReplayResponseFn: found ${childSpans.length} spans for requestUrl: ${requestUrl}.`); 128 | 129 | const span = childSpans.find(span => 130 | span.labels['/http/method'] === method && span.labels['http.req.body'] === requestBodyStr 131 | ) || childSpans[0]; 132 | return [ 133 | span.labels['/http/status_code'], 134 | span.labels['http.res.body'], 135 | JSON.parse(span.labels['cp.res.headers']), 136 | span.spanId 137 | ]; 138 | } 139 | } 140 | 141 | createGrpcReplayResponseFn() { 142 | return (requestName, requestStr) => { 143 | const childSpans = this.currentSpan.children.filter(span => span.labels['cp.req.name'] === requestName); 144 | 145 | if (childSpans.length === 0) { 146 | diag.error(`createGrpcReplayResponseFn: Could not find span for requestName: ${requestName}. Returning empty response.`); 147 | return ['', 'cp-no-matching-span-id']; 148 | } 149 | 150 | diag.info(`createGrpcReplayResponseFn: found ${childSpans.length} spans for requestName: ${requestName}.`); 151 | const span = childSpans.find(span => span.labels['cp.req.body'] === requestStr) || childSpans[0]; 152 | return [span.labels['cp.res.body'], span.spanId]; 153 | } 154 | } 155 | 156 | createPgReplayResponseFn() { 157 | return (statement, values) => { 158 | const childSpans = this.currentSpan.children.filter(span => span.labels['db.statement']); 159 | // TODO, maybe get better span(s) by considering 'db.postgresql.values' 160 | 161 | if (childSpans.length === 0) { 162 | diag.error(`createPgReplayResponseFn: Could not find span for statement: ${statement}`); 163 | return [undefined, { rows: [] }, 'cp-no-matching-span-id']; 164 | } 165 | 166 | diag.info(`createPgReplayResponseFn: found ${childSpans.length} spans for statement: ${statement}.`); 167 | 168 | // the span with max number of common characters in statement is the best match 169 | const span = childSpans.reduce((prev, curr) => { 170 | const prevCommon = prev ? commonCharacters(statement, prev.labels['db.statement']) : -1; 171 | const currCommon = commonCharacters(statement, curr.labels['db.statement']); 172 | return prevCommon > currCommon ? prev : curr; 173 | }); 174 | 175 | diag.info(`createPgReplayResponseFn: best match span: ${span.labels['db.statement']}`); 176 | 177 | if (span.labels['db.results']) { 178 | return [undefined, JSON.parse(span.labels['db.results']), span.spanId]; 179 | } 180 | 181 | const error = new Error(span.labels['cp.error.message'] || 'error from replay data'); 182 | Object.assign(error, { 183 | schema: span.labels['cp.error.schema'], 184 | table: span.labels['cp.error.table'], 185 | column: span.labels['cp.error.column'], 186 | dataType: span.labels['cp.error.dataType'], 187 | constraint: span.labels['cp.error.constraint'], 188 | }); 189 | 190 | return [error, undefined, span.spanId]; 191 | } 192 | } 193 | } 194 | 195 | module.exports.triggerOnReplayComplete = async function (jsonKeyFile, namespace, service, metadata, version) { 196 | diag.info(`Waiting 10s before triggering onReplayComplete`); 197 | await new Promise((resolve) => setTimeout(resolve, 10000)); 198 | 199 | const keys = require(jsonKeyFile); 200 | const client = new JWT({ 201 | email: keys.client_email, 202 | key: keys.private_key, 203 | scopes: ['https://www.googleapis.com/auth/cloud-platform'], 204 | }); 205 | const url = `https://pubsub.googleapis.com/v1/projects/innate-actor-378220/topics/cp-replay-cron:publish`; 206 | const data = { // uses JSON 207 | messages: [{ 208 | attributes: { namespace, service, metadata, version }, 209 | }] 210 | } 211 | const res = await client.request({ url, method: 'POST', data }); 212 | if (res.status !== 200) { 213 | logAndThrow(`Failed to trigger onReplayComplete: ${res.status} ${JSON.stringify(res.data)}`); 214 | } 215 | diag.info(`Triggered onReplayComplete: ${res.status}`); 216 | diag.info(`Report will be available at: https://dashboard.codeparrot.ai/diff/${namespace}/${service}/${version}`); 217 | } 218 | --------------------------------------------------------------------------------