├── .github └── workflows │ └── publish.yml ├── .gitignore ├── .release-it.json ├── .vscode ├── launch.json └── settings.json ├── CHANGELOG.md ├── Contributing.md ├── LICENSE ├── README.md ├── e2e ├── arc │ ├── app.arc │ ├── package-lock.json │ ├── package.json │ ├── sam.json │ └── sam.yaml ├── benchmarking │ ├── .gitignore │ ├── .vscode │ │ ├── launch.json │ │ └── settings.json │ ├── package-lock.json │ ├── package.json │ ├── packages │ │ └── functions │ │ │ ├── package.json │ │ │ ├── src │ │ │ └── lambda.ts │ │ │ ├── sst-env.d.ts │ │ │ └── tsconfig.json │ ├── pnpm-workspace.yaml │ ├── sst.config.ts │ ├── stacks │ │ └── MyStack.ts │ └── tsconfig.json ├── serverless-webpack-babel │ ├── babel.config.js │ ├── handler.js │ ├── package-lock.json │ ├── package.json │ ├── serverless.yml │ ├── src │ │ └── func.js │ └── webpack.config.js ├── serverless │ ├── handler.js │ ├── package-lock.json │ ├── package.json │ ├── serverless.yml │ └── src │ │ ├── api.js │ │ ├── dispatcher.js │ │ ├── eventbridge.js │ │ ├── main.js │ │ └── utils.js └── sst │ ├── .gitignore │ ├── .vscode │ ├── launch.json │ └── settings.json │ ├── package-lock.json │ ├── package.json │ ├── packages │ ├── core │ │ ├── package.json │ │ ├── src │ │ │ ├── event.ts │ │ │ └── todo.ts │ │ ├── sst-env.d.ts │ │ └── tsconfig.json │ └── functions │ │ ├── package.json │ │ ├── src │ │ ├── events │ │ │ └── todo-created.ts │ │ ├── lambda.ts │ │ └── todo.ts │ │ ├── sst-env.d.ts │ │ └── tsconfig.json │ ├── pnpm-workspace.yaml │ ├── sst.config.ts │ ├── stacks │ └── MyStack.ts │ └── tsconfig.json ├── layer-dir └── baselime ├── meta.json ├── meta.wrapper.json ├── multi-region-deploy.ts ├── multiRegion.js ├── package-lock.json ├── package.json ├── scripts └── publish ├── src ├── handler.cjs ├── handler.mjs ├── index.ts ├── lambda-wrapper.ts ├── load-async.ts └── load-sync.ts ├── sst.config.ts ├── tests ├── data │ └── src │ │ ├── const-export.cjs │ │ ├── original-handler.cjs │ │ ├── original-handler.mjs │ │ └── sample.js ├── load.test.ts ├── loadSync.test.ts └── wrap.test.ts ├── trace-timeline.png ├── tsconfig.json └── vitest.config.ts /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: build-publish-release 2 | 3 | on: 4 | push: 5 | tags: 6 | - 'v*.*.*' 7 | 8 | jobs: 9 | publish-node-packages: 10 | runs-on: ubuntu-latest 11 | permissions: 12 | contents: write 13 | packages: read 14 | id-token: write 15 | 16 | steps: 17 | - name: Checkout 18 | uses: actions/checkout@v2 19 | 20 | - name: Setup 21 | uses: actions/setup-node@v2 22 | with: 23 | node-version: '18.x' 24 | registry-url: 'https://registry.npmjs.org' 25 | - run: | 26 | echo "//npm.pkg.github.com/:_authToken=${{ secrets.GITHUB_TOKEN }}" >> .npmrc 27 | echo "@baselime:registry=https://npm.pkg.github.com/" >> .npmrc 28 | 29 | - name: Build the package 30 | continue-on-error: false 31 | run: 32 | npm ci && 33 | npm run build 34 | - name: Configure AWS Credentials 35 | uses: aws-actions/configure-aws-credentials@v1 36 | with: 37 | aws-region: eu-west-1 38 | role-to-assume: arn:aws:iam::097948374213:role/github-actions-deploy 39 | - name: Deploy Layer 40 | run: STAGE=prod AWS_REGION=eu-west-1 npm run deploy 41 | 42 | create-release: 43 | needs: [publish-node-packages] 44 | 45 | runs-on: ubuntu-latest 46 | 47 | steps: 48 | - name: Checkout 49 | uses: actions/checkout@v2 50 | 51 | - name: Set version 52 | run: echo "RELEASE_VERSION=${GITHUB_REF#refs/*/}" >> $GITHUB_ENV 53 | 54 | - name: Set current date 55 | run: | 56 | echo "RELEASE_DATE=$(date +"%d %B %Y")" >> $GITHUB_ENV 57 | 58 | - name: Get version from tag 59 | id: tag_name 60 | run: | 61 | echo ::set-output name=current_version::${GITHUB_REF#refs/tags/v} 62 | 63 | - name: Get Changelog Entry 64 | id: changelog_reader 65 | uses: mindsers/changelog-reader-action@v2 66 | with: 67 | validation_level: none 68 | version: ${{ steps.tag_name.outputs.current_version }} 69 | path: ./CHANGELOG.md 70 | 71 | - name: Compute checksums 72 | run: | 73 | echo "## ${{ env.RELEASE_VERSION }} (${{ env.RELEASE_DATE }})" >> checksums.md 74 | echo "${{ steps.changelog_reader.outputs.changes }}" >> checksums.md 75 | echo "" >> checksums.md 76 | echo "" >> checksums.md 77 | 78 | - name: Release 79 | uses: softprops/action-gh-release@v1 80 | with: 81 | prerelease: false 82 | body_path: checksums.md 83 | files: | 84 | LICENSE 85 | env: 86 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 87 | 88 | notify-community: 89 | needs: [create-release] 90 | runs-on: ubuntu-latest 91 | steps: 92 | - name: Checkout 93 | uses: actions/checkout@v2 94 | - name: Get version from tag 95 | id: tag_name 96 | run: | 97 | echo ::set-output name=current_version::${GITHUB_REF#refs/tags/v} 98 | - name: Post to the community Slack channel 99 | uses: slackapi/slack-github-action@v1.23.0 100 | with: 101 | channel-id: 'C04KT9JNRHS' 102 | payload: | 103 | { 104 | "text": "[Release] Baselime Opentelemetry for Node.JS Lambda v${{ steps.tag_name.outputs.current_version }}", 105 | "blocks": [ 106 | { 107 | "type": "section", 108 | "text": { 109 | "type": "mrkdwn", 110 | "text": "*[Release] Baselime Opentelemetry for Node.JS Lambda v${{ steps.tag_name.outputs.current_version }}*" 111 | } 112 | }, 113 | { 114 | "type": "section", 115 | "text": { 116 | "type": "mrkdwn", 117 | "text": "" 118 | } 119 | } 120 | ] 121 | } 122 | env: 123 | SLACK_BOT_TOKEN: ${{ secrets.SLACK_BOT_TOKEN }} 124 | 125 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # dependencies 2 | node_modules 3 | 4 | # sst 5 | .sst 6 | .build 7 | .serverless 8 | dist 9 | # opennext 10 | .open-next 11 | 12 | # published 13 | index.js 14 | lambda-wrapper.js 15 | loader.js 16 | handler.cjs 17 | handler.mjs 18 | !src/handler.cjs 19 | !src/handler.mjs 20 | # misc 21 | .DS_Store 22 | 23 | # local env files 24 | .env*.local 25 | node-tracing.zip -------------------------------------------------------------------------------- /.release-it.json: -------------------------------------------------------------------------------- 1 | { 2 | "github": { 3 | "release": true 4 | }, 5 | "git": { 6 | "tagName": "v${version}" 7 | }, 8 | "npm": { 9 | "publish": false 10 | }, 11 | "plugins": { 12 | "@release-it/keep-a-changelog": { 13 | "filename": "CHANGELOG.md" 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | "name": "Debug SST Start", 6 | "type": "node", 7 | "request": "launch", 8 | "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/sst", 9 | "runtimeArgs": ["start", "--increase-timeout"], 10 | "console": "integratedTerminal", 11 | "skipFiles": ["/**"], 12 | "env": {} 13 | } 14 | ] 15 | } 16 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "search.exclude": { 3 | "**/.sst": true 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | 6 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). 7 | 8 | ## [0.5.7] - 2024-04-11 9 | 10 | * Add disabling of req and response capture with envs 11 | 12 | ## [0.5.6] - 2024-04-03 13 | 14 | * AWS SDK Instrumentation - capture request info in pre-request hook 15 | 16 | ## [0.5.5] - 2024-03-28 17 | 18 | * Fix: don't swallow lambda errors 19 | 20 | ## [0.5.4] - 2024-03-28 21 | 22 | * upgrade step function tracing 23 | 24 | ## [0.5.3] - 2024-03-27 25 | 26 | * Fix deploy 27 | 28 | ## [0.5.2] - 2024-03-27 29 | 30 | * fix deploy 31 | 32 | ## [0.5.1] - 2024-03-27 33 | 34 | * Deploy to all regions 35 | 36 | ## [0.5.0] - 2024-03-27 37 | 38 | - step function tracing 39 | 40 | ## [0.3.10] - 2024-03-05 41 | 42 | * configure github auth 43 | 44 | ## [0.3.9] - 2024-03-05 45 | 46 | * fix ci 47 | 48 | ## [0.3.8] - 2024-03-04 49 | 50 | * Uses @baselime/node-opentelemetry as core 51 | 52 | ## [0.3.7] - 2024-01-30 53 | 54 | - Add sa-east-1 55 | 56 | ## [0.3.6] - 2023-12-11 57 | 58 | - fallback if request data cannot be parsed 59 | 60 | ## [0.3.5] - 2023-12-07 61 | 62 | - upgrade ci node version 63 | 64 | ## [0.3.4] - 2023-12-06 65 | 66 | - updating deps 67 | 68 | ## [0.3.3] - 2023-11-28 69 | 70 | - Hide esm loader error log 71 | 72 | ## [0.3.2] - 2023-11-09 73 | 74 | - support lowercase headers 75 | - remove json parsing error log in fallback 76 | 77 | ## [0.3.1] - 2023-11-06 78 | 79 | - fix ci 80 | - 81 | ## [0.3.0] - 2023-11-06 82 | 83 | - fix json parsing 84 | ## [0.2.22] - 2023-10-29 85 | 86 | - make http request body parsing safer 87 | 88 | ## [0.2.21] - 2023-10-23 89 | 90 | - ensure .cjs files are imported 91 | - parse request bodys if the content type is json 92 | 93 | ## [0.2.20] 2023-09-20 94 | 95 | - add eu-north-1 96 | 97 | ## [0.2.19] 2023-09-04 98 | 99 | - fix loading for default exports 100 | - remove span logger 101 | 102 | ## [0.2.16] 2023-09-04 103 | 104 | - fix loading for default exports 105 | 106 | ## [0.2.15] 2023-09-04 107 | 108 | - add cjs to extension for otel extension so it loads in all node environments 109 | - add esm build for wrapper 110 | ## [0.2.10] 2023-09-03 111 | 112 | - fix manual setup build 113 | 114 | ## [0.2.8] 2023-09-03 115 | 116 | - don't enrich span for outgoing trace http post 117 | - 118 | ## [0.2.7] 2023-09-03 119 | 120 | - don't enrich span for outgoing trace http post 121 | 122 | ## [0.2.6] 2023-09-03 123 | 124 | - fix build 125 | 126 | ## [0.2.4] 2023-09-02 127 | 128 | - Parse and instrument request bodies 129 | 130 | ## [0.2.3] 2023-09-02 131 | 132 | - remove gzip 133 | 134 | ## [0.2.2] 2023-09-01 135 | 136 | - Coldstart improvements 137 | - 138 | ## [0.2.1] 2023-08-08 139 | 140 | - Add better loading diagnostics 141 | - 142 | 143 | The latest layer is: `arn:aws:lambda:${your-region-here}:097948374213:layer:baselime-node:20` 144 | 145 | ## [0.2.0] 2023-08-07 146 | 147 | - fix importing of cjs from esm loader 148 | 149 | 150 | ## [0.1.19] 2023-08-06 151 | 152 | - Improve diagnostics on import error 153 | 154 | The latest layer is: `arn:aws:lambda:${your-region-here}:097948374213:layer:baselime-node:1` 155 | 156 | ## [0.1.18] 2023-07-24 157 | 158 | - Improved robustness of callback support 159 | 160 | 161 | The latest layer is: `arn:aws:lambda:${your-region-here}:097948374213:layer:baselime-node:18` 162 | 163 | ## [0.1.17] 2023-07-24 164 | 165 | - fix callback support 166 | 167 | 168 | The latest layer is: `arn:aws:lambda:${your-region-here}:097948374213:layer:baselime-node:13` 169 | 170 | ## [0.1.16] 2023-07-17 171 | 172 | - fix 173 | 174 | The latest layer is: `arn:aws:lambda:${your-region-here}:097948374213:layer:baselime-node:12` 175 | 176 | ## [0.1.15] 2023-07-17 177 | 178 | - Add support for callback based lambda functions 179 | 180 | 181 | 182 | The latest layer is: `arn:aws:lambda:${your-region-here}:097948374213:layer:baselime-node:11` 183 | 184 | ## [0.1.14] 2023-07-07 185 | 186 | - Add lots of aws lambda resource spans 187 | - GZIP 188 | 189 | 190 | The latest layer is: `arn:aws:lambda:${your-region-here}:097948374213:layer:baselime-node:8` 191 | 192 | ## [0.1.13] 2023-07-05 193 | 194 | - Make sure flushing is not canceled 195 | 196 | ## [0.1.12] 2023-06-28 197 | 198 | - publish via CI 199 | - Fix: auto-loader paths 200 | 201 | The latest layer is: `arn:aws:lambda:${your-region-here}:097948374213:layer:baselime-node:6` 202 | 203 | ## [0.1.11] 2023-07-22 204 | 205 | - publish via CI 206 | - Fix: auto-loader paths 207 | 208 | 209 | The latest layer is: `arn:aws:lambda:${your-region-here}:097948374213:layer:baselime-node:4` 210 | 211 | ## [0.1.6] 2023-07-21 212 | 213 | - Add esm auto loading 214 | - Add logging extension 215 | 216 | 217 | The latest layer is: `arn:aws:lambda:${your-region-here}:374211872663:layer:baselime-node:8` 218 | 219 | 220 | The latest layer is: `arn:aws:lambda:${your-region-here}:374211872663:layer:baselime-node:9` 221 | 222 | ## [0.1.4] 2023-07-16 223 | 224 | - Added support for the baselime-extension to forward open telemetry data 225 | - Added support for esm and bundlers with `baselime.wrap` 226 | 227 | ## [0.1.2] 2023-07-15 228 | 229 | ## [0.1.1] 2023-07-15 230 | 231 | ## [0.0.13] 2023-05-17 232 | 233 | ### Added 234 | - Improved environment variables BASELIME_OTEL_KEY -> BASELIME_KEY 235 | - Service discovery 236 | 237 | ## [0.0.11] 2023-05-17 238 | 239 | ### Added 240 | - Changelog 241 | -------------------------------------------------------------------------------- /Contributing.md: -------------------------------------------------------------------------------- 1 | # Contributing to Baselime AWS Lambda Node.js OpenTelemetry 2 | 3 | You want to help improve the Baselime AWS Lambda Node.js OpenTelemetry? Awesome, thank you! 4 | 5 | ## Reporting Issues 6 | 7 | Bugs, feature requests, and development-related questions should be directed to our [GitHub issue tracker](https://github.com/baselime/lambda-node-opentelemetry/issues). 8 | 9 | When reporting a bug, please try and provide as much context as possible such as your operating system, Node version, and anything else that might be relevant to the bug. For feature requests, please explain what you're trying to do, and how the requested feature would help you do that. 10 | 11 | ## Building and Packaging the project 12 | 13 | ### Prerequisites: 14 | 15 | - Node 16.15+ Installed. 16 | 17 | ```shell 18 | $ npm run build 19 | ``` 20 | 21 | ## Setup 22 | 23 | [Fork](https://github.com/baselime/lambda-node-opentelemetry) then clone this repository: 24 | 25 | ``` 26 | $ git clone https://github.com/baselime/lambda-node-opentelemetry.git 27 | $ cd lambda-node-opentelemetry 28 | $ npm ci 29 | ``` 30 | -------------------------------------------------------------------------------- /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 {2023} {Baselime Limited} 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 | # Lambda Opentelemetry for Node.JS 2 | [![Documentation][docs_badge]][docs] 3 | [![Latest Release][release_badge]][release] 4 | [![License][license_badge]][license] 5 | 6 | > Don't install this package - add it via the `baselime:tracing` tag 7 | 8 | 9 | The `@baselime/lambda-node-opentelemetry` package instruments your Node.js AWS Lambda functions with OpenTelemetry and automatically sends tracing data to Baselime. This is the most powerful and flexible way to instrument your serverless functions. 10 | 11 | ![Trace Timeline](trace-timeline.png) 12 | 13 | ### Automatic Installation 14 | 15 | Once you've connected your AWS account to Baselime, add the `baselime:tracing` tag to any of your Node.js AWS Lambda functions and it will be automatically instrumented with OpenTelemetry. 16 | 17 | ## License 18 | 19 | © Baselime Limited, 2023 20 | 21 | Distributed under Apache 2 License (`Apache-2.0`). 22 | 23 | See [LICENSE](LICENSE) for more information. 24 | 25 | 26 | 27 | [docs]: https://baselime.io/docs/ 28 | [docs_badge]: https://img.shields.io/badge/docs-reference-blue.svg?style=flat-square 29 | [release]: https://github.com/baselime/lambda-node-opentelemetry/releases/latest 30 | [release_badge]: https://img.shields.io/github/release/baselime/lambda-node-opentelemetry.svg?style=flat-square&ghcache=unused 31 | [license]: https://opensource.org/licenses/MIT 32 | [license_badge]: https://img.shields.io/github/license/baselime/lambda-node-opentelemetry.svg?color=blue&style=flat-square&ghcache=unused 33 | -------------------------------------------------------------------------------- /e2e/arc/app.arc: -------------------------------------------------------------------------------- 1 | @app 2 | tracer-node-arc-example 3 | 4 | @http 5 | get / 6 | 7 | @aws 8 | # profile default 9 | region eu-west-2 10 | architecture arm64 11 | -------------------------------------------------------------------------------- /e2e/arc/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "your-app", 3 | "version": "0.0.0", 4 | "description": "A fresh new Architect project!", 5 | "scripts": { 6 | "predeploy": "cd ../.. && npm run build && cd examples/arc && cp ../../lambda-wrapper.js ./", 7 | "deploy": "arc deploy", 8 | "start": "npx sandbox" 9 | }, 10 | "devDependencies": { 11 | "@architect/architect": "^10.16.3" 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /e2e/arc/sam.json: -------------------------------------------------------------------------------- 1 | { 2 | "AWSTemplateFormatVersion": "2010-09-09", 3 | "Transform": "AWS::Serverless-2016-10-31", 4 | "Description": "Exported by architect/package@8.2.2 on 2023-01-13T12:12:46.360Z", 5 | "Resources": { 6 | "Role": { 7 | "Type": "AWS::IAM::Role", 8 | "Properties": { 9 | "AssumeRolePolicyDocument": { 10 | "Version": "2012-10-17", 11 | "Statement": [ 12 | { 13 | "Effect": "Allow", 14 | "Principal": { 15 | "Service": "lambda.amazonaws.com" 16 | }, 17 | "Action": "sts:AssumeRole" 18 | } 19 | ] 20 | }, 21 | "Policies": [ 22 | { 23 | "PolicyName": "ArcGlobalPolicy", 24 | "PolicyDocument": { 25 | "Statement": [ 26 | { 27 | "Effect": "Allow", 28 | "Action": [ 29 | "logs:CreateLogGroup", 30 | "logs:CreateLogStream", 31 | "logs:PutLogEvents", 32 | "logs:DescribeLogStreams" 33 | ], 34 | "Resource": "arn:aws:logs:*:*:*" 35 | } 36 | ] 37 | } 38 | }, 39 | { 40 | "PolicyName": "ArcStaticBucketPolicy", 41 | "PolicyDocument": { 42 | "Statement": [ 43 | { 44 | "Effect": "Allow", 45 | "Action": [ 46 | "s3:GetObject", 47 | "s3:PutObject", 48 | "s3:PutObjectAcl", 49 | "s3:DeleteObject", 50 | "s3:ListBucket" 51 | ], 52 | "Resource": [ 53 | { 54 | "Fn::Sub": [ 55 | "arn:aws:s3:::${bukkit}", 56 | { 57 | "bukkit": { 58 | "Ref": "StaticBucket" 59 | } 60 | } 61 | ] 62 | }, 63 | { 64 | "Fn::Sub": [ 65 | "arn:aws:s3:::${bukkit}/*", 66 | { 67 | "bukkit": { 68 | "Ref": "StaticBucket" 69 | } 70 | } 71 | ] 72 | } 73 | ] 74 | } 75 | ] 76 | } 77 | } 78 | ] 79 | } 80 | }, 81 | "StaticBucketParam": { 82 | "Type": "AWS::SSM::Parameter", 83 | "Properties": { 84 | "Type": "String", 85 | "Name": { 86 | "Fn::Sub": [ 87 | "/${AWS::StackName}/static/${key}", 88 | { 89 | "key": "bucket" 90 | } 91 | ] 92 | }, 93 | "Value": { 94 | "Ref": "StaticBucket" 95 | } 96 | } 97 | }, 98 | "StaticFingerprintParam": { 99 | "Type": "AWS::SSM::Parameter", 100 | "Properties": { 101 | "Type": "String", 102 | "Name": { 103 | "Fn::Sub": [ 104 | "/${AWS::StackName}/static/${key}", 105 | { 106 | "key": "fingerprint" 107 | } 108 | ] 109 | }, 110 | "Value": "false" 111 | } 112 | }, 113 | "ParameterStorePolicy": { 114 | "Type": "AWS::IAM::Policy", 115 | "DependsOn": "Role", 116 | "Properties": { 117 | "PolicyName": "ArcParameterStorePolicy", 118 | "PolicyDocument": { 119 | "Statement": [ 120 | { 121 | "Effect": "Allow", 122 | "Action": [ 123 | "ssm:GetParametersByPath", 124 | "ssm:GetParameter" 125 | ], 126 | "Resource": { 127 | "Fn::Sub": [ 128 | "arn:aws:ssm:${AWS::Region}:${AWS::AccountId}:parameter/${AWS::StackName}", 129 | {} 130 | ] 131 | } 132 | }, 133 | { 134 | "Effect": "Allow", 135 | "Action": [ 136 | "ssm:GetParametersByPath", 137 | "ssm:GetParameter" 138 | ], 139 | "Resource": { 140 | "Fn::Sub": [ 141 | "arn:aws:ssm:${AWS::Region}:${AWS::AccountId}:parameter/${AWS::StackName}/*", 142 | {} 143 | ] 144 | } 145 | }, 146 | { 147 | "Effect": "Allow", 148 | "Action": [ 149 | "ssm:GetParametersByPath", 150 | "ssm:GetParameter" 151 | ], 152 | "Resource": { 153 | "Fn::Sub": [ 154 | "arn:aws:ssm:${AWS::Region}:${AWS::AccountId}:parameter/${AWS::StackName}/*/*", 155 | {} 156 | ] 157 | } 158 | } 159 | ] 160 | }, 161 | "Roles": [ 162 | { 163 | "Ref": "Role" 164 | } 165 | ] 166 | } 167 | }, 168 | "HTTP": { 169 | "Type": "AWS::Serverless::HttpApi", 170 | "Properties": { 171 | "StageName": "$default", 172 | "DefinitionBody": { 173 | "openapi": "3.0.1", 174 | "info": { 175 | "title": { 176 | "Ref": "AWS::StackName" 177 | } 178 | }, 179 | "paths": { 180 | "/": { 181 | "get": { 182 | "x-amazon-apigateway-integration": { 183 | "payloadFormatVersion": "2.0", 184 | "type": "aws_proxy", 185 | "httpMethod": "POST", 186 | "uri": { 187 | "Fn::Sub": "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${GetIndexHTTPLambda.Arn}/invocations" 188 | }, 189 | "connectionType": "INTERNET" 190 | } 191 | } 192 | }, 193 | "/_static/{proxy+}": { 194 | "get": { 195 | "x-amazon-apigateway-integration": { 196 | "payloadFormatVersion": "1.0", 197 | "type": "http_proxy", 198 | "httpMethod": "GET", 199 | "uri": { 200 | "Fn::Sub": [ 201 | "https://${bukkit}.s3.${AWS::Region}.amazonaws.com/{proxy}", 202 | { 203 | "bukkit": { 204 | "Ref": "StaticBucket" 205 | } 206 | } 207 | ] 208 | }, 209 | "connectionType": "INTERNET", 210 | "timeoutInMillis": 30000 211 | } 212 | } 213 | } 214 | } 215 | } 216 | } 217 | }, 218 | "GetIndexHTTPLambda": { 219 | "Type": "AWS::Serverless::Function", 220 | "Properties": { 221 | "Handler": "index.handler", 222 | "CodeUri": "/home/user/Baselime/tracer-node/examples/arc/src/http/get-index", 223 | "Runtime": "nodejs16.x", 224 | "Architectures": [ 225 | "arm64" 226 | ], 227 | "MemorySize": 1152, 228 | "EphemeralStorage": { 229 | "Size": 512 230 | }, 231 | "Timeout": 5, 232 | "Environment": { 233 | "Variables": { 234 | "ARC_APP_NAME": "tracer-node-arc-example", 235 | "ARC_ENV": "staging", 236 | "ARC_ROLE": { 237 | "Ref": "Role" 238 | }, 239 | "ARC_SESSION_TABLE_NAME": "jwe", 240 | "ARC_STACK_NAME": { 241 | "Ref": "AWS::StackName" 242 | }, 243 | "ARC_STATIC_BUCKET": { 244 | "Ref": "StaticBucket" 245 | }, 246 | "ARC_STATIC_SPA": false, 247 | "BASELIME_SERVICE": "arc-example", 248 | "BASELIME_OTEL_KEY": "fViVVRCY3LNmHAkySOZj1I2bWiJRufo7ltTW1Fka", 249 | "NODE_OPTIONS": "node_modules/@architect/shared/lambda-wrapper.js" 250 | } 251 | }, 252 | "Role": { 253 | "Fn::Sub": [ 254 | "arn:aws:iam::${AWS::AccountId}:role/${roleName}", 255 | { 256 | "roleName": { 257 | "Ref": "Role" 258 | } 259 | } 260 | ] 261 | }, 262 | "Events": { 263 | "GetIndexHTTPEvent": { 264 | "Type": "HttpApi", 265 | "Properties": { 266 | "Path": "/", 267 | "Method": "GET", 268 | "ApiId": { 269 | "Ref": "HTTP" 270 | } 271 | } 272 | } 273 | } 274 | } 275 | }, 276 | "StaticBucket": { 277 | "Type": "AWS::S3::Bucket", 278 | "Properties": { 279 | "OwnershipControls": { 280 | "Rules": [ 281 | { 282 | "ObjectOwnership": "BucketOwnerEnforced" 283 | } 284 | ] 285 | }, 286 | "WebsiteConfiguration": { 287 | "IndexDocument": "index.html", 288 | "ErrorDocument": "404.html" 289 | } 290 | } 291 | }, 292 | "StaticBucketPolicy": { 293 | "Type": "AWS::S3::BucketPolicy", 294 | "Properties": { 295 | "Bucket": { 296 | "Ref": "StaticBucket" 297 | }, 298 | "PolicyDocument": { 299 | "Version": "2012-10-17", 300 | "Statement": [ 301 | { 302 | "Action": [ 303 | "s3:GetObject" 304 | ], 305 | "Effect": "Allow", 306 | "Principal": "*", 307 | "Resource": [ 308 | { 309 | "Fn::Sub": [ 310 | "arn:aws:s3:::${bukkit}/*", 311 | { 312 | "bukkit": { 313 | "Ref": "StaticBucket" 314 | } 315 | } 316 | ] 317 | } 318 | ], 319 | "Sid": "PublicReadGetObject" 320 | } 321 | ] 322 | } 323 | } 324 | } 325 | }, 326 | "Outputs": { 327 | "API": { 328 | "Description": "API Gateway (HTTP)", 329 | "Value": { 330 | "Fn::Sub": [ 331 | "https://${ApiId}.execute-api.${AWS::Region}.amazonaws.com", 332 | { 333 | "ApiId": { 334 | "Ref": "HTTP" 335 | } 336 | } 337 | ] 338 | } 339 | }, 340 | "ApiId": { 341 | "Description": "API ID (ApiId)", 342 | "Value": { 343 | "Ref": "HTTP" 344 | } 345 | }, 346 | "BucketURL": { 347 | "Description": "Bucket URL", 348 | "Value": { 349 | "Fn::Sub": [ 350 | "http://${bukkit}.s3-website.${AWS::Region}.amazonaws.com", 351 | { 352 | "bukkit": { 353 | "Ref": "StaticBucket" 354 | } 355 | } 356 | ] 357 | } 358 | } 359 | } 360 | } -------------------------------------------------------------------------------- /e2e/arc/sam.yaml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: '2010-09-09' 2 | Transform: AWS::Serverless-2016-10-31 3 | Description: Exported by architect/package@8.2.2 on 2023-01-13T12:12:46.360Z 4 | Resources: 5 | Role: 6 | Type: AWS::IAM::Role 7 | Properties: 8 | AssumeRolePolicyDocument: 9 | Version: '2012-10-17' 10 | Statement: 11 | - Effect: Allow 12 | Principal: 13 | Service: lambda.amazonaws.com 14 | Action: sts:AssumeRole 15 | Policies: 16 | - PolicyName: ArcGlobalPolicy 17 | PolicyDocument: 18 | Statement: 19 | - Effect: Allow 20 | Action: 21 | - logs:CreateLogGroup 22 | - logs:CreateLogStream 23 | - logs:PutLogEvents 24 | - logs:DescribeLogStreams 25 | Resource: arn:aws:logs:*:*:* 26 | - PolicyName: ArcStaticBucketPolicy 27 | PolicyDocument: 28 | Statement: 29 | - Effect: Allow 30 | Action: 31 | - s3:GetObject 32 | - s3:PutObject 33 | - s3:PutObjectAcl 34 | - s3:DeleteObject 35 | - s3:ListBucket 36 | Resource: 37 | - Fn::Sub: 38 | - arn:aws:s3:::${bukkit} 39 | - bukkit: 40 | Ref: StaticBucket 41 | - Fn::Sub: 42 | - arn:aws:s3:::${bukkit}/* 43 | - bukkit: 44 | Ref: StaticBucket 45 | StaticBucketParam: 46 | Type: AWS::SSM::Parameter 47 | Properties: 48 | Type: String 49 | Name: 50 | Fn::Sub: 51 | - /${AWS::StackName}/static/${key} 52 | - key: bucket 53 | Value: 54 | Ref: StaticBucket 55 | StaticFingerprintParam: 56 | Type: AWS::SSM::Parameter 57 | Properties: 58 | Type: String 59 | Name: 60 | Fn::Sub: 61 | - /${AWS::StackName}/static/${key} 62 | - key: fingerprint 63 | Value: 'false' 64 | ParameterStorePolicy: 65 | Type: AWS::IAM::Policy 66 | DependsOn: Role 67 | Properties: 68 | PolicyName: ArcParameterStorePolicy 69 | PolicyDocument: 70 | Statement: 71 | - Effect: Allow 72 | Action: 73 | - ssm:GetParametersByPath 74 | - ssm:GetParameter 75 | Resource: 76 | Fn::Sub: 77 | - arn:aws:ssm:${AWS::Region}:${AWS::AccountId}:parameter/${AWS::StackName} 78 | - {} 79 | - Effect: Allow 80 | Action: 81 | - ssm:GetParametersByPath 82 | - ssm:GetParameter 83 | Resource: 84 | Fn::Sub: 85 | - arn:aws:ssm:${AWS::Region}:${AWS::AccountId}:parameter/${AWS::StackName}/* 86 | - {} 87 | - Effect: Allow 88 | Action: 89 | - ssm:GetParametersByPath 90 | - ssm:GetParameter 91 | Resource: 92 | Fn::Sub: 93 | - arn:aws:ssm:${AWS::Region}:${AWS::AccountId}:parameter/${AWS::StackName}/*/* 94 | - {} 95 | Roles: 96 | - Ref: Role 97 | HTTP: 98 | Type: AWS::Serverless::HttpApi 99 | Properties: 100 | StageName: $default 101 | DefinitionBody: 102 | openapi: 3.0.1 103 | info: 104 | title: 105 | Ref: AWS::StackName 106 | paths: 107 | /: 108 | get: 109 | x-amazon-apigateway-integration: 110 | payloadFormatVersion: '2.0' 111 | type: aws_proxy 112 | httpMethod: POST 113 | uri: 114 | Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${GetIndexHTTPLambda.Arn}/invocations 115 | connectionType: INTERNET 116 | /_static/{proxy+}: 117 | get: 118 | x-amazon-apigateway-integration: 119 | payloadFormatVersion: '1.0' 120 | type: http_proxy 121 | httpMethod: GET 122 | uri: 123 | Fn::Sub: 124 | - https://${bukkit}.s3.${AWS::Region}.amazonaws.com/{proxy} 125 | - bukkit: 126 | Ref: StaticBucket 127 | connectionType: INTERNET 128 | timeoutInMillis: 30000 129 | GetIndexHTTPLambda: 130 | Type: AWS::Serverless::Function 131 | Properties: 132 | Handler: index.handler 133 | CodeUri: s3://tracer-node-arc-example-cfn-deployments-fc981/6e414c18c85c0813412b4f90bcce740a 134 | Runtime: nodejs16.x 135 | Architectures: 136 | - arm64 137 | MemorySize: 1152 138 | EphemeralStorage: 139 | Size: 512 140 | Timeout: 5 141 | Environment: 142 | Variables: 143 | ARC_APP_NAME: tracer-node-arc-example 144 | ARC_ENV: staging 145 | ARC_ROLE: 146 | Ref: Role 147 | ARC_SESSION_TABLE_NAME: jwe 148 | ARC_STACK_NAME: 149 | Ref: AWS::StackName 150 | ARC_STATIC_BUCKET: 151 | Ref: StaticBucket 152 | ARC_STATIC_SPA: false 153 | BASELIME_SERVICE: arc-example 154 | BASELIME_OTEL_KEY: fViVVRCY3LNmHAkySOZj1I2bWiJRufo7ltTW1Fka 155 | NODE_OPTIONS: node_modules/@architect/shared/lambda-wrapper.js 156 | Role: 157 | Fn::Sub: 158 | - arn:aws:iam::${AWS::AccountId}:role/${roleName} 159 | - roleName: 160 | Ref: Role 161 | Events: 162 | GetIndexHTTPEvent: 163 | Type: HttpApi 164 | Properties: 165 | Path: / 166 | Method: GET 167 | ApiId: 168 | Ref: HTTP 169 | StaticBucket: 170 | Type: AWS::S3::Bucket 171 | Properties: 172 | OwnershipControls: 173 | Rules: 174 | - ObjectOwnership: BucketOwnerEnforced 175 | WebsiteConfiguration: 176 | IndexDocument: index.html 177 | ErrorDocument: 404.html 178 | StaticBucketPolicy: 179 | Type: AWS::S3::BucketPolicy 180 | Properties: 181 | Bucket: 182 | Ref: StaticBucket 183 | PolicyDocument: 184 | Version: '2012-10-17' 185 | Statement: 186 | - Action: 187 | - s3:GetObject 188 | Effect: Allow 189 | Principal: '*' 190 | Resource: 191 | - Fn::Sub: 192 | - arn:aws:s3:::${bukkit}/* 193 | - bukkit: 194 | Ref: StaticBucket 195 | Sid: PublicReadGetObject 196 | Outputs: 197 | API: 198 | Description: API Gateway (HTTP) 199 | Value: 200 | Fn::Sub: 201 | - https://${ApiId}.execute-api.${AWS::Region}.amazonaws.com 202 | - ApiId: 203 | Ref: HTTP 204 | ApiId: 205 | Description: API ID (ApiId) 206 | Value: 207 | Ref: HTTP 208 | BucketURL: 209 | Description: Bucket URL 210 | Value: 211 | Fn::Sub: 212 | - http://${bukkit}.s3-website.${AWS::Region}.amazonaws.com 213 | - bukkit: 214 | Ref: StaticBucket 215 | -------------------------------------------------------------------------------- /e2e/benchmarking/.gitignore: -------------------------------------------------------------------------------- 1 | # dependencies 2 | node_modules 3 | 4 | # sst 5 | .sst 6 | .build 7 | 8 | # opennext 9 | .open-next 10 | 11 | # misc 12 | .DS_Store 13 | 14 | # local env files 15 | .env*.local 16 | -------------------------------------------------------------------------------- /e2e/benchmarking/.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | "name": "Debug SST Start", 6 | "type": "node", 7 | "request": "launch", 8 | "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/sst", 9 | "runtimeArgs": ["start", "--increase-timeout"], 10 | "console": "integratedTerminal", 11 | "skipFiles": ["/**"], 12 | "env": {} 13 | } 14 | ] 15 | } 16 | -------------------------------------------------------------------------------- /e2e/benchmarking/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "search.exclude": { 3 | "**/.sst": true 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /e2e/benchmarking/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "benchmarking", 3 | "version": "0.0.0", 4 | "private": true, 5 | "type": "module", 6 | "scripts": { 7 | "dev": "sst dev", 8 | "build": "sst build", 9 | "deploy": "sst deploy", 10 | "remove": "sst remove", 11 | "console": "sst console", 12 | "typecheck": "tsc --noEmit" 13 | }, 14 | "devDependencies": { 15 | "sst": "^2.26.6", 16 | "aws-cdk-lib": "2.95.1", 17 | "constructs": "10.2.69", 18 | "typescript": "^5.2.2", 19 | "@tsconfig/node18": "^18.2.2" 20 | }, 21 | "workspaces": [ 22 | "packages/*" 23 | ] 24 | } -------------------------------------------------------------------------------- /e2e/benchmarking/packages/functions/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@benchmarking/functions", 3 | "version": "0.0.0", 4 | "type": "module", 5 | "scripts": { 6 | "test": "sst bind vitest", 7 | "typecheck": "tsc -noEmit" 8 | }, 9 | "devDependencies": { 10 | "@types/node": "^20.7.0", 11 | "@types/aws-lambda": "^8.10.122", 12 | "vitest": "^0.34.5", 13 | "sst": "^2.26.6" 14 | } 15 | } -------------------------------------------------------------------------------- /e2e/benchmarking/packages/functions/src/lambda.ts: -------------------------------------------------------------------------------- 1 | import { ApiHandler } from "sst/node/api"; 2 | 3 | export const handler = ApiHandler(async (_evt) => { 4 | // simulate a 100ms delay 5 | await new Promise((resolve) => setTimeout(resolve, 100)); 6 | return { 7 | statusCode: 200, 8 | body: `Hello world. The time is ${new Date().toISOString()}`, 9 | }; 10 | }); 11 | -------------------------------------------------------------------------------- /e2e/benchmarking/packages/functions/sst-env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | -------------------------------------------------------------------------------- /e2e/benchmarking/packages/functions/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "@tsconfig/node18/tsconfig.json", 3 | "compilerOptions": { 4 | "module": "esnext", 5 | "moduleResolution": "node", 6 | "baseUrl": ".", 7 | "paths": { 8 | "@benchmarking/core/*": ["../core/src/*"] 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /e2e/benchmarking/pnpm-workspace.yaml: -------------------------------------------------------------------------------- 1 | packages: 2 | - "packages/**/*" 3 | -------------------------------------------------------------------------------- /e2e/benchmarking/sst.config.ts: -------------------------------------------------------------------------------- 1 | import { SSTConfig } from "sst"; 2 | import { API } from "./stacks/MyStack"; 3 | 4 | export default { 5 | config(_input) { 6 | return { 7 | name: "benchmarking", 8 | region: "eu-west-2", 9 | }; 10 | }, 11 | stacks(app) { 12 | app.setDefaultFunctionProps({ 13 | architecture: "arm_64", 14 | }) 15 | app.stack(API); 16 | } 17 | } satisfies SSTConfig; 18 | -------------------------------------------------------------------------------- /e2e/benchmarking/stacks/MyStack.ts: -------------------------------------------------------------------------------- 1 | import { StackContext, Api, EventBus } from "sst/constructs"; 2 | 3 | const environment = (handler: string) => ({ 4 | "AWS_LAMBDA_EXEC_WRAPPER": "/opt/baselime", 5 | "BASELIME_ACTUAL_HANDLER": handler, 6 | "BASELIME_KEY": "gB8vt7EOWH25VzkHtwJRe9hzZIOE70ZaSueQJwH2", 7 | "BASELIME_SURPRESS_EXTENSION_LOGS": "true", 8 | "COLLECTOR_URL": "https://otel.baselime.cc" 9 | }) 10 | 11 | const handler = "/opt/nodejs/node_modules/@baselime/lambda-node-opentelemetry/handler.handler"; 12 | 13 | 14 | export function API({ stack }: StackContext) { 15 | const api = new Api(stack, "api", { 16 | routes: { 17 | "GET /no-tracing": { function: { handler: "packages/functions/src/lambda.handler" } }, 18 | "GET /both": { function: { handler: "packages/functions/src/lambda.handler", layers: ["arn:aws:lambda:eu-west-2:374211872663:layer:baselime-extension-arm64:11", "arn:aws:lambda:eu-west-2:374211872663:layer:baselime-node:56"] } }, 19 | "GET /tracing": { function: { handler: "packages/functions/src/lambda.handler", layers: ["arn:aws:lambda:eu-west-2:374211872663:layer:baselime-node:56"] } }, 20 | "GET /extension": { function: { handler: "packages/functions/src/lambda.handler", layers: ["arn:aws:lambda:eu-west-2:374211872663:layer:baselime-extension-arm64:11"] } }, 21 | "GET /combined": { function: { handler: "packages/functions/src/lambda.handler", layers: ["arn:aws:lambda:eu-west-2:374211872663:layer:baselime-node-combined:7"] } }, 22 | "GET /tracing-activated": { 23 | function: { 24 | // todo set handler to /opt/nodejs/node_modules/@baselime/lambda-node-opentelemetry/handler.handler when deployed 25 | handler: "packages/functions/src/lambda.handler", layers: ["arn:aws:lambda:eu-west-2:374211872663:layer:baselime-node:56"], environment: environment("packages/functions/src/lambda.handler") 26 | } 27 | }, 28 | "GET /combined-activated": { 29 | function: { 30 | handler: "packages/functions/src/lambda.handler", layers: ["arn:aws:lambda:eu-west-2:374211872663:layer:baselime-node-combined:7"], environment: environment("packages/functions/src/lambda.handler") 31 | } 32 | }, 33 | "GET /both-activated": { 34 | function: { 35 | handler: "packages/functions/src/lambda.handler", layers: ["arn:aws:lambda:eu-west-2:374211872663:layer:baselime-extension-arm64:11", "arn:aws:lambda:eu-west-2:374211872663:layer:baselime-node:56"], environment: environment("packages/functions/src/lambda.handler") 36 | } 37 | }, 38 | }, 39 | }); 40 | 41 | stack.addOutputs({ 42 | ApiEndpoint: api.url, 43 | }); 44 | } 45 | -------------------------------------------------------------------------------- /e2e/benchmarking/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "@tsconfig/node18/tsconfig.json", 3 | "exclude": ["packages"], 4 | "compilerOptions": { 5 | "module": "esnext", 6 | "moduleResolution": "node" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /e2e/serverless-webpack-babel/babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | presets: [ 3 | [ 4 | '@babel/preset-env', 5 | { 6 | targets: { 7 | node: 'current', 8 | }, 9 | }, 10 | ], 11 | ], 12 | plugins: [ 13 | "@babel/plugin-transform-modules-commonjs", 14 | "@babel/plugin-syntax-flow", 15 | "@babel/plugin-transform-flow-strip-types", 16 | "@babel/plugin-proposal-optional-chaining", 17 | [ 18 | "@babel/plugin-proposal-decorators", 19 | { 20 | "legacy": true, 21 | } 22 | ], 23 | "transform-class-properties", 24 | [ 25 | "module-resolver", 26 | { 27 | "alias": { 28 | "@": "." 29 | } 30 | } 31 | ] 32 | ], 33 | }; -------------------------------------------------------------------------------- /e2e/serverless-webpack-babel/handler.js: -------------------------------------------------------------------------------- 1 | export { default as enum } from './src/func'; -------------------------------------------------------------------------------- /e2e/serverless-webpack-babel/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "serverless-webpack-babel", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "handler.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "author": "", 10 | "license": "ISC", 11 | "devDependencies": { 12 | "@babel/core": "^7.17.9", 13 | "@babel/eslint-parser": "^7.17.0", 14 | "@babel/plugin-proposal-decorators": "^7.23.0", 15 | "@babel/plugin-proposal-optional-chaining": "^7.16.7", 16 | "@babel/plugin-syntax-flow": "^7.16.7", 17 | "@babel/plugin-transform-flow-strip-types": "^7.16.7", 18 | "@babel/plugin-transform-modules-commonjs": "^7.23.0", 19 | "@babel/preset-env": "^7.16.11", 20 | "@babel/register": "^7.17.7", 21 | "babel-loader": "^8.2.4", 22 | "babel-plugin-module-resolver": "^5.0.0", 23 | "babel-plugin-transform-class-properties": "^6.24.1", 24 | "serverless-webpack": "^5.7.0", 25 | "webpack": "^5.72.0", 26 | "webpack-node-externals": "^3.0.0" 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /e2e/serverless-webpack-babel/serverless.yml: -------------------------------------------------------------------------------- 1 | service: trace-webpack-babel 2 | 3 | 4 | plugins: 5 | - serverless-webpack 6 | 7 | provider: 8 | name: aws 9 | runtime: nodejs14.x 10 | timeout: 10 11 | region: eu-west-2 12 | architecture: arm64 13 | versionFunctions: false 14 | tags: 15 | 'baselime:tracing': true 16 | 17 | functions: 18 | hello: 19 | handler: ./handler.enum 20 | events: 21 | - httpApi: 22 | method: get 23 | path: /hello 24 | -------------------------------------------------------------------------------- /e2e/serverless-webpack-babel/src/func.js: -------------------------------------------------------------------------------- 1 | export default async (event, context) => { 2 | console.log('im alive'); 3 | return { 4 | statusCode: 200, 5 | body: JSON.stringify({ 6 | message: 'Hello World!', 7 | }) 8 | } 9 | } -------------------------------------------------------------------------------- /e2e/serverless-webpack-babel/webpack.config.js: -------------------------------------------------------------------------------- 1 | const nodeExternals = require('webpack-node-externals'); 2 | const slsw = require('serverless-webpack'); 3 | const path = require('path'); 4 | 5 | module.exports = { 6 | entry: slsw.lib.entries, 7 | mode: process.env.WEBPACK_MODE || 'production', 8 | devtool: 'source-map', 9 | target: 'node', 10 | externals: [ 11 | nodeExternals({ 12 | modulesFromFile: true, 13 | }), 14 | ], 15 | performance: { 16 | hints: false, 17 | }, 18 | output: { 19 | libraryTarget: 'commonjs', 20 | path: path.join(__dirname, '.webpack'), 21 | filename: '[name].js', 22 | sourceMapFilename: '[name].map', 23 | }, 24 | module: { 25 | rules: [ 26 | { 27 | test: /\.js?$/, 28 | exclude: /node_modules/, 29 | use: [ 30 | { 31 | loader: 'babel-loader', 32 | options: { 33 | cacheDirectory: true, 34 | }, 35 | }, 36 | ], 37 | }, 38 | ], 39 | }, 40 | resolve: { 41 | alias: { 42 | '@': path.resolve(__dirname), 43 | }, 44 | }, 45 | }; -------------------------------------------------------------------------------- /e2e/serverless/handler.js: -------------------------------------------------------------------------------- 1 | const { lambdaWrapper } = require('@baselime/lambda-node-opentelemetry'); 2 | 3 | 4 | if (!process.env.BASELIME_ORIGINAL_HANDLER) { 5 | throw Error('BASELIME_ORIGINAL_HANDLER not set'); 6 | } 7 | 8 | const [path, functionName] = process.env.BASELIME_ORIGINAL_HANDLER.split('.'); 9 | console.log(path, functionName); 10 | const originalHandler = require(path + '.js')[functionName]; 11 | 12 | export const handler = lambdaWrapper(originalHandler); -------------------------------------------------------------------------------- /e2e/serverless/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "serverless", 3 | "version": "1.0.0", 4 | "description": "", 5 | "scripts": { 6 | "aaaa": "cd ../../ && npm run build && cd examples/serverless && mkdir -p node_modules/@baselime/lambda-node-opentelemetry && cp -r ../../dist/* node_modules/@baselime/lambda-node-opentelemetry/", 7 | "deploy": "npx serverless deploy --stage prod" 8 | }, 9 | "author": "", 10 | "license": "UNLICENSED", 11 | "devDependencies": { 12 | "esbuild": "^0.16.16", 13 | "serverless": "^3.26.0", 14 | "serverless-esbuild": "^1.37.0" 15 | }, 16 | "dependencies": { 17 | "@opentelemetry/api": "1.3.0", 18 | "aws-xray-sdk": "^3.5.2", 19 | "tiny-json-http": "^7.4.2" 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /e2e/serverless/serverless.yml: -------------------------------------------------------------------------------- 1 | service: tracing 2 | 3 | package: 4 | individually: true 5 | 6 | plugins: 7 | - serverless-esbuild 8 | 9 | provider: 10 | name: aws 11 | runtime: nodejs16.x 12 | timeout: 10 13 | region: eu-west-2 14 | architecture: arm64 15 | versionFunctions: false 16 | iam: 17 | role: 18 | statements: 19 | - Effect: Allow 20 | Action: 'dynamodb:updateItem' 21 | Resource: !GetAtt DB.Arn 22 | - Effect: Allow 23 | Action: 'sns:publish' 24 | Resource: '*' 25 | - Effect: Allow 26 | Action: 'events:PutEvents' 27 | Resource: '*' 28 | tags: 29 | 'baselime:tracing': auto 30 | environment: 31 | AWS_SDK_INTERNALS: false 32 | BASELIME_REQUEST_CAPTURE: true 33 | API_URL: !GetAtt HttpApi.ApiEndpoint 34 | functions: 35 | hello: 36 | handler: src/main.handler 37 | events: 38 | - schedule: rate(10 minutes) 39 | environment: 40 | API_URL: !GetAtt HttpApi.ApiEndpoint 41 | wait-for-it: 42 | handler: src/eventbridge.handler 43 | events: 44 | - eventBridge: 45 | pattern: 46 | source: 47 | - baselime 48 | api: 49 | handler: src/api.handler 50 | events: 51 | - httpApi: 52 | method: get 53 | path: /hello 54 | environment: 55 | DB_NAME: !Ref DB 56 | TOPIC_ARN: !Ref SNSTopicDispatch 57 | dispatcher: 58 | handler: src/dispatcher.handler 59 | events: 60 | - sns: dispatch 61 | 62 | 63 | resources: 64 | Resources: 65 | DB: 66 | Type: AWS::DynamoDB::Table 67 | Properties: 68 | BillingMode: PAY_PER_REQUEST 69 | AttributeDefinitions: 70 | - AttributeName: id 71 | AttributeType: S 72 | KeySchema: 73 | - AttributeName: id 74 | KeyType: HASH 75 | 76 | -------------------------------------------------------------------------------- /e2e/serverless/src/api.js: -------------------------------------------------------------------------------- 1 | import Dynamodb from 'aws-sdk/clients/dynamodb'; 2 | import SNS from 'aws-sdk/clients/sns'; 3 | import EventBridge from 'aws-sdk/clients/eventbridge'; 4 | 5 | const dynamo = new Dynamodb(); 6 | const sns = new SNS(); 7 | const eventbridge = new EventBridge(); 8 | 9 | export const handler = async (event, context) => { 10 | context.callbackWaitForEmptyEventLoop = false; 11 | await sns.publish({ TopicArn: process.env.TOPIC_ARN, Message: 'wow much payload' }).promise() 12 | await eventbridge.putEvents({ 13 | Entries: [{ 14 | Source: 'baselime', 15 | Detail: JSON.stringify({ comment: "too many chickens" }), 16 | DetailType: 'comment', 17 | Resources: [], 18 | }] 19 | }).promise() 20 | const random = Math.random(); 21 | // if(random < 0.3) { 22 | // const response = await dynamo.updateItem({ 23 | // TableName: 'this-table-does-not-exist', 24 | // ReturnValues: 'ALL_NEW', 25 | // Key: { 26 | // id: { 27 | // S: 'test' 28 | // } 29 | // }, 30 | // UpdateExpression: 'ADD #c :c', 31 | // ExpressionAttributeNames: { 32 | // '#c': 'count' 33 | // }, 34 | // ExpressionAttributeValues: { 35 | // ':c': { N: '1' } 36 | // } 37 | // }).promise() 38 | // } 39 | const response = await dynamo.updateItem({ 40 | TableName: process.env.DB_NAME, 41 | ReturnValues: 'ALL_NEW', 42 | Key: { 43 | id: { 44 | S: 'test' 45 | } 46 | }, 47 | UpdateExpression: 'ADD #c :c', 48 | ExpressionAttributeNames: { 49 | '#c': 'count' 50 | }, 51 | ExpressionAttributeValues: { 52 | ':c': { N: '1' } 53 | } 54 | }).promise() 55 | return { 56 | statusCode: 200, 57 | body: JSON.stringify({ 58 | data: response 59 | }) 60 | } 61 | }; 62 | -------------------------------------------------------------------------------- /e2e/serverless/src/dispatcher.js: -------------------------------------------------------------------------------- 1 | 2 | exports.handler = (event, context, callback) => { 3 | context.callbackWaitForEmptyEventLoop = false; 4 | console.log(event.Records[0].Sns); 5 | return callback(null, { 6 | message: 'req processed' 7 | }) 8 | }; -------------------------------------------------------------------------------- /e2e/serverless/src/eventbridge.js: -------------------------------------------------------------------------------- 1 | 2 | exports.handler = async (event, context) => { 3 | context.callbackWaitForEmptyEventLoop = false; 4 | console.log(event) 5 | return { 6 | message: 'req processed' 7 | } 8 | }; -------------------------------------------------------------------------------- /e2e/serverless/src/main.js: -------------------------------------------------------------------------------- 1 | const { post, get } = require("tiny-json-http"); 2 | const { context, trace, } = require("@opentelemetry/api"); 3 | 4 | const { flattenObject } = require("./utils"); 5 | 6 | async function track(name, func, args) { 7 | const tracer = trace.getTracer(name); 8 | 9 | const attrIn = flattenObject(args, "name.args"); 10 | 11 | const span = tracer.startSpan(name, { 12 | attributes: attrIn, 13 | }); 14 | const ctx = trace.setSpan(context.active(), span); 15 | try { 16 | const result = await context.with(ctx, func, null, args); 17 | const attrOut = flattenObject(result, `${name}.result`); 18 | span.setAttributes(attrOut); 19 | span.end(); 20 | return result; 21 | } catch (e) { 22 | span.recordException(e); 23 | span.setAttributes(flattenObject({ name: e.name, message: e.message, stack: e.stack }, 'error')); 24 | span.end(); 25 | throw e 26 | } 27 | } 28 | 29 | function trackAll(name, lib) { 30 | const tracedLib = {}; 31 | Object.values(lib).forEach((func) => { 32 | tracedLib[func] = (args) => track(`${name}.${func}`, func, args); 33 | }); 34 | return tracedLib; 35 | } 36 | 37 | exports.handler = async (e, context) => { 38 | const { body: customer } = await get({ 39 | url: `${process.env.API_URL}/hello`, 40 | }); 41 | 42 | // await tiny.get({ url: 'https://react-rum.vercel.app/' }); 43 | 44 | await post({ 45 | url: "https://jsonplaceholder.typicode.com/posts", 46 | data: { 47 | name: 'John Doe', 48 | age: 25, 49 | email: 'john@dummyjson.com', 50 | }, 51 | }); 52 | 53 | 54 | }; 55 | -------------------------------------------------------------------------------- /e2e/serverless/src/utils.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param ob Object The object to flatten 3 | * @param prefix String (Optional) The prefix to add before each key, also used for recursion 4 | **/ 5 | export function flattenObject(ob, prefix = "", result = {}) { 6 | // Preserve empty objects and arrays, they are lost otherwise 7 | if ( 8 | prefix && 9 | typeof ob === "object" && 10 | ob !== null && 11 | Object.keys(ob).length === 0 12 | ) { 13 | result[prefix] = Array.isArray(ob) ? [] : {}; 14 | return result; 15 | } 16 | 17 | prefix = prefix ? `${prefix}.` : ""; 18 | 19 | for (const i in ob) { 20 | if (Object.prototype.hasOwnProperty.call(ob, i)) { 21 | if (typeof ob[i] === "object" && ob[i] !== null) { 22 | // Recursion on deeper objects 23 | flattenObject(ob[i], prefix + i, result); 24 | } else { 25 | result[prefix + i] = ob[i]; 26 | } 27 | } 28 | } 29 | return result; 30 | } -------------------------------------------------------------------------------- /e2e/sst/.gitignore: -------------------------------------------------------------------------------- 1 | # dependencies 2 | node_modules 3 | 4 | # sst 5 | .sst 6 | .build 7 | 8 | # opennext 9 | .open-next 10 | 11 | # misc 12 | .DS_Store 13 | 14 | # local env files 15 | .env*.local 16 | -------------------------------------------------------------------------------- /e2e/sst/.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | "name": "Debug SST Start", 6 | "type": "node", 7 | "request": "launch", 8 | "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/sst", 9 | "runtimeArgs": ["start", "--increase-timeout"], 10 | "console": "integratedTerminal", 11 | "skipFiles": ["/**"], 12 | "env": {} 13 | } 14 | ] 15 | } 16 | -------------------------------------------------------------------------------- /e2e/sst/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "search.exclude": { 3 | "**/.sst": true 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /e2e/sst/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "sst", 3 | "version": "0.0.0", 4 | "private": true, 5 | "type": "module", 6 | "scripts": { 7 | "dev": "sst dev", 8 | "build": "sst build", 9 | "deploy": "sst deploy", 10 | "remove": "sst remove", 11 | "console": "sst console", 12 | "typecheck": "tsc --noEmit" 13 | }, 14 | "devDependencies": { 15 | "sst": "^2.22.5", 16 | "aws-cdk-lib": "2.84.0", 17 | "constructs": "10.1.156", 18 | "typescript": "^5.1.6", 19 | "@tsconfig/node16": "^16.1.0" 20 | }, 21 | "workspaces": [ 22 | "packages/*" 23 | ] 24 | } -------------------------------------------------------------------------------- /e2e/sst/packages/core/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@sst/core", 3 | "version": "0.0.0", 4 | "type": "module", 5 | "scripts": { 6 | "test": "sst bind vitest", 7 | "typecheck": "tsc -noEmit" 8 | }, 9 | "devDependencies": { 10 | "vitest": "^0.33.0", 11 | "@types/node": "^20.4.4", 12 | "sst": "^2.22.5" 13 | }, 14 | "dependencies": { 15 | "zod": "^3.22.3" 16 | } 17 | } -------------------------------------------------------------------------------- /e2e/sst/packages/core/src/event.ts: -------------------------------------------------------------------------------- 1 | import { createEventBuilder } from "sst/node/event-bus"; 2 | 3 | export const event = createEventBuilder({ 4 | bus: "bus", 5 | }); 6 | -------------------------------------------------------------------------------- /e2e/sst/packages/core/src/todo.ts: -------------------------------------------------------------------------------- 1 | export * as Todo from "./todo"; 2 | import { z } from "zod"; 3 | import crypto from "crypto"; 4 | 5 | import { event } from "./event"; 6 | 7 | export const Events = { 8 | Created: event("todo.created", { 9 | id: z.string(), 10 | }), 11 | }; 12 | 13 | export async function create() { 14 | const id = crypto.randomUUID(); 15 | // write to database 16 | 17 | await Events.Created.publish({ 18 | id, 19 | }); 20 | } 21 | 22 | export function list() { 23 | return Array(50) 24 | .fill(0) 25 | .map((_, index) => ({ 26 | id: crypto.randomUUID(), 27 | title: "Todo #" + index, 28 | })); 29 | } 30 | -------------------------------------------------------------------------------- /e2e/sst/packages/core/sst-env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | -------------------------------------------------------------------------------- /e2e/sst/packages/core/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "@tsconfig/node16/tsconfig.json", 3 | "compilerOptions": { 4 | "module": "esnext", 5 | "moduleResolution": "node" 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /e2e/sst/packages/functions/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@sst/functions", 3 | "version": "0.0.0", 4 | "type": "module", 5 | "scripts": { 6 | "test": "sst bind vitest", 7 | "typecheck": "tsc -noEmit" 8 | }, 9 | "devDependencies": { 10 | "@types/node": "^20.4.4", 11 | "@types/aws-lambda": "^8.10.119", 12 | "vitest": "^0.33.0", 13 | "sst": "^2.22.5" 14 | } 15 | } -------------------------------------------------------------------------------- /e2e/sst/packages/functions/src/events/todo-created.ts: -------------------------------------------------------------------------------- 1 | import { EventHandler } from "sst/node/event-bus"; 2 | import { Todo } from "@sst/core/todo"; 3 | 4 | export const handler = EventHandler(Todo.Events.Created, async (evt) => { 5 | console.log("Todo created", evt); 6 | }); 7 | -------------------------------------------------------------------------------- /e2e/sst/packages/functions/src/lambda.ts: -------------------------------------------------------------------------------- 1 | import { ApiHandler } from "sst/node/api"; 2 | 3 | export const handler = ApiHandler(async (_evt) => { 4 | return { 5 | statusCode: 200, 6 | body: `Hello world. The time is ${new Date().toISOString()}`, 7 | }; 8 | }); 9 | -------------------------------------------------------------------------------- /e2e/sst/packages/functions/src/todo.ts: -------------------------------------------------------------------------------- 1 | import { ApiHandler } from "sst/node/api"; 2 | import { Todo } from "@sst/core/todo"; 3 | 4 | export const create = ApiHandler(async (_evt) => { 5 | await Todo.create(); 6 | 7 | return { 8 | statusCode: 200, 9 | body: "Todo created", 10 | }; 11 | }); 12 | 13 | export const list = ApiHandler(async (_evt) => { 14 | await Todo.create(); 15 | return { 16 | statusCode: 200, 17 | body: JSON.stringify(Todo.list()), 18 | }; 19 | }); 20 | -------------------------------------------------------------------------------- /e2e/sst/packages/functions/sst-env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | -------------------------------------------------------------------------------- /e2e/sst/packages/functions/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "@tsconfig/node16/tsconfig.json", 3 | "compilerOptions": { 4 | "module": "esnext", 5 | "moduleResolution": "node", 6 | "baseUrl": ".", 7 | "paths": { 8 | "@sst/core/*": ["../core/src/*"] 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /e2e/sst/pnpm-workspace.yaml: -------------------------------------------------------------------------------- 1 | packages: 2 | - "packages/**/*" 3 | -------------------------------------------------------------------------------- /e2e/sst/sst.config.ts: -------------------------------------------------------------------------------- 1 | import { SSTConfig } from "sst"; 2 | import { API } from "./stacks/MyStack"; 3 | import { Tags } from "aws-cdk-lib/core"; 4 | 5 | export default { 6 | config(_input) { 7 | return { 8 | name: "sst", 9 | region: "eu-west-2", 10 | }; 11 | }, 12 | stacks(app) { 13 | app.stack(API); 14 | Tags.of(app).add("baselime:tracing", "true"); 15 | } 16 | } satisfies SSTConfig; 17 | -------------------------------------------------------------------------------- /e2e/sst/stacks/MyStack.ts: -------------------------------------------------------------------------------- 1 | import { StackContext, Api, EventBus } from "sst/constructs"; 2 | 3 | export function API({ stack }: StackContext) { 4 | const bus = new EventBus(stack, "bus", { 5 | defaults: { 6 | retries: 10, 7 | }, 8 | }); 9 | 10 | const api = new Api(stack, "api", { 11 | defaults: { 12 | function: { 13 | bind: [bus], 14 | }, 15 | }, 16 | routes: { 17 | "GET /": "packages/functions/src/lambda.handler", 18 | "GET /todo": "packages/functions/src/todo.list", 19 | "POST /todo": "packages/functions/src/todo.create", 20 | }, 21 | }); 22 | 23 | bus.subscribe("todo.created", { 24 | handler: "packages/functions/src/events/todo-created.handler", 25 | }); 26 | 27 | 28 | stack.addOutputs({ 29 | ApiEndpoint: api.url, 30 | }); 31 | } 32 | -------------------------------------------------------------------------------- /e2e/sst/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "@tsconfig/node16/tsconfig.json", 3 | "exclude": ["packages"], 4 | "compilerOptions": { 5 | "moduleResolution": "node" 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /layer-dir/baselime: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # the path to the interpreter and all of the originally intended arguments 4 | args=("$@") 5 | 6 | # the extra options to pass to the interpreter 7 | extra_args=("-r" "@baselime/lambda-node-opentelemetry/lambda-wrapper.cjs") 8 | 9 | # insert the extra options 10 | args=("${args[@]:0:$#-1}" "${extra_args[@]}" "${args[@]: -1}") 11 | # start the runtime with the extra options 12 | exec "${args[@]}" -------------------------------------------------------------------------------- /meta.json: -------------------------------------------------------------------------------- 1 | { 2 | "inputs": { 3 | "node_modules/@baselime/node-opentelemetry/dist/lambda.cjs": { 4 | "bytes": 42886, 5 | "imports": [], 6 | "format": "cjs" 7 | }, 8 | "src/index.ts": { 9 | "bytes": 81, 10 | "imports": [ 11 | { 12 | "path": "node_modules/@baselime/node-opentelemetry/dist/lambda.cjs", 13 | "kind": "import-statement", 14 | "original": "@baselime/node-opentelemetry/lambda" 15 | } 16 | ], 17 | "format": "esm" 18 | } 19 | }, 20 | "outputs": { 21 | "dist/index.cjs": { 22 | "imports": [], 23 | "exports": [], 24 | "entryPoint": "src/index.ts", 25 | "inputs": { 26 | "node_modules/@baselime/node-opentelemetry/dist/lambda.cjs": { 27 | "bytesInOutput": 19620 28 | }, 29 | "src/index.ts": { 30 | "bytesInOutput": 89 31 | } 32 | }, 33 | "bytes": 20366 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /multi-region-deploy.ts: -------------------------------------------------------------------------------- 1 | import { execSync } from "child_process"; 2 | import { config } from "./multiRegion.js"; 3 | import { readFile, writeFile } from "fs/promises"; 4 | 5 | console.log(config) 6 | const stage = process.argv[2] 7 | 8 | if (!stage) { 9 | console.error("Please specify a stage") 10 | process.exit(1) 11 | } 12 | 13 | function deployToRegion(region: string) { 14 | try { 15 | const result = execSync(`npm run deploy -- --stage ${stage} --region ${region}`) 16 | console.log(result.toString()) 17 | } catch (error) { 18 | console.log(error.stdout?.toString()) 19 | console.log(error.stderr?.toString()) 20 | 21 | throw Error(`Failed to deploy - ${region} ${error.stderr?.toString() || error}`) 22 | } 23 | } 24 | 25 | 26 | for (let region of config.regions) { 27 | deployToRegion(region) 28 | } -------------------------------------------------------------------------------- /multiRegion.js: -------------------------------------------------------------------------------- 1 | export const config = { 2 | "regions": [ 3 | "eu-west-2", 4 | "eu-west-1", 5 | "us-east-1", 6 | "us-east-2", 7 | "us-west-2", 8 | "us-west-1", 9 | "eu-central-1", 10 | "ap-south-1", 11 | "ap-southeast-1", 12 | "ap-southeast-2", 13 | "ap-northeast-1", 14 | "ca-central-1", 15 | "eu-north-1", 16 | "sa-east-1" 17 | ], 18 | "output": "md" 19 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@baselime/lambda-node-opentelemetry", 3 | "version": "0.5.7", 4 | "description": "OpenTelemetry auto tracer for Node.JS based AWS Lambda functions", 5 | "types": "index.d.ts", 6 | "exports": { 7 | "require": "./index.cjs", 8 | "import": "./index.mjs" 9 | }, 10 | "keywords": [ 11 | "nodejs", 12 | "aws-lambda", 13 | "serverless", 14 | "opentelemetry" 15 | ], 16 | "files": [ 17 | "lambda-wrapper.cjs", 18 | "index.mjs", 19 | "index.cjs", 20 | "index.d.ts" 21 | ], 22 | "type": "module", 23 | "scripts": { 24 | "tsc": "tsc --declaration --emitDeclarationOnly --p ./tsconfig.json", 25 | "build:handler": "npm run build:esm && npm run build:cjs", 26 | "build:esm": "esbuild src/handler.mjs --bundle --minify --platform=node --target=node18 --outfile=dist/handler.mjs --metafile=meta.json --format=esm", 27 | "build:cjs": "esbuild src/handler.cjs --bundle --minify --platform=node --target=node18 --outfile=dist/handler.cjs --metafile=meta.json --format=cjs", 28 | "distribute": "mkdir -p layer-dir/nodejs/node_modules/@baselime/lambda-node-opentelemetry && cp -r dist/* layer-dir/nodejs/node_modules/@baselime/lambda-node-opentelemetry", 29 | "build:tracer": "esbuild src/lambda-wrapper.ts --bundle --minify --platform=node --target=node18 --format=cjs --outfile=dist/lambda-wrapper.cjs --metafile=meta.wrapper.json", 30 | "build:wrappercjs": "esbuild src/index.ts --bundle --minify --platform=node --target=node18 --format=cjs --outfile=dist/index.cjs --metafile=meta.json", 31 | "build": "npm run build:handler && npm run build:tracer && npm run build:wrappercjs && npm run distribute", 32 | "deploy": "npm run build && ./scripts/publish", 33 | "test": "vitest", 34 | "coverage": "vitest run --coverage", 35 | "release": "release-it" 36 | }, 37 | "repository": { 38 | "type": "git", 39 | "url": "git+https://github.com/Baselime/tracer-node.git" 40 | }, 41 | "author": "", 42 | "license": "MIT", 43 | "bugs": { 44 | "url": "https://github.com/Baselime/tracer-node/issues" 45 | }, 46 | "homepage": "https://github.com/Baselime/tracer-node#readme", 47 | "devDependencies": { 48 | "@release-it/keep-a-changelog": "^4.0.0", 49 | "@tsconfig/node16": "^1.0.4", 50 | "@types/flat": "^5.0.2", 51 | "@types/node": "^20.1.7", 52 | "esbuild": "^0.20.1", 53 | "release-it": "^16.2.1", 54 | "serverless-webpack": "^5.13.0", 55 | "typescript": "^5.2.2", 56 | "vite": "^4.3.9", 57 | "vitest": "^0.32.2" 58 | }, 59 | "dependencies": { 60 | "@baselime/node-opentelemetry": "^0.5.7", 61 | "@opentelemetry/api": "^1.8.0", 62 | "@opentelemetry/instrumentation-aws-sdk": "^0.39.0", 63 | "flat": "^5.0.2" 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /scripts/publish: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | cd "$(dirname "$0")" 3 | 4 | # Set the scripts permissions 5 | 6 | chmod +x ../layer-dir/baselime 7 | 8 | #Zip the build directory 9 | cd ../layer-dir 10 | zip -r ../node-tracing.zip . 11 | # Get the list of AWS regions 12 | REGIONS=$(aws ec2 describe-regions --output text --query "Regions[*].RegionName") 13 | echo $REGIONS 14 | 15 | 16 | upload_layer() { 17 | echo "$region: started" 18 | local region=$1 19 | output=$(aws lambda publish-layer-version \ 20 | --region $region \ 21 | --layer-name baselime-node \ 22 | --description "Use Baselimes enhanced OpenTelemetry Distro to trace your AWS Lambda functions" \ 23 | --compatible-runtimes nodejs16.x nodejs18.x nodejs20.x \ 24 | --zip-file "fileb://../node-tracing.zip" 25 | ) 26 | 27 | 28 | 29 | if [[ $? -eq 0 ]]; then 30 | # Extract the version number from the output 31 | version_number=$(echo "$output" | jq -r .Version) 32 | name=$(echo "$output" | jq -r .LayerArn) 33 | if [[ -n "$version_number" ]]; then 34 | perm=$(aws lambda add-layer-version-permission \ 35 | --region $region \ 36 | --layer-name baselime-node \ 37 | --version-number $version_number \ 38 | --principal "*" \ 39 | --statement-id share-access \ 40 | --action lambda:GetLayerVersion 41 | ) 42 | else 43 | echo "failed to extract version number from publish output." 44 | fi 45 | layer_arn=$(echo "$output" | jq -r .LayerArn) 46 | perm=$(aws ssm put-parameter \ 47 | --name "/$STAGE/baselime/otel/tracer/node" \ 48 | --description "The ARN for our telemetry extension" \ 49 | --value "$name:$version_number" \ 50 | --type String \ 51 | --overwrite \ 52 | --region $region 53 | ) 54 | else 55 | echo "failed to publish Lambda layer." 56 | fi 57 | echo "$region: done" 58 | } 59 | 60 | for region in $REGIONS; do 61 | upload_layer "$region" & 62 | done 63 | 64 | 65 | wait 66 | 67 | echo "Lambda layer uploaded to all regions." -------------------------------------------------------------------------------- /src/handler.cjs: -------------------------------------------------------------------------------- 1 | const { loadSync } = require('./load-sync'); 2 | const { wrap } = require('./index'); 3 | 4 | const actualHandler = process.env.BASELIME_ACTUAL_HANDLER; 5 | const taskRoot = process.env.LAMBDA_TASK_ROOT; 6 | 7 | if(!taskRoot) { 8 | throw Error('LAMBDA_TASK_ROOT is not defined'); 9 | } 10 | 11 | if(!actualHandler) { 12 | throw Error('BASELIME_ACTUAL_HANDLER is not defined'); 13 | } 14 | 15 | const handler = loadSync(taskRoot, actualHandler); 16 | 17 | exports.handler = wrap(handler, { 18 | timeoutThreshold: 100, 19 | captureEvent: !!process.env.BASELIME_CAPTURE_EVENT, 20 | captureResponse: !!process.env.BASELIME_CAPTURE_RESPONSE, 21 | }); -------------------------------------------------------------------------------- /src/handler.mjs: -------------------------------------------------------------------------------- 1 | import { wrap } from './index'; 2 | import { load } from './load-async' 3 | 4 | 5 | const actualHandler = process.env.BASELIME_ACTUAL_HANDLER; 6 | const taskRoot = process.env.LAMBDA_TASK_ROOT; 7 | 8 | if(typeof taskRoot !== 'string') { 9 | throw Error('LAMBDA_TASK_ROOT is not defined'); 10 | } 11 | 12 | if(typeof actualHandler !== 'string') { 13 | throw Error('BASELIME_ACTUAL_HANDLER is not defined'); 14 | } 15 | 16 | export const handler = wrap(await load(taskRoot, actualHandler), { 17 | timeoutThreshold: 100, 18 | captureEvent: !!process.env.BASELIME_CAPTURE_EVENT, 19 | captureResponse: !!process.env.BASELIME_CAPTURE_RESPONSE, 20 | }); -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | export { withOpenTelemetry as wrap } from '@baselime/node-opentelemetry/lambda'; 2 | -------------------------------------------------------------------------------- /src/lambda-wrapper.ts: -------------------------------------------------------------------------------- 1 | 2 | import { AwsInstrumentation } from "@opentelemetry/instrumentation-aws-sdk"; 3 | import { flatten } from "flat"; 4 | 5 | import { BaselimeSDK, BetterHttpInstrumentation } from "@baselime/node-opentelemetry"; 6 | 7 | const blockedRequestOperations = [ 8 | { service: 'S3', operation: 'PutObject' }, 9 | { service: 'Kinesis', operation: 'PutRecord' } 10 | ] 11 | 12 | const blockedResponseOperations = [ 13 | { service: 'S3', operation: 'GetObject' }, 14 | ] 15 | 16 | const instrumentations = [ 17 | new AwsInstrumentation({ 18 | suppressInternalInstrumentation: process.env.AWS_SDK_INTERNALS === 'true' ? false : true, 19 | responseHook(span, { response }) { 20 | if (response && !blockedResponseOperations.some(({ service, operation }) => response.request.serviceName === service && response.request.commandName === operation)) { 21 | span.setAttributes(flatten({ 22 | response: response.data, 23 | })) 24 | } 25 | }, 26 | preRequestHook(span, request) { 27 | if (!blockedRequestOperations.some(({ service, operation }) => request.request.serviceName === service && request.request.commandName === operation)) { 28 | span.setAttributes(flatten({ 29 | request: request.request, 30 | })) 31 | } 32 | } 33 | }), 34 | new BetterHttpInstrumentation({ 35 | captureBody: process.env.BASELIME_REQUEST_CAPTURE === 'true' ? true : false, 36 | captureHeaders: true, 37 | }) 38 | ] 39 | 40 | new BaselimeSDK({ instrumentations, service: process.env.AWS_LAMBDA_FUNCTION_NAME }).start(); -------------------------------------------------------------------------------- /src/load-async.ts: -------------------------------------------------------------------------------- 1 | import path from "path"; 2 | import { Handler } from "aws-lambda"; 3 | let diagnostics: Error[] = [] 4 | 5 | async function _tryImport(path: string): Promise> { 6 | try { 7 | return await import(path); 8 | } catch (err) { 9 | if (err instanceof Error && !err.message.includes('file exist?') && !err.message.includes("Cannot find module")) { 10 | diagnostics.push(err) 11 | } 12 | 13 | return false 14 | } 15 | } 16 | 17 | export async function load(taskRoot: string, originalHandler: string) { 18 | diagnostics = [] 19 | if (originalHandler.includes('..')) { 20 | throw Error(`${originalHandler} is not a valid handler, it must not contain '..'`); 21 | } 22 | const pathDetails = path.parse(originalHandler); 23 | 24 | const functionName = pathDetails.ext.slice(1); 25 | 26 | const functionPath = path.resolve(taskRoot, pathDetails.dir, pathDetails.name); 27 | const lambda = await _tryImport(functionPath + '.js') || await _tryImport(functionPath + '.mjs') || await _tryImport(functionPath + '.cjs'); 28 | 29 | if (diagnostics.length > 0) { 30 | process.stdout.write(`Diagnostics load for ${originalHandler}\n${diagnostics.map(d => JSON.stringify({ name: d.name, message: d.message, stack: d.stack })).join('\n')}\n`) 31 | } 32 | 33 | if (lambda === false) { 34 | throw Error(`Could not load ${originalHandler}`); 35 | } 36 | 37 | if(typeof lambda[functionName] !== 'function') { 38 | const mod = lambda.default as Record | undefined; 39 | if(mod && typeof mod[functionName] === 'function') { 40 | return mod[functionName]; 41 | } 42 | throw Error(`Handler path format not supported for OpenTelemetry Auto Instrumentation. Please contact Baselime \n ${originalHandler} \n ${JSON.stringify(lambda)}`) 43 | } 44 | 45 | return lambda[functionName]; 46 | } 47 | -------------------------------------------------------------------------------- /src/load-sync.ts: -------------------------------------------------------------------------------- 1 | import path from "path"; 2 | 3 | let diagnostics: Error[] = [] 4 | 5 | function _tryRequire(path: string) { 6 | try { 7 | return require(path); 8 | } catch (err) { 9 | if (err instanceof Error && !err.message.includes('Cannot find module')) { 10 | diagnostics.push(err) 11 | } 12 | return false; 13 | } 14 | } 15 | 16 | 17 | export function loadSync(taskRoot: string, originalHandler: string) { 18 | if (originalHandler.includes('..')) { 19 | throw Error(`${originalHandler} is not a valid handler, it must not contain '..'`); 20 | } 21 | const pathDetails = path.parse(originalHandler); 22 | 23 | const functionName = pathDetails.ext.slice(1); 24 | 25 | const functionPath = path.resolve(taskRoot, pathDetails.dir, pathDetails.name); 26 | 27 | const lambda = _tryRequire(functionPath) || _tryRequire(functionPath + '.cjs') 28 | 29 | if (diagnostics.length > 0) { 30 | process.stdout.write(`Diagnostics load for ${originalHandler}\n${diagnostics.map(d => JSON.stringify({ name: d.name, message: d.message, stack: d.stack })).join('\n')}\n`) 31 | } 32 | 33 | if (!lambda) { 34 | throw Error(`Could not load ${originalHandler}`); 35 | } 36 | 37 | if(typeof lambda[functionName] !== 'function') { 38 | if(typeof lambda.default === 'object' && typeof lambda.default[functionName] === 'function') { 39 | return lambda.default[functionName]; 40 | } 41 | console.log(lambda, originalHandler) 42 | throw Error(`Handler path format not supported for OpenTelemetry Auto Instrumentation. Please contact Baselime \n ${originalHandler} \n ${JSON.stringify(lambda)}`) 43 | } 44 | return lambda[functionName]; 45 | } -------------------------------------------------------------------------------- /sst.config.ts: -------------------------------------------------------------------------------- 1 | import { SSTConfig } from "sst"; 2 | import { LAYER } from "./stacks/Layer"; 3 | 4 | export default { 5 | config(_input) { 6 | return { 7 | name: "lambda-node-opentelemetry", 8 | region: "eu-west-2", 9 | }; 10 | }, 11 | stacks(app) { 12 | app.stack(LAYER); 13 | } 14 | } satisfies SSTConfig; 15 | -------------------------------------------------------------------------------- /tests/data/src/const-export.cjs: -------------------------------------------------------------------------------- 1 | function middlewareLikeThing(app) { 2 | return (event, context) => { 3 | return app(event, context); 4 | } 5 | } 6 | 7 | export const handler = middlewareLikeThing((e) => { 8 | 9 | return { 10 | statusCode: 200, 11 | body: JSON.stringify({ 12 | message: 'hi' 13 | }) 14 | } 15 | }); -------------------------------------------------------------------------------- /tests/data/src/original-handler.cjs: -------------------------------------------------------------------------------- 1 | 2 | 3 | exports.handler = function handler(e) { 4 | return { 5 | statusCode: 200, 6 | body: JSON.stringify({ 7 | message: 'Hello World!', 8 | }) 9 | } 10 | } -------------------------------------------------------------------------------- /tests/data/src/original-handler.mjs: -------------------------------------------------------------------------------- 1 | 2 | 3 | export function handler(e) { 4 | return { 5 | statusCode: 200, 6 | body: JSON.stringify({ 7 | message: 'Hello World!', 8 | }) 9 | } 10 | } -------------------------------------------------------------------------------- /tests/data/src/sample.js: -------------------------------------------------------------------------------- 1 | throw Error("KABOOOOOOOOOM") -------------------------------------------------------------------------------- /tests/load.test.ts: -------------------------------------------------------------------------------- 1 | import { describe, expect, it } from 'vitest'; 2 | import { load } from '../src/load-async'; 3 | 4 | import path from 'node:path'; 5 | 6 | describe('load()', () => { 7 | it('should load a file', async () => { 8 | const taskRoot = path.resolve(__dirname, 'data'); 9 | const originalHandler = './src/original-handler.handler'; 10 | 11 | const handler = await load(taskRoot, originalHandler); 12 | expect(handler).toBeInstanceOf(Function); 13 | 14 | }) 15 | 16 | it('should load with no path', async () => { 17 | const taskRoot = path.resolve(__dirname, 'data'); 18 | const originalHandler = 'index.main'; 19 | 20 | const handler = await load(taskRoot, originalHandler); 21 | expect(handler).toBeInstanceOf(Function); 22 | 23 | }) 24 | 25 | it('should not load sample.js', async () => { 26 | const taskRoot = path.resolve(__dirname, 'data'); 27 | const originalHandler = 'src/sample.handler'; 28 | 29 | await expect(load(taskRoot, originalHandler)).rejects.toThrowErrorMatchingInlineSnapshot('"Could not load src/sample.handler"') 30 | }); 31 | 32 | it('should load const-export.cjs', async () => { 33 | const taskRoot = path.resolve(__dirname, 'data'); 34 | const originalHandler = 'src/const-export.handler'; 35 | 36 | const handler = await load(taskRoot, originalHandler); 37 | expect(handler).toBeInstanceOf(Function); 38 | }) 39 | }); -------------------------------------------------------------------------------- /tests/loadSync.test.ts: -------------------------------------------------------------------------------- 1 | import { describe, expect, expectTypeOf, it } from 'vitest'; 2 | import { loadSync } from '../src/load-sync'; 3 | import path from 'node:path'; 4 | 5 | describe('load()', () => { 6 | it('should load a file', async () => { 7 | const taskRoot = path.resolve(__dirname, 'data'); 8 | const originalHandler = './src/original-handler.handler'; 9 | 10 | const handler = loadSync(taskRoot, originalHandler) 11 | expect(handler).toBeInstanceOf(Function); 12 | 13 | }) 14 | }); -------------------------------------------------------------------------------- /tests/wrap.test.ts: -------------------------------------------------------------------------------- 1 | import { describe, expect, test } from "vitest"; 2 | import { wrap } from '../src/index'; 3 | import { NodeTracerProvider, ReadableSpan } from "@opentelemetry/sdk-trace-node"; 4 | import { Resource } from "@opentelemetry/resources"; 5 | 6 | let spans: ReadableSpan[] = []; 7 | 8 | function setupOtelTestHarness() { 9 | const provider = new NodeTracerProvider({ 10 | resource: new Resource({ 11 | "testing": true, 12 | }), 13 | }); 14 | 15 | provider.register(); 16 | 17 | provider.addSpanProcessor({ 18 | forceFlush: async () => console.log('im called'), 19 | onStart: (span, context) => { }, 20 | onEnd: (span) => { spans.push(span); }, 21 | shutdown: async () => console.log('im called'), 22 | }) 23 | 24 | return { 25 | getSpan() { 26 | return spans.pop(); 27 | } 28 | } 29 | } 30 | 31 | 32 | async function asyncHandler(event, context) { 33 | return "async lambda go brrr" 34 | }; 35 | 36 | function callbackHandler(event, context, callback) { 37 | callback(null, "callback lambda go brrr"); 38 | } 39 | 40 | const context = { 41 | functionName: "test", 42 | awsRequestId: "1234", 43 | invokedFunctionArn: "arn:aws:lambda:us-east-1:123456789012:function:test", 44 | callbackWaitsForEmptyEventLoop: false, 45 | memoryLimitInMB: "128", 46 | logGroupName: "test", 47 | logStreamName: "test", 48 | getRemainingTimeInMillis: () => 1000, 49 | functionVersion: "1", 50 | invokedFunctionUniqueIdentifier: "1", 51 | done: () => { }, 52 | fail: () => { }, 53 | succeed: () => { } 54 | 55 | } 56 | describe("wrap", () => { 57 | const { getSpan } = setupOtelTestHarness() 58 | test("should wrap a callback lambda handler and not error", async () => { 59 | const wrapped = wrap(callbackHandler); 60 | await wrapped({}, context, (err, result) => { 61 | expect(result).toBe("callback lambda go brrr"); 62 | 63 | }); 64 | 65 | const span = getSpan(); 66 | expect(span).toBeDefined(); 67 | expect(span?.name).toBe("test"); 68 | expect(span?.attributes.result).toBe("callback lambda go brrr"); 69 | 70 | 71 | }); 72 | test("should wrap a async lambda handler and not error", async () => { 73 | const wrapped = wrap(asyncHandler); 74 | const result = await wrapped({}, context, () => {}); 75 | const span = getSpan(); 76 | expect(span).toBeDefined(); 77 | expect(span?.name).toBe("test"); 78 | expect(span?.attributes.result).toBe("async lambda go brrr"); 79 | 80 | expect(result).toBe("async lambda go brrr"); 81 | }); 82 | 83 | 84 | }); -------------------------------------------------------------------------------- /trace-timeline.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/baselime/lambda-node-opentelemetry/594ac607defb3f47302276f7ea2aceb293f608b8/trace-timeline.png -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "nodenext", 4 | "allowImportingTsExtensions": true, 5 | "declaration": true, 6 | "moduleResolution": "nodenext", 7 | "noImplicitAny": true, 8 | "removeComments": true, 9 | "preserveConstEnums": true, 10 | "sourceMap": true, 11 | 12 | }, 13 | "include": [ 14 | "src/**/*.ts" 15 | ], 16 | "exclude": [ 17 | "node_modules", 18 | "**/*.spec.ts" 19 | ] 20 | } -------------------------------------------------------------------------------- /vitest.config.ts: -------------------------------------------------------------------------------- 1 | import { defineConfig } from 'vitest/config' 2 | 3 | export default defineConfig({ 4 | test: { 5 | environment: 'node', 6 | }, 7 | base: './tests' 8 | }) --------------------------------------------------------------------------------