├── .github └── workflows │ ├── artifacts.yml │ └── docker-publish-tags.yml ├── .gitignore ├── .gitlab-ci.yml ├── CONFIG.md ├── Dockerfile ├── LICENSE ├── README.md ├── benchmarks ├── CheckIfInt_test.go └── RouteBucket_test.go ├── go.mod ├── go.sum ├── grafana-dash └── dash.json ├── k6_tests └── loadtest1.js ├── lib ├── bucketpath.go ├── bucketpath_test.go ├── discord.go ├── distributed_global.go ├── env.go ├── http.go ├── logger.go ├── memberlist.go ├── memberlist_delegate.go ├── memberlist_events.go ├── metrics.go ├── profile.go ├── queue.go ├── queue_manager.go ├── util.go └── util_test.go └── main.go /.github/workflows/artifacts.yml: -------------------------------------------------------------------------------- 1 | # .github/workflows/release.yaml 2 | 3 | on: 4 | release: 5 | types: [created] 6 | 7 | jobs: 8 | releases-matrix: 9 | name: Release Go Binary 10 | runs-on: ubuntu-latest 11 | strategy: 12 | matrix: 13 | goos: [linux, windows] 14 | goarch: ["386", amd64, arm] 15 | steps: 16 | - uses: actions/checkout@v2 17 | - uses: wangyoucao577/go-release-action@v1.49 18 | with: 19 | github_token: ${{ secrets.GITHUB_TOKEN }} 20 | goos: ${{ matrix.goos }} 21 | goarch: ${{ matrix.goarch }} 22 | binary_name: "nirn-proxy" 23 | -------------------------------------------------------------------------------- /.github/workflows/docker-publish-tags.yml: -------------------------------------------------------------------------------- 1 | name: Docker 2 | 3 | # This workflow uses actions that are not certified by GitHub. 4 | # They are provided by a third-party and are governed by 5 | # separate terms of service, privacy policy, and support 6 | # documentation. 7 | 8 | on: 9 | push: 10 | branches: [ main, dev ] 11 | # Publish semver tags as releases. 12 | tags: [ 'v*.*.*' ] 13 | pull_request: 14 | branches: [ main ] 15 | 16 | env: 17 | # Use docker.io for Docker Hub if empty 18 | REGISTRY: ghcr.io 19 | # github.repository as / 20 | IMAGE_NAME: ${{ github.repository }} 21 | 22 | 23 | jobs: 24 | build: 25 | runs-on: ubuntu-latest 26 | permissions: 27 | contents: read 28 | packages: write 29 | # This is used to complete the identity challenge 30 | # with sigstore/fulcio when running outside of PRs. 31 | id-token: write 32 | 33 | steps: 34 | - name: Checkout repository 35 | uses: actions/checkout@v2 36 | 37 | # Workaround: https://github.com/docker/build-push-action/issues/461 38 | - name: Setup Docker buildx 39 | uses: docker/setup-buildx-action@79abd3f86f79a9d68a23c75a09a9a85889262adf 40 | 41 | # Login against a Docker registry except on PR 42 | # https://github.com/docker/login-action 43 | - name: Log into registry ${{ env.REGISTRY }} 44 | if: github.event_name != 'pull_request' 45 | uses: docker/login-action@28218f9b04b4f3f62068d7b6ce6ca5b26e35336c 46 | with: 47 | registry: ${{ env.REGISTRY }} 48 | username: ${{ github.actor }} 49 | password: ${{ secrets.GITHUB_TOKEN }} 50 | 51 | # Extract metadata (tags, labels) for Docker 52 | # https://github.com/docker/metadata-action 53 | - name: Extract Docker metadata 54 | id: meta 55 | uses: docker/metadata-action@98669ae865ea3cffbcbaa878cf57c20bbf1c6c38 56 | with: 57 | images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} 58 | 59 | # Build and push Docker image with Buildx (don't push on PR) 60 | # https://github.com/docker/build-push-action 61 | - name: Build and push Docker image 62 | id: build-and-push 63 | uses: docker/build-push-action@ad44023a93711e3deb337508980b4b5e9bcdc5dc 64 | with: 65 | context: . 66 | platforms: "linux/amd64,linux/arm64/v8" 67 | push: ${{ github.event_name != 'pull_request' }} 68 | tags: ${{ steps.meta.outputs.tags }} 69 | labels: ${{ steps.meta.outputs.labels }} 70 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | nirn-proxy.* 3 | nirn-proxy 4 | .env 5 | *.txt 6 | *.log 7 | k6_tests/node_modules -------------------------------------------------------------------------------- /.gitlab-ci.yml: -------------------------------------------------------------------------------- 1 | stages: 2 | - docker 3 | - deploy 4 | 5 | build docker: 6 | stage: docker 7 | variables: 8 | GIT_SUBMODULE_STRATEGY: recursive 9 | image: 10 | name: gcr.io/kaniko-project/executor:debug 11 | entrypoint: [""] 12 | script: 13 | - mkdir -p /kaniko/.docker 14 | - echo "{\"auths\":{\"$CI_REGISTRY\":{\"username\":\"$CI_REGISTRY_USER\",\"password\":\"$CI_REGISTRY_PASSWORD\"}}}" > /kaniko/.docker/config.json 15 | - /kaniko/executor --context $CI_PROJECT_DIR --dockerfile $CI_PROJECT_DIR/Dockerfile --destination $CI_REGISTRY_IMAGE/$CI_COMMIT_BRANCH:$CI_COMMIT_SHORT_SHA 16 | 17 | deploy to prod kube: 18 | stage: deploy 19 | image: 20 | name: bitnami/kubectl:latest 21 | entrypoint: [""] 22 | script: 23 | - kubectl --kubeconfig="$KUBE_CONFIG" get deployment nirn-proxy -n rest-proxy -o yaml | sed -E -e "s/(registry\.gitlab\.com\/dyno1\/.*\/).*:[a-z0-9]*/\1$CI_COMMIT_BRANCH:$CI_COMMIT_SHORT_SHA/gm" | kubectl --kubeconfig="$KUBE_CONFIG" apply -f - 24 | only: 25 | - main 26 | -------------------------------------------------------------------------------- /CONFIG.md: -------------------------------------------------------------------------------- 1 | # Config 2 | All variables are optional unless stated otherwise 3 | 4 | ##### LOG_LEVEL 5 | Logrus log level. Passed directly to [ParseLevel](https://github.com/sirupsen/logrus/blob/master/logrus.go#L25-L45) 6 | 7 | ##### PORT 8 | The port to listen for requests on 9 | 10 | ##### METRICS_PORT 11 | The port to listen for metrics requests on 12 | 13 | ##### ENABLE_METRICS 14 | Toggle to enable and register metrics. Disabling may improve resource usage 15 | 16 | ##### ENABLE_PPROF 17 | Enables the performance profiling handler. Read more [here](https://github.com/google/pprof/blob/master/doc/README.md) 18 | 19 | ##### BUFFER_SIZE 20 | Size for the internal proxy go channels. Channels are used to synchronize and order requests. As each request comes in, it gets pushed to a channel. In go, channels can be buffered, this var defines the size of this buffer. 21 | Decreasing this will improve memory usage, but beware that once a channel buffer is full, requests will fight to be added to the channel on the next free spot. This means that during high usage periods, a part of the requests will be unordered if this value is set too low. 22 | 23 | ##### OUTBOUND_IP 24 | The local address to use when firing requests to discord. 25 | 26 | Example: `120.121.122.123` 27 | 28 | ##### BIND_IP 29 | The IP to bind the HTTP server on (both for requests and metrics). 127.0.0.1 will only allow requests coming from the loopback interface. Useful for preventing the proxy from being accessed from outside of LAN, for example. 30 | 31 | Example: `10.0.0.42` - Would only listen on LAN 32 | 33 | ##### REQUEST_TIMEOUT 34 | Defines the amount of time the proxy will wait for a response from discord. Does not include time waiting for ratelimits to clear. 35 | 36 | ##### CLUSTER_PORT 37 | Sets the port that's going to be used to communicate with other cluster members. Default 7946 38 | 39 | ##### CLUSTER_MEMBERS 40 | Comma separated list of stable/known members of the cluster. Does not need to include all members, a gossip protocol is used for discovery. You may include a port along with the address and if you don't, CLUSTER_PORT is used. This variable overrides CLUSTER_DNS. 41 | 42 | Example: `10.0.0.2,10.0.0.3:7244` 43 | 44 | ##### CLUSTER_DNS 45 | DNS address that will resolve to multiple members of the cluster. Does not need to include all members, a gossip protocol is used for discovery. While this is the recommended method of discovery for Kubernetes or similar, it does come with a limitation, which is that all nodes must use the same port for communication since DNS can't return port information. The port used by the proxy for requests is broadcasted automatically and doesn't need to be the same for nodes. 46 | 47 | If using Kubernetes, create a headless service and use it here for easy clustering. 48 | 49 | Example: `nirn-headless.default.svc.cluster.local` or `nirn.mydomain.com` 50 | 51 | ##### MAX_BEARER_COUNT 52 | Bearer token queues max size. Internally, bearer queues are put in an LRU map, this env var represents the max amount of items for this map. 53 | Requests are never interrupted midway, even when an entry is evicted. A low LRU size may cause increased 429s if a bearer token has too many requests queued and fires another one after eviction. 54 | Default: 1024 55 | 56 | ##### DISABLE_HTTP_2 57 | Flag to disable HTTP/2 requests on the client that makes discord requests. Does not impact the http server. 58 | This flag defaults to true due to go http2 support having a few minor issues that can cause requests to fail. 59 | 60 | Default: true 61 | 62 | ##### BOT_RATELIMIT_OVERRIDES 63 | Allows you to define custom global request limits for one or multiple bots. The default is 50 for bots with concurrency = 1 (/gateway/bot -> session_start_limit.max_concurrency field), 500 for concurrency 16 and based on a formula for higher concurrency values. This does not always represents the correct REST limit though, in those cases, you can manually set it using this flag. 64 | 65 | Format: Command separated list of **user id** and limit combo, separated by `:` and with no spaces at all. Don't use application ids. 66 | Example: `392827169497284619:100,227115752396685313:80` 67 | 68 | 69 | ##### DISABLE_GLOBAL_RATELIMIT_DETECTION 70 | Disables the optimistic global rest limit detection. This detection uses the /gateway/bot endpoint, which has a low ratelimit and can cause issues with requests being dropped/delayed as cluster size grows. 71 | 72 | You probably want to set BOT_RATELIMIT_OVERRIDES if you set this to true. 73 | 74 | Default: false 75 | 76 | In the future, this will be the only possible behavior. 77 | 78 | ## Unstable env vars 79 | Collection of env vars that may be removed at any time, mainly used for Discord introducing new behaviour on their edge api versions 80 | 81 | ##### DISABLE_401_LOCK 82 | The proxy locks its queue permanently in case a 401 is encountered during normal operation. This env disables this mechanism but not the logging for it. 83 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM golang:alpine as app-builder 2 | WORKDIR /go/src/app 3 | COPY . . 4 | RUN CGO_ENABLED=0 go install -ldflags '-extldflags "-static"' -tags timetzdata -buildvcs=false 5 | 6 | FROM scratch 7 | COPY --from=app-builder /go/bin/nirn-proxy /nirn-proxy 8 | # the tls certificates: 9 | # NB: this pulls directly from the upstream image, which already has ca-certificates: 10 | COPY --from=alpine:latest /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ 11 | EXPOSE 9000 12 | EXPOSE 8080 13 | ENTRYPOINT ["/nirn-proxy"] -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Nirn-proxy 2 | Nirn-proxy is a highly available, transparent & dynamic HTTP proxy that 3 | handles Discord ratelimits for you and exports meaningful prometheus metrics. 4 | This project is at the heart of [Dyno](https://dyno.gg), handling several hundreds of requests per sec across hundreds of bots all while keeping 429s at ~100 per hour. 5 | 6 | It is designed to be minimally invasive and exploits common library patterns to make the adoption as simple as a URL change. 7 | 8 | #### Features 9 | 10 | - Highly available, horizontally scalable 11 | - Transparent ratelimit handling, per-route and global 12 | - Works with any API version (Also supports using two or more versions for the same bot) 13 | - Small resource footprint 14 | - Works with webhooks 15 | - Works with Bearer tokens 16 | - Supports an unlimited number of clients (Bots and Bearer) 17 | - Prometheus metrics exported out of the box 18 | - No hardcoded routes, therefore no need of updates for new routes introduced by Discord 19 | 20 | ### Usage 21 | Binaries can be found [here](https://github.com/germanoeich/nirn-proxy/releases). Docker images can be found [here](https://github.com/germanoeich/nirn-proxy/pkgs/container/nirn-proxy) 22 | 23 | The proxy sits between the client and discord. Instead of pointing to discord.com, you point to whatever IP and port the proxy is running on, so discord.com/api/v9/gateway becomes 10.0.0.1:8080/api/v9/gateway. This can be achieved in many ways, some suggestions are host remapping on the OS level, DNS overrides or changes to the library code. Please note that the proxy currently does not support SSL. 24 | 25 | Configuration options are 26 | 27 | | Variable | Value | Default | 28 | |-----------------|---------------------------------------------|---------| 29 | | LOG_LEVEL | panic, fatal, error, warn, info, debug, trace | info | 30 | | PORT | number | 8080 | 31 | | METRICS_PORT | number | 9000 | 32 | | ENABLE_METRICS | boolean | true | 33 | | ENABLE_PPROF | boolean | false | 34 | | BUFFER_SIZE | number | 50 | 35 | | OUTBOUND_IP | string | "" | 36 | | BIND_IP | string | 0.0.0.0 | 37 | | REQUEST_TIMEOUT | number (milliseconds) | 5000 | 38 | | CLUSTER_PORT | number | 7946 | 39 | | CLUSTER_MEMBERS | string list (comma separated) | "" | 40 | | CLUSTER_DNS | string | "" | 41 | | MAX_BEARER_COUNT| number | 1024 | 42 | | DISABLE_HTTP_2 | bool | true | 43 | | BOT_RATELIMIT_OVERRIDES | string list (comma separated) | "" | 44 | | DISABLE_GLOBAL_RATELIMIT_DETECTION | boolean | false | 45 | 46 | Information on each config var can be found [here](https://github.com/germanoeich/nirn-proxy/blob/main/CONFIG.md) 47 | 48 | .env files are loaded if present 49 | 50 | ### Behaviour 51 | 52 | The proxy listens on all routes and relays them to Discord, while keeping track of ratelimit buckets and making requests wait if there are no tokens to spare. The proxy fires requests sequentially for each bucket and ordering is preserved. The proxy does not modify the requests in any way so any library compatible with Discords API can be pointed at the proxy and it will not break the library, even with the libraries own ratelimiting intact. 53 | 54 | When using the proxy, it is safe to remove the ratelimiting logic from clients and fire requests instantly, however, the proxy does not handle retries. If for some reason (i.e shared ratelimits, internal discord ratelimits, etc) the proxy encounters a 429, it will return that to the client. It is safe to immediately retry requests that return 429 or even setup retry logic elsewhere (like in a load balancer or service mesh). 55 | 56 | The proxy also guards against known scenarios that might cause a cloudflare ban, like too many webhook 404s or too many 401s. 57 | 58 | ### Proxy specific responses 59 | 60 | The proxy may return a 408 Request Timeout if Discord takes more than $REQUEST_TIMEOUT milliseconds to respond. This allows you to identify and react to routes that have issues. 61 | 62 | Requests may also return a 408 status code in the event that they were aborted because of ratelimits, as documented above. 63 | 64 | ### Limitations 65 | 66 | The ratelimiting only works with `X-RateLimit-Precision` set to `seconds`. If you are using Discord API v8+, that is the only possible behaviour. For users on v6 or v7, please refer to your library docs for information on which precision it uses and how to change it to seconds. 67 | 68 | The proxy tries its best to detect your REST global limits, but Discord does not expose this information. Be sure to set `BOT_RATELIMIT_OVERRIDES` for any clients with elevated limits. 69 | 70 | ### High availability 71 | 72 | The proxy can be run in a cluster by setting either `CLUSTER_MEMBERS` or `CLUSTER_DNS` env vars. When in cluster mode, all nodes are a suitable gateway for all requests and the proxy will route requests consistently using the bucket hash. 73 | 74 | It's recommended that all nodes are reachable through LAN. Please reach out if a WAN cluster is desired for your use case. 75 | 76 | If a node fails, there is a brief period where it will be unhealthy but requests will still be routed to it. When these requests fail, the proxy will mock a 429 to send back to the user. The 429 will signal the client to wait 1s and will have a custom header `generated-by-proxy`. This is done in order to allow seamless retries when a member fails. If you want to backoff, use the custom header to override your lib retry logic. 77 | 78 | The cluster uses [SWIM](https://www.cs.cornell.edu/projects/Quicksilver/public_pdfs/SWIM.pdf), which is an [AP protocol](https://en.wikipedia.org/wiki/CAP_theorem) and is powered by hashicorps excellent [memberlist](https://github.com/hashicorp/memberlist) implementation. 79 | 80 | Being an AP system means that the cluster will tolerate a network partition and needs no quorum to function. In case a network partition occurs, you'll have two clusters running independently, which may or may not be desirable. Configure your network accordingly. 81 | 82 | In case you want to specifically target a node (i.e, for troubleshooting), set the `nirn-routed-to` header on the request. The value doesn't matter. This will prevent the node from routing the request to another node. 83 | 84 | During recovery periods or when nodes join/leave the cluster, you might notice increased 429s. This is expected since the hashing table is changing as members change. Once the cluster settles into a stable state, it'll go back to normal. 85 | 86 | Global ratelimits are handled by a single node on the cluster, however this affinity is soft. There is no concept of leader or elections and if this node leaves, the cluster will simply pick a new one. This is a bottleneck and might increase tail latency, but the other options were either too complex, required an external storage, or would require quorum for the proxy to function. Webhooks and other requests with no token bypass this mechanism completely. 87 | 88 | The best deployment strategy for the cluster is to kill nodes one at a time, preferably with the replacement node already up. 89 | 90 | ### Bearer Tokens 91 | 92 | Bearer tokens are first class citizens. They are treated differently than bot tokens, while bot queues are long lived and never get evicted, Bearer queues are put into an LRU and are spread out by their token hash instead of by the path hash. This provides a more even spread of bearer queues across nodes in the cluster. In addition, Bearer globals are always handled locally. You can control how many bearer queues to keep at any time with the MAX_BEARER_COUNT env var. 93 | 94 | ### Why? 95 | 96 | As projects grow, it's desirable to break them into multiple pieces, each responsible for its own domain. Discord provides gateway sharding on their end but REST can get tricky once you start moving logic out of the shards themselves and lose the guild affinity that shards inherently have, thus a centralized place for handling ratelimits is a must to prevent cloudflare bans and prevent avoidable 429s. At the time this project was created, there was no alternative that fully satisfied our requirements like multi-bot support. We are also early adopters of Discord features, so we need a proxy that supports new routes without us having to manually update it. Thus, this project was born. 97 | 98 | ### Resource usage 99 | 100 | This will vary depending on your usage, how many unique routes you see, etc. For reference, for Dynos use case, doing 150req/s, the usage is ~0.3 CPU and ~550MB of RAM. The proxy can comfortably run on a cheap VPS or an ARM based system. 101 | 102 | ### Metrics / Health 103 | 104 | | Key | Labels | Description | 105 | |------------------------------------|----------------------------------------|------------------------------------------------------------| 106 | |nirn_proxy_error | none | Counter for errors | 107 | |nirn_proxy_requests | method, status, route, clientId | Histogram that keeps track of all request metrics | 108 | |nirn_proxy_open_connections | route, method | Gauge for open client connections with the proxy | 109 | |nirn_proxy_requests_routed_sent | none | Counter for requests routed to other nodes | 110 | |nirn_proxy_requests_routed_received | none | Counter for requests received from other nodes | 111 | |nirn_proxy_requests_routed_error | none | Counter for requests routed that failed | 112 | 113 | Note: 429s can produce two status: 429 Too Many Requests or 429 Shared. The latter is only produced for requests that return with the x-ratelimit-scope header set to "shared", which means they don't count towards the cloudflare firewall limit and thus should not be used for alerts, etc. 114 | 115 | The proxy has an internal endpoint located at `/nirn/healthz` for liveliness and readiness probes. 116 | 117 | ### Profiling 118 | 119 | The proxy can be profiled at runtime by enabling the ENABLE_PPROF flag and browsing to `http://ip:7654/debug/pprof/` 120 | 121 | ### Related projects 122 | 123 | [nirn-probe](https://github.com/germanoeich/nirn-probe) - Checks and alerts if a server is cloudflare banned 124 | 125 | ##### Acknowledgements 126 | - [Eris](https://github.com/abalabahaha/eris) - used as reference throughout this project 127 | - [Twilight](https://github.com/twilight-rs) - used as inspiration and reference 128 | - [@bsian](https://github.com/bsian03) & [@bean](https://github.com/beanjo55) - for listening to my rants and providing assistance -------------------------------------------------------------------------------- /benchmarks/CheckIfInt_test.go: -------------------------------------------------------------------------------- 1 | package benchmarks 2 | 3 | import ( 4 | "regexp" 5 | "strconv" 6 | "testing" 7 | "unicode" 8 | ) 9 | 10 | var url = `121124124124124124` 11 | 12 | func BenchmarkAtoi(b *testing.B) { 13 | b.ReportAllocs() 14 | for n := 0; n < b.N; n++ { 15 | _, err := strconv.Atoi(url) 16 | if err != nil { 17 | } 18 | } 19 | } 20 | 21 | func BenchmarkIsDigit(b *testing.B) { 22 | b.ReportAllocs() 23 | for n := 0; n < b.N; n++ { 24 | for _, d := range url { 25 | if !unicode.IsDigit(d) { 26 | } 27 | } 28 | } 29 | } 30 | 31 | func BenchmarkManual(b *testing.B) { 32 | b.ReportAllocs() 33 | for n := 0; n < b.N; n++ { 34 | for _, d := range url { 35 | if d < '0' || d > '9' { 36 | } 37 | } 38 | } 39 | } 40 | 41 | var r = regexp.MustCompile(`^[0-9]+$`) 42 | func BenchmarkRegexInt(b *testing.B) { 43 | b.ReportAllocs() 44 | for n := 0; n < b.N; n++ { 45 | r.MatchString(url) 46 | } 47 | } -------------------------------------------------------------------------------- /benchmarks/RouteBucket_test.go: -------------------------------------------------------------------------------- 1 | package benchmarks 2 | 3 | import ( 4 | "github.com/germanoeich/nirn-proxy/lib" 5 | "regexp" 6 | "strings" 7 | "testing" 8 | ) 9 | 10 | /* 11 | 12 | First regex: \/([a-z-]+)\/(?:[0-9]{17,19}) 13 | match /a-z/0-9/ 14 | replace channels/id, guilds/id, webhooks/id with / or with the match 15 | 16 | Second regex: \/reactions\/[^/]+ 17 | Matches /reactions/* where * is the emoji id. Replaces it with /reactions/:id 18 | 19 | Third regex: \/reactions\/:id\/[^/]+ 20 | Matches /reactions/:id/* where * is the user id or @me. Replaces it with /reactions/:id/:userID 21 | 22 | Fourth regex: ^\/webhooks\/(\d+)\/[A-Za-z0-9-_]{64,} 23 | Matches /webhooks/id/token, replaces with /webhooks/$1/:token where $1 is the id 24 | 25 | */ 26 | var majorsRegex = regexp.MustCompile(`/(guilds|channels|webhooks)/[0-9]{17,19}`) 27 | func GetBucketPath(url string) string { 28 | var bucket string 29 | bucket += majorsRegex.ReplaceAllString(url, `/$1/:id`) 30 | return bucket 31 | } 32 | 33 | func BenchmarkRegex(b *testing.B) { 34 | b.ReportAllocs() 35 | url := `/guilds/121124124124124124/` 36 | for n := 0; n < b.N; n++ { 37 | GetBucketPath(url) 38 | } 39 | } 40 | 41 | // ==================================================== 42 | 43 | 44 | func BenchmarkOptimistic(b *testing.B) { 45 | b.ReportAllocs() 46 | url := `guilds/121124124124124124/pins/121124124124124124` 47 | for n := 0; n < b.N; n++ { 48 | lib.GetOptimisticBucketPath(url, "GET") 49 | } 50 | } 51 | 52 | // ==================================================== 53 | 54 | var prefixUrl = `/api/v9/guilds/121124124124124124/pins/121124124124124124` 55 | 56 | func BenchmarkPrefixStripReplaceAllNaive(b *testing.B) { 57 | b.ReportAllocs() 58 | for n := 0; n < b.N; n++ { 59 | strings.ReplaceAll(prefixUrl, "/api/v10/", "") 60 | strings.ReplaceAll(prefixUrl, "/api/v9/", "") 61 | strings.ReplaceAll(prefixUrl, "/api/v8/", "") 62 | strings.ReplaceAll(prefixUrl, "/api/v7/", "") 63 | strings.ReplaceAll(prefixUrl, "/api/v6/", "") 64 | } 65 | } 66 | 67 | func BenchmarkPrefixStripReplaceAllSmart(b *testing.B) { 68 | b.ReportAllocs() 69 | for n := 0; n < b.N; n++ { 70 | var clean string 71 | if strings.HasPrefix(prefixUrl, "/api/v") { 72 | clean = strings.ReplaceAll(prefixUrl, "/api/v", "") 73 | l := len(clean) 74 | i := strings.Index(clean, "/") 75 | clean = clean[i:l] 76 | } 77 | } 78 | } -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/germanoeich/nirn-proxy 2 | 3 | go 1.18 4 | 5 | require ( 6 | github.com/Clever/leakybucket v1.2.0 7 | github.com/hashicorp/golang-lru v0.5.4 8 | github.com/hashicorp/memberlist v0.3.1 9 | github.com/joho/godotenv v1.4.0 10 | github.com/prometheus/client_golang v1.11.0 11 | github.com/sirupsen/logrus v1.8.1 12 | ) 13 | 14 | require ( 15 | github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da // indirect 16 | github.com/beorn7/perks v1.0.1 // indirect 17 | github.com/cespare/xxhash/v2 v2.1.1 // indirect 18 | github.com/golang/protobuf v1.4.3 // indirect 19 | github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c // indirect 20 | github.com/hashicorp/errwrap v1.0.0 // indirect 21 | github.com/hashicorp/go-immutable-radix v1.0.0 // indirect 22 | github.com/hashicorp/go-msgpack v0.5.3 // indirect 23 | github.com/hashicorp/go-multierror v1.0.0 // indirect 24 | github.com/hashicorp/go-sockaddr v1.0.0 // indirect 25 | github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect 26 | github.com/miekg/dns v1.1.26 // indirect 27 | github.com/prometheus/client_model v0.2.0 // indirect 28 | github.com/prometheus/common v0.26.0 // indirect 29 | github.com/prometheus/procfs v0.6.0 // indirect 30 | github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529 // indirect 31 | golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 // indirect 32 | golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4 // indirect 33 | golang.org/x/sys v0.0.0-20210603081109-ebe580a85c40 // indirect 34 | golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect 35 | google.golang.org/protobuf v1.26.0-rc.1 // indirect 36 | ) 37 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= 2 | github.com/Clever/leakybucket v1.2.0 h1:tj9bHR6QS6c5Crszv+EP66NcbJxLabwZ90CUqNlFsSw= 3 | github.com/Clever/leakybucket v1.2.0/go.mod h1:gZbI9EI3nNh9loJzrwobjtPUh3fuOT2Q6GgqtBHFuc4= 4 | github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= 5 | github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= 6 | github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= 7 | github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= 8 | github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho= 9 | github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da h1:8GUt8eRujhVEGZFFEjBj46YV4rDjvGrNxb0KMWYkL2I= 10 | github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY= 11 | github.com/aws/aws-sdk-go v1.29.31/go.mod h1:1KvfttTE3SPKMpo8g2c6jL3ZKfXtFvKscTgahTma5Xg= 12 | github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= 13 | github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= 14 | github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= 15 | github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= 16 | github.com/cespare/xxhash/v2 v2.1.1 h1:6MnRN8NT7+YBpUIWxHtefFZOKTAPgGjpQSxqLNn0+qY= 17 | github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= 18 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 19 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 20 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 21 | github.com/eapache/go-resiliency v1.2.0/go.mod h1:kFI+JgMyC7bLPUVY133qvEBtVayf5mFgVsvEsIPBvNs= 22 | github.com/garyburd/redigo v1.3.0/go.mod h1:NR3MbYisc3/PwhQ00EMzDiPmrwpPxAn5GI05/YaO1SY= 23 | github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= 24 | github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= 25 | github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vbaY= 26 | github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= 27 | github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= 28 | github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A= 29 | github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= 30 | github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= 31 | github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= 32 | github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 33 | github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 34 | github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 35 | github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= 36 | github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= 37 | github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= 38 | github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= 39 | github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= 40 | github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= 41 | github.com/golang/protobuf v1.4.3 h1:JjCZWpVbqXDqFVmTfYWEVTMIYrL/NPdPSCHPJ0T/raM= 42 | github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= 43 | github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c h1:964Od4U6p2jUkFxvCydnIczKteheJEzHRToSGK3Bnlw= 44 | github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= 45 | github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= 46 | github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= 47 | github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= 48 | github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= 49 | github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= 50 | github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= 51 | github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= 52 | github.com/hashicorp/errwrap v1.0.0 h1:hLrqtEDnRye3+sgx6z4qVLNuviH3MR5aQ0ykNJa/UYA= 53 | github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= 54 | github.com/hashicorp/go-immutable-radix v1.0.0 h1:AKDB1HM5PWEA7i4nhcpwOrO2byshxBjXVn/J/3+z5/0= 55 | github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= 56 | github.com/hashicorp/go-msgpack v0.5.3 h1:zKjpN5BK/P5lMYrLmBHdBULWbJ0XpYR+7NGzqkZzoD4= 57 | github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM= 58 | github.com/hashicorp/go-multierror v1.0.0 h1:iVjPR7a6H0tWELX5NxNe7bYopibicUzc7uPribsnS6o= 59 | github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= 60 | github.com/hashicorp/go-sockaddr v1.0.0 h1:GeH6tui99pF4NJgfnhp+L6+FfobzVW3Ah46sLo0ICXs= 61 | github.com/hashicorp/go-sockaddr v1.0.0/go.mod h1:7Xibr9yA9JjQq1JpNB2Vw7kxv8xerXegt+ozgdvDeDU= 62 | github.com/hashicorp/go-uuid v1.0.0 h1:RS8zrF7PhGwyNPOtxSClXXj9HA8feRnJzgnI1RJCSnM= 63 | github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= 64 | github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= 65 | github.com/hashicorp/golang-lru v0.5.4 h1:YDjusn29QI/Das2iO9M0BHnIbxPeyuCHsjMW+lJfyTc= 66 | github.com/hashicorp/golang-lru v0.5.4/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4= 67 | github.com/hashicorp/memberlist v0.3.1 h1:MXgUXLqva1QvpVEDQW1IQLG0wivQAtmFlHRQ+1vWZfM= 68 | github.com/hashicorp/memberlist v0.3.1/go.mod h1:MS2lj3INKhZjWNqd3N0m3J+Jxf3DAOnAH9VT3Sh9MUE= 69 | github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= 70 | github.com/joho/godotenv v1.4.0 h1:3l4+N6zfMWnkbPEXKng2o2/MR5mSwTrBih4ZEkkz1lg= 71 | github.com/joho/godotenv v1.4.0/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= 72 | github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4= 73 | github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= 74 | github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= 75 | github.com/json-iterator/go v1.1.11/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= 76 | github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= 77 | github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM= 78 | github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= 79 | github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= 80 | github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= 81 | github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= 82 | github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= 83 | github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= 84 | github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU= 85 | github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= 86 | github.com/miekg/dns v1.1.26 h1:gPxPSwALAeHJSjarOs00QjVdV9QoBvc1D2ujQUr5BzU= 87 | github.com/miekg/dns v1.1.26/go.mod h1:bPDLeHnStXmXAq1m/Ch/hvfNHr14JKNPMBo3VZKjuso= 88 | github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= 89 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= 90 | github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= 91 | github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= 92 | github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= 93 | github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= 94 | github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c h1:Lgl0gzECD8GnQ5QCWA8o6BtfL6mDH5rQgM4/fX3avOs= 95 | github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= 96 | github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 97 | github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 98 | github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 99 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 100 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 101 | github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= 102 | github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= 103 | github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= 104 | github.com/prometheus/client_golang v1.11.0 h1:HNkLOAEQMIDv/K+04rukrLx6ch7msSRwf3/SASFAGtQ= 105 | github.com/prometheus/client_golang v1.11.0/go.mod h1:Z6t4BnS23TR94PD6BsDNk8yVqroYurpAkEiz0P2BEV0= 106 | github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= 107 | github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= 108 | github.com/prometheus/client_model v0.2.0 h1:uq5h0d+GuxiXLJLNABMgp2qUWDPiLvgCzz2dUR+/W/M= 109 | github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= 110 | github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= 111 | github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo= 112 | github.com/prometheus/common v0.26.0 h1:iMAkS2TDoNWnKM+Kopnx/8tnEStIfpYA0ur0xQzzhMQ= 113 | github.com/prometheus/common v0.26.0/go.mod h1:M7rCNAaPfAosfx8veZJCuw84e35h3Cfd9VFqTh1DIvc= 114 | github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= 115 | github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= 116 | github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= 117 | github.com/prometheus/procfs v0.6.0 h1:mxy4L2jP6qMonqmq+aTtOx1ifVWUgG/TAmntgbh3xv4= 118 | github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA= 119 | github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529 h1:nn5Wsu0esKSJiIVhscUtVbo7ada43DJhG55ua/hjS5I= 120 | github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= 121 | github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= 122 | github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= 123 | github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88= 124 | github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE= 125 | github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= 126 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 127 | github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 128 | github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= 129 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= 130 | github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= 131 | github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0= 132 | github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 133 | golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= 134 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 135 | golang.org/x/crypto v0.0.0-20190923035154-9ee001bba392/go.mod h1:/lpIB1dKB+9EgE3H3cr1v9wB50oz8l4C4h62xy7jSTY= 136 | golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 h1:psW17arqaxU48Z5kZ0CQnkZWQJsqcURM6tKiBApRjXI= 137 | golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= 138 | golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 139 | golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 140 | golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 141 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 142 | golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 143 | golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 144 | golang.org/x/net v0.0.0-20190923162816-aa69164e4478/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 145 | golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 146 | golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= 147 | golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4 h1:4nGaVu0QrbjT/AK2PRLuQfQuh6DJve+pELhqTdAj3x0= 148 | golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= 149 | golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= 150 | golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 151 | golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 152 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 153 | golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 154 | golang.org/x/sync v0.0.0-20201207232520-09787c993a3a h1:DcqTD9SDLc+1P/r1EmRBwnVsrOwW+kk2vWf9n+1sGhs= 155 | golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 156 | golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 157 | golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 158 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 159 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 160 | golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 161 | golang.org/x/sys v0.0.0-20190922100055-0a153f010e69/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 162 | golang.org/x/sys v0.0.0-20190924154521-2837fb4f24fe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 163 | golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 164 | golang.org/x/sys v0.0.0-20200106162015-b016eb3dc98e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 165 | golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 166 | golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 167 | golang.org/x/sys v0.0.0-20200625212154-ddb9806d33ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 168 | golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 169 | golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 170 | golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 171 | golang.org/x/sys v0.0.0-20210603081109-ebe580a85c40 h1:JWgyZ1qgdTaF3N3oxC+MdTV7qvEEgHo3otj+HB5CM7Q= 172 | golang.org/x/sys v0.0.0-20210603081109-ebe580a85c40/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 173 | golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= 174 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 175 | golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= 176 | golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 177 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 178 | golang.org/x/tools v0.0.0-20190907020128-2ca718005c18/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= 179 | golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 180 | golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 181 | golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= 182 | golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 183 | google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= 184 | google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= 185 | google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= 186 | google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= 187 | google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= 188 | google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= 189 | google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= 190 | google.golang.org/protobuf v1.26.0-rc.1 h1:7QnIQpGRHE5RnLKnESfDoxm2dTapTZua5a0kS0A+VXQ= 191 | google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= 192 | gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= 193 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 194 | gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 195 | gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 196 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 197 | gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 198 | gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 199 | gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 200 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= 201 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 202 | -------------------------------------------------------------------------------- /grafana-dash/dash.json: -------------------------------------------------------------------------------- 1 | { 2 | "annotations": { 3 | "list": [ 4 | { 5 | "builtIn": 1, 6 | "datasource": "-- Grafana --", 7 | "enable": true, 8 | "hide": true, 9 | "iconColor": "rgba(0, 211, 255, 1)", 10 | "name": "Annotations & Alerts", 11 | "target": { 12 | "limit": 100, 13 | "matchAny": false, 14 | "tags": [], 15 | "type": "dashboard" 16 | }, 17 | "type": "dashboard" 18 | } 19 | ] 20 | }, 21 | "editable": true, 22 | "fiscalYearStartMonth": 0, 23 | "graphTooltip": 1, 24 | "id": 16, 25 | "iteration": 1642101763496, 26 | "links": [], 27 | "liveNow": false, 28 | "panels": [ 29 | { 30 | "datasource": { 31 | "type": "prometheus", 32 | "uid": "${datasource}" 33 | }, 34 | "fieldConfig": { 35 | "defaults": { 36 | "color": { 37 | "mode": "thresholds" 38 | }, 39 | "mappings": [], 40 | "thresholds": { 41 | "mode": "absolute", 42 | "steps": [ 43 | { 44 | "color": "green", 45 | "value": null 46 | } 47 | ] 48 | } 49 | }, 50 | "overrides": [] 51 | }, 52 | "gridPos": { 53 | "h": 7, 54 | "w": 3, 55 | "x": 0, 56 | "y": 0 57 | }, 58 | "id": 14, 59 | "options": { 60 | "colorMode": "value", 61 | "graphMode": "area", 62 | "justifyMode": "auto", 63 | "orientation": "auto", 64 | "reduceOptions": { 65 | "calcs": [ 66 | "lastNotNull" 67 | ], 68 | "fields": "", 69 | "values": false 70 | }, 71 | "text": {}, 72 | "textMode": "auto" 73 | }, 74 | "pluginVersion": "8.3.3", 75 | "targets": [ 76 | { 77 | "datasource": { 78 | "type": "prometheus", 79 | "uid": "${datasource}" 80 | }, 81 | "exemplar": true, 82 | "expr": "sum(increase(nirn_proxy_requests_count{status=\"429 Too Many Requests\",clientId=~\"$clientId\"}[1h]))", 83 | "interval": "", 84 | "legendFormat": "", 85 | "queryType": "randomWalk", 86 | "refId": "A" 87 | } 88 | ], 89 | "timeFrom": "1h", 90 | "title": "429s (1h)", 91 | "type": "stat" 92 | }, 93 | { 94 | "datasource": { 95 | "type": "prometheus", 96 | "uid": "${datasource}" 97 | }, 98 | "fieldConfig": { 99 | "defaults": { 100 | "color": { 101 | "mode": "thresholds" 102 | }, 103 | "mappings": [], 104 | "thresholds": { 105 | "mode": "absolute", 106 | "steps": [ 107 | { 108 | "color": "green", 109 | "value": null 110 | } 111 | ] 112 | } 113 | }, 114 | "overrides": [] 115 | }, 116 | "gridPos": { 117 | "h": 7, 118 | "w": 3, 119 | "x": 3, 120 | "y": 0 121 | }, 122 | "id": 17, 123 | "options": { 124 | "colorMode": "value", 125 | "graphMode": "none", 126 | "justifyMode": "auto", 127 | "orientation": "auto", 128 | "reduceOptions": { 129 | "calcs": [ 130 | "lastNotNull" 131 | ], 132 | "fields": "", 133 | "values": false 134 | }, 135 | "text": {}, 136 | "textMode": "auto" 137 | }, 138 | "pluginVersion": "8.3.3", 139 | "targets": [ 140 | { 141 | "datasource": { 142 | "type": "prometheus", 143 | "uid": "${datasource}" 144 | }, 145 | "exemplar": true, 146 | "expr": "sum (rate(nirn_proxy_requests_count{clientId=~\"$clientId\"}[$__rate_interval]))", 147 | "interval": "", 148 | "legendFormat": "", 149 | "refId": "A" 150 | } 151 | ], 152 | "title": "Reqs /s (curr)", 153 | "type": "stat" 154 | }, 155 | { 156 | "datasource": { 157 | "type": "prometheus", 158 | "uid": "${datasource}" 159 | }, 160 | "fieldConfig": { 161 | "defaults": { 162 | "color": { 163 | "mode": "palette-classic" 164 | }, 165 | "custom": { 166 | "axisLabel": "", 167 | "axisPlacement": "auto", 168 | "barAlignment": 0, 169 | "drawStyle": "line", 170 | "fillOpacity": 0, 171 | "gradientMode": "none", 172 | "hideFrom": { 173 | "legend": false, 174 | "tooltip": false, 175 | "viz": false 176 | }, 177 | "lineInterpolation": "linear", 178 | "lineWidth": 1, 179 | "pointSize": 5, 180 | "scaleDistribution": { 181 | "type": "linear" 182 | }, 183 | "showPoints": "auto", 184 | "spanNulls": false, 185 | "stacking": { 186 | "group": "A", 187 | "mode": "none" 188 | }, 189 | "thresholdsStyle": { 190 | "mode": "off" 191 | } 192 | }, 193 | "mappings": [], 194 | "thresholds": { 195 | "mode": "absolute", 196 | "steps": [ 197 | { 198 | "color": "green", 199 | "value": null 200 | }, 201 | { 202 | "color": "red", 203 | "value": 80 204 | } 205 | ] 206 | }, 207 | "unit": "reqps" 208 | }, 209 | "overrides": [] 210 | }, 211 | "gridPos": { 212 | "h": 7, 213 | "w": 6, 214 | "x": 6, 215 | "y": 0 216 | }, 217 | "id": 10, 218 | "options": { 219 | "legend": { 220 | "calcs": [], 221 | "displayMode": "list", 222 | "placement": "bottom" 223 | }, 224 | "tooltip": { 225 | "mode": "single" 226 | } 227 | }, 228 | "targets": [ 229 | { 230 | "datasource": { 231 | "type": "prometheus", 232 | "uid": "${datasource}" 233 | }, 234 | "exemplar": true, 235 | "expr": "sum(rate(nirn_proxy_requests_count{clientId=~\"$clientId\"}[$__rate_interval])) by (clientId)", 236 | "interval": "", 237 | "legendFormat": "{{clientId}}", 238 | "queryType": "randomWalk", 239 | "refId": "A" 240 | }, 241 | { 242 | "datasource": { 243 | "type": "prometheus", 244 | "uid": "${datasource}" 245 | }, 246 | "exemplar": true, 247 | "expr": "sum(rate(nirn_proxy_requests_count{clientId=~\"$clientId\"}[1m]))", 248 | "hide": false, 249 | "interval": "", 250 | "legendFormat": "Total", 251 | "refId": "B" 252 | } 253 | ], 254 | "title": "Reqs/s", 255 | "type": "timeseries" 256 | }, 257 | { 258 | "datasource": { 259 | "type": "prometheus", 260 | "uid": "${datasource}" 261 | }, 262 | "fieldConfig": { 263 | "defaults": { 264 | "color": { 265 | "mode": "palette-classic" 266 | }, 267 | "custom": { 268 | "axisLabel": "", 269 | "axisPlacement": "auto", 270 | "barAlignment": 0, 271 | "drawStyle": "line", 272 | "fillOpacity": 0, 273 | "gradientMode": "none", 274 | "hideFrom": { 275 | "legend": false, 276 | "tooltip": false, 277 | "viz": false 278 | }, 279 | "lineInterpolation": "linear", 280 | "lineWidth": 1, 281 | "pointSize": 5, 282 | "scaleDistribution": { 283 | "type": "linear" 284 | }, 285 | "showPoints": "auto", 286 | "spanNulls": false, 287 | "stacking": { 288 | "group": "A", 289 | "mode": "none" 290 | }, 291 | "thresholdsStyle": { 292 | "mode": "off" 293 | } 294 | }, 295 | "mappings": [], 296 | "thresholds": { 297 | "mode": "absolute", 298 | "steps": [ 299 | { 300 | "color": "green", 301 | "value": null 302 | }, 303 | { 304 | "color": "red", 305 | "value": 80 306 | } 307 | ] 308 | }, 309 | "unit": "reqps" 310 | }, 311 | "overrides": [] 312 | }, 313 | "gridPos": { 314 | "h": 7, 315 | "w": 6, 316 | "x": 12, 317 | "y": 0 318 | }, 319 | "id": 15, 320 | "options": { 321 | "legend": { 322 | "calcs": [], 323 | "displayMode": "list", 324 | "placement": "bottom" 325 | }, 326 | "tooltip": { 327 | "mode": "single" 328 | } 329 | }, 330 | "targets": [ 331 | { 332 | "datasource": { 333 | "type": "prometheus", 334 | "uid": "${datasource}" 335 | }, 336 | "exemplar": true, 337 | "expr": "sum by(method, status, route) (rate(nirn_proxy_requests_count{status=\"429 Too Many Requests\",clientId=~\"$clientId\"}[$__rate_interval]))", 338 | "interval": "", 339 | "legendFormat": "{{method}} {{route}} ({{status}})", 340 | "queryType": "randomWalk", 341 | "refId": "A" 342 | } 343 | ], 344 | "title": "429", 345 | "type": "timeseries" 346 | }, 347 | { 348 | "datasource": { 349 | "type": "prometheus", 350 | "uid": "${datasource}" 351 | }, 352 | "fieldConfig": { 353 | "defaults": { 354 | "color": { 355 | "mode": "palette-classic" 356 | }, 357 | "custom": { 358 | "axisLabel": "", 359 | "axisPlacement": "auto", 360 | "barAlignment": 0, 361 | "drawStyle": "line", 362 | "fillOpacity": 0, 363 | "gradientMode": "none", 364 | "hideFrom": { 365 | "legend": false, 366 | "tooltip": false, 367 | "viz": false 368 | }, 369 | "lineInterpolation": "linear", 370 | "lineWidth": 1, 371 | "pointSize": 5, 372 | "scaleDistribution": { 373 | "type": "linear" 374 | }, 375 | "showPoints": "auto", 376 | "spanNulls": false, 377 | "stacking": { 378 | "group": "A", 379 | "mode": "none" 380 | }, 381 | "thresholdsStyle": { 382 | "mode": "off" 383 | } 384 | }, 385 | "mappings": [], 386 | "noValue": "0", 387 | "thresholds": { 388 | "mode": "absolute", 389 | "steps": [ 390 | { 391 | "color": "green", 392 | "value": null 393 | }, 394 | { 395 | "color": "red", 396 | "value": 80 397 | } 398 | ] 399 | }, 400 | "unit": "reqps" 401 | }, 402 | "overrides": [] 403 | }, 404 | "gridPos": { 405 | "h": 7, 406 | "w": 6, 407 | "x": 18, 408 | "y": 0 409 | }, 410 | "id": 2, 411 | "options": { 412 | "legend": { 413 | "calcs": [], 414 | "displayMode": "list", 415 | "placement": "bottom" 416 | }, 417 | "tooltip": { 418 | "mode": "single" 419 | } 420 | }, 421 | "targets": [ 422 | { 423 | "datasource": { 424 | "type": "prometheus", 425 | "uid": "${datasource}" 426 | }, 427 | "exemplar": true, 428 | "expr": "sum by(method, status, route) (rate(nirn_proxy_requests_count{status=~\"500 Internal Server Error|501 Not Implemented|502 Bad Gateway|503 Service Unavailable|504 Gateway Timeout|505 HTTP Version Not Supported|506 Variant Also Negotiates|507 Insufficient Storage|508 Loop Detected|510 Not Extended|511 Network Authentication Required\", clientId=~\"$clientId\"}[$__rate_interval]))", 429 | "interval": "", 430 | "legendFormat": "{{method}} {{route}} ({{status}})", 431 | "queryType": "randomWalk", 432 | "refId": "A" 433 | } 434 | ], 435 | "title": "5XX", 436 | "type": "timeseries" 437 | }, 438 | { 439 | "datasource": { 440 | "type": "prometheus", 441 | "uid": "${datasource}" 442 | }, 443 | "fieldConfig": { 444 | "defaults": { 445 | "color": { 446 | "mode": "palette-classic" 447 | }, 448 | "custom": { 449 | "axisLabel": "", 450 | "axisPlacement": "auto", 451 | "barAlignment": 0, 452 | "drawStyle": "line", 453 | "fillOpacity": 0, 454 | "gradientMode": "none", 455 | "hideFrom": { 456 | "legend": false, 457 | "tooltip": false, 458 | "viz": false 459 | }, 460 | "lineInterpolation": "linear", 461 | "lineWidth": 1, 462 | "pointSize": 5, 463 | "scaleDistribution": { 464 | "type": "linear" 465 | }, 466 | "showPoints": "auto", 467 | "spanNulls": false, 468 | "stacking": { 469 | "group": "A", 470 | "mode": "none" 471 | }, 472 | "thresholdsStyle": { 473 | "mode": "off" 474 | } 475 | }, 476 | "mappings": [], 477 | "thresholds": { 478 | "mode": "absolute", 479 | "steps": [ 480 | { 481 | "color": "green", 482 | "value": null 483 | }, 484 | { 485 | "color": "red", 486 | "value": 80 487 | } 488 | ] 489 | }, 490 | "unit": "reqps" 491 | }, 492 | "overrides": [] 493 | }, 494 | "gridPos": { 495 | "h": 8, 496 | "w": 24, 497 | "x": 0, 498 | "y": 7 499 | }, 500 | "id": 8, 501 | "options": { 502 | "legend": { 503 | "calcs": [], 504 | "displayMode": "list", 505 | "placement": "bottom" 506 | }, 507 | "tooltip": { 508 | "mode": "single" 509 | } 510 | }, 511 | "targets": [ 512 | { 513 | "datasource": { 514 | "type": "prometheus", 515 | "uid": "${datasource}" 516 | }, 517 | "exemplar": true, 518 | "expr": "sum by (status) (rate(nirn_proxy_requests_count{clientId=~\"$clientId\"}[$__rate_interval]))", 519 | "interval": "", 520 | "legendFormat": "{{status}}", 521 | "queryType": "randomWalk", 522 | "refId": "A" 523 | } 524 | ], 525 | "title": "Status codes", 526 | "type": "timeseries" 527 | }, 528 | { 529 | "datasource": { 530 | "type": "prometheus", 531 | "uid": "${datasource}" 532 | }, 533 | "fieldConfig": { 534 | "defaults": { 535 | "color": { 536 | "mode": "palette-classic" 537 | }, 538 | "custom": { 539 | "axisLabel": "", 540 | "axisPlacement": "auto", 541 | "barAlignment": 0, 542 | "drawStyle": "line", 543 | "fillOpacity": 0, 544 | "gradientMode": "none", 545 | "hideFrom": { 546 | "legend": false, 547 | "tooltip": false, 548 | "viz": false 549 | }, 550 | "lineInterpolation": "linear", 551 | "lineWidth": 1, 552 | "pointSize": 5, 553 | "scaleDistribution": { 554 | "type": "linear" 555 | }, 556 | "showPoints": "auto", 557 | "spanNulls": false, 558 | "stacking": { 559 | "group": "A", 560 | "mode": "none" 561 | }, 562 | "thresholdsStyle": { 563 | "mode": "off" 564 | } 565 | }, 566 | "mappings": [], 567 | "thresholds": { 568 | "mode": "absolute", 569 | "steps": [ 570 | { 571 | "color": "green", 572 | "value": null 573 | }, 574 | { 575 | "color": "red", 576 | "value": 80 577 | } 578 | ] 579 | }, 580 | "unit": "reqps" 581 | }, 582 | "overrides": [] 583 | }, 584 | "gridPos": { 585 | "h": 8, 586 | "w": 24, 587 | "x": 0, 588 | "y": 15 589 | }, 590 | "id": 6, 591 | "options": { 592 | "legend": { 593 | "calcs": [], 594 | "displayMode": "list", 595 | "placement": "bottom" 596 | }, 597 | "tooltip": { 598 | "mode": "single" 599 | } 600 | }, 601 | "targets": [ 602 | { 603 | "datasource": { 604 | "type": "prometheus", 605 | "uid": "${datasource}" 606 | }, 607 | "exemplar": true, 608 | "expr": "sum by (route) (rate(nirn_proxy_requests_count{clientId=~\"$clientId\"}[$__rate_interval]))", 609 | "interval": "", 610 | "legendFormat": "{{route}}", 611 | "queryType": "randomWalk", 612 | "refId": "A" 613 | } 614 | ], 615 | "title": "Reqs by path", 616 | "type": "timeseries" 617 | }, 618 | { 619 | "datasource": { 620 | "type": "prometheus", 621 | "uid": "${datasource}" 622 | }, 623 | "fieldConfig": { 624 | "defaults": { 625 | "color": { 626 | "mode": "palette-classic" 627 | }, 628 | "custom": { 629 | "axisLabel": "", 630 | "axisPlacement": "auto", 631 | "barAlignment": 0, 632 | "drawStyle": "line", 633 | "fillOpacity": 0, 634 | "gradientMode": "none", 635 | "hideFrom": { 636 | "legend": false, 637 | "tooltip": false, 638 | "viz": false 639 | }, 640 | "lineInterpolation": "linear", 641 | "lineWidth": 1, 642 | "pointSize": 4, 643 | "scaleDistribution": { 644 | "type": "linear" 645 | }, 646 | "showPoints": "auto", 647 | "spanNulls": false, 648 | "stacking": { 649 | "group": "A", 650 | "mode": "none" 651 | }, 652 | "thresholdsStyle": { 653 | "mode": "off" 654 | } 655 | }, 656 | "mappings": [], 657 | "thresholds": { 658 | "mode": "absolute", 659 | "steps": [ 660 | { 661 | "color": "green", 662 | "value": null 663 | }, 664 | { 665 | "color": "red", 666 | "value": 80 667 | } 668 | ] 669 | }, 670 | "unit": "s" 671 | }, 672 | "overrides": [] 673 | }, 674 | "gridPos": { 675 | "h": 9, 676 | "w": 12, 677 | "x": 0, 678 | "y": 23 679 | }, 680 | "id": 11, 681 | "options": { 682 | "legend": { 683 | "calcs": [], 684 | "displayMode": "list", 685 | "placement": "bottom" 686 | }, 687 | "tooltip": { 688 | "mode": "single" 689 | } 690 | }, 691 | "targets": [ 692 | { 693 | "datasource": { 694 | "type": "prometheus", 695 | "uid": "${datasource}" 696 | }, 697 | "exemplar": true, 698 | "expr": "histogram_quantile(0.9, sum(rate(nirn_proxy_requests_bucket{clientId=~\"$clientId\"}[5m])) by (le))", 699 | "interval": "", 700 | "legendFormat": "90th", 701 | "queryType": "randomWalk", 702 | "refId": "A" 703 | }, 704 | { 705 | "datasource": { 706 | "type": "prometheus", 707 | "uid": "${datasource}" 708 | }, 709 | "exemplar": true, 710 | "expr": "histogram_quantile(0.95, sum(rate(nirn_proxy_requests_bucket{clientId=~\"$clientId\"}[5m])) by (le))", 711 | "hide": false, 712 | "interval": "", 713 | "legendFormat": "95th", 714 | "refId": "B" 715 | }, 716 | { 717 | "datasource": { 718 | "type": "prometheus", 719 | "uid": "${datasource}" 720 | }, 721 | "exemplar": true, 722 | "expr": "histogram_quantile(0.99, sum(rate(nirn_proxy_requests_bucket{clientId=~\"$clientId\"}[5m])) by (le))", 723 | "hide": false, 724 | "interval": "", 725 | "legendFormat": "99th", 726 | "refId": "C" 727 | } 728 | ], 729 | "title": "Latency", 730 | "type": "timeseries" 731 | }, 732 | { 733 | "datasource": { 734 | "type": "prometheus", 735 | "uid": "${datasource}" 736 | }, 737 | "fieldConfig": { 738 | "defaults": { 739 | "color": { 740 | "mode": "palette-classic" 741 | }, 742 | "custom": { 743 | "axisLabel": "", 744 | "axisPlacement": "auto", 745 | "barAlignment": 0, 746 | "drawStyle": "line", 747 | "fillOpacity": 0, 748 | "gradientMode": "none", 749 | "hideFrom": { 750 | "legend": false, 751 | "tooltip": false, 752 | "viz": false 753 | }, 754 | "lineInterpolation": "linear", 755 | "lineWidth": 1, 756 | "pointSize": 5, 757 | "scaleDistribution": { 758 | "type": "linear" 759 | }, 760 | "showPoints": "auto", 761 | "spanNulls": false, 762 | "stacking": { 763 | "group": "A", 764 | "mode": "none" 765 | }, 766 | "thresholdsStyle": { 767 | "mode": "off" 768 | } 769 | }, 770 | "mappings": [], 771 | "noValue": "0", 772 | "thresholds": { 773 | "mode": "absolute", 774 | "steps": [ 775 | { 776 | "color": "green", 777 | "value": null 778 | }, 779 | { 780 | "color": "red", 781 | "value": 80 782 | } 783 | ] 784 | }, 785 | "unit": "s" 786 | }, 787 | "overrides": [] 788 | }, 789 | "gridPos": { 790 | "h": 9, 791 | "w": 12, 792 | "x": 12, 793 | "y": 23 794 | }, 795 | "id": 4, 796 | "options": { 797 | "legend": { 798 | "calcs": [], 799 | "displayMode": "list", 800 | "placement": "bottom" 801 | }, 802 | "tooltip": { 803 | "mode": "single" 804 | } 805 | }, 806 | "targets": [ 807 | { 808 | "datasource": { 809 | "type": "prometheus", 810 | "uid": "${datasource}" 811 | }, 812 | "exemplar": true, 813 | "expr": "histogram_quantile(0.90, sum(rate(nirn_proxy_requests_bucket{clientId=~\"$clientId\"}[5m])) by (le, method, route))", 814 | "instant": false, 815 | "interval": "1m", 816 | "intervalFactor": 1, 817 | "legendFormat": "{{method}} {{route}}", 818 | "queryType": "randomWalk", 819 | "refId": "A" 820 | } 821 | ], 822 | "title": "Latency 90th", 823 | "type": "timeseries" 824 | }, 825 | { 826 | "datasource": { 827 | "type": "prometheus", 828 | "uid": "${datasource}" 829 | }, 830 | "fieldConfig": { 831 | "defaults": { 832 | "color": { 833 | "mode": "palette-classic" 834 | }, 835 | "custom": { 836 | "axisLabel": "", 837 | "axisPlacement": "auto", 838 | "barAlignment": 0, 839 | "drawStyle": "line", 840 | "fillOpacity": 0, 841 | "gradientMode": "none", 842 | "hideFrom": { 843 | "legend": false, 844 | "tooltip": false, 845 | "viz": false 846 | }, 847 | "lineInterpolation": "linear", 848 | "lineWidth": 1, 849 | "pointSize": 5, 850 | "scaleDistribution": { 851 | "type": "linear" 852 | }, 853 | "showPoints": "auto", 854 | "spanNulls": false, 855 | "stacking": { 856 | "group": "A", 857 | "mode": "none" 858 | }, 859 | "thresholdsStyle": { 860 | "mode": "off" 861 | } 862 | }, 863 | "mappings": [], 864 | "thresholds": { 865 | "mode": "absolute", 866 | "steps": [ 867 | { 868 | "color": "green", 869 | "value": null 870 | }, 871 | { 872 | "color": "red", 873 | "value": 80 874 | } 875 | ] 876 | }, 877 | "unit": "s" 878 | }, 879 | "overrides": [] 880 | }, 881 | "gridPos": { 882 | "h": 8, 883 | "w": 12, 884 | "x": 0, 885 | "y": 32 886 | }, 887 | "id": 12, 888 | "options": { 889 | "legend": { 890 | "calcs": [], 891 | "displayMode": "list", 892 | "placement": "bottom" 893 | }, 894 | "tooltip": { 895 | "mode": "single" 896 | } 897 | }, 898 | "targets": [ 899 | { 900 | "datasource": { 901 | "type": "prometheus", 902 | "uid": "${datasource}" 903 | }, 904 | "exemplar": true, 905 | "expr": "histogram_quantile(0.99, sum(rate(nirn_proxy_requests_bucket{clientId=~\"$clientId\"}[5m])) by (le, method, route))", 906 | "interval": "", 907 | "legendFormat": "{{method}} {{route}}", 908 | "queryType": "randomWalk", 909 | "refId": "A" 910 | } 911 | ], 912 | "title": "Latency 99th", 913 | "type": "timeseries" 914 | }, 915 | { 916 | "datasource": { 917 | "type": "prometheus", 918 | "uid": "${datasource}" 919 | }, 920 | "fieldConfig": { 921 | "defaults": { 922 | "color": { 923 | "mode": "palette-classic" 924 | }, 925 | "custom": { 926 | "axisLabel": "", 927 | "axisPlacement": "auto", 928 | "barAlignment": 0, 929 | "drawStyle": "line", 930 | "fillOpacity": 0, 931 | "gradientMode": "none", 932 | "hideFrom": { 933 | "legend": false, 934 | "tooltip": false, 935 | "viz": false 936 | }, 937 | "lineInterpolation": "linear", 938 | "lineWidth": 1, 939 | "pointSize": 5, 940 | "scaleDistribution": { 941 | "type": "linear" 942 | }, 943 | "showPoints": "auto", 944 | "spanNulls": false, 945 | "stacking": { 946 | "group": "A", 947 | "mode": "none" 948 | }, 949 | "thresholdsStyle": { 950 | "mode": "off" 951 | } 952 | }, 953 | "mappings": [], 954 | "thresholds": { 955 | "mode": "absolute", 956 | "steps": [ 957 | { 958 | "color": "green", 959 | "value": null 960 | }, 961 | { 962 | "color": "red", 963 | "value": 80 964 | } 965 | ] 966 | } 967 | }, 968 | "overrides": [] 969 | }, 970 | "gridPos": { 971 | "h": 8, 972 | "w": 12, 973 | "x": 12, 974 | "y": 32 975 | }, 976 | "id": 22, 977 | "options": { 978 | "legend": { 979 | "calcs": [], 980 | "displayMode": "list", 981 | "placement": "bottom" 982 | }, 983 | "tooltip": { 984 | "mode": "single" 985 | } 986 | }, 987 | "targets": [ 988 | { 989 | "datasource": { 990 | "type": "prometheus", 991 | "uid": "${datasource}" 992 | }, 993 | "exemplar": true, 994 | "expr": "sum(nirn_proxy_open_connections)", 995 | "interval": "", 996 | "legendFormat": "Connections Open", 997 | "refId": "A" 998 | } 999 | ], 1000 | "title": "Open connections", 1001 | "type": "timeseries" 1002 | } 1003 | ], 1004 | "refresh": "10s", 1005 | "schemaVersion": 34, 1006 | "style": "dark", 1007 | "tags": [], 1008 | "templating": { 1009 | "list": [ 1010 | { 1011 | "current": { 1012 | "selected": false, 1013 | "text": "Prometheus", 1014 | "value": "Prometheus" 1015 | }, 1016 | "hide": 0, 1017 | "includeAll": false, 1018 | "label": "Datasource", 1019 | "multi": false, 1020 | "name": "datasource", 1021 | "options": [], 1022 | "query": "prometheus", 1023 | "queryValue": "", 1024 | "refresh": 1, 1025 | "regex": "", 1026 | "skipUrlSync": false, 1027 | "type": "datasource" 1028 | }, 1029 | { 1030 | "current": { 1031 | "selected": true, 1032 | "text": [ 1033 | "All" 1034 | ], 1035 | "value": [ 1036 | "$__all" 1037 | ] 1038 | }, 1039 | "datasource": { 1040 | "type": "prometheus", 1041 | "uid": "${datasource}" 1042 | }, 1043 | "definition": "label_values(nirn_proxy_requests_count, clientId)", 1044 | "hide": 0, 1045 | "includeAll": true, 1046 | "multi": true, 1047 | "name": "clientId", 1048 | "options": [], 1049 | "query": { 1050 | "query": "label_values(nirn_proxy_requests_count, clientId)", 1051 | "refId": "StandardVariableQuery" 1052 | }, 1053 | "refresh": 1, 1054 | "regex": "", 1055 | "skipUrlSync": false, 1056 | "sort": 0, 1057 | "type": "query" 1058 | } 1059 | ] 1060 | }, 1061 | "time": { 1062 | "from": "now-1h", 1063 | "to": "now" 1064 | }, 1065 | "timepicker": {}, 1066 | "timezone": "", 1067 | "title": "Nirn Proxy", 1068 | "uid": "LFGoppS7k", 1069 | "version": 26, 1070 | "weekStart": "" 1071 | } 1072 | -------------------------------------------------------------------------------- /k6_tests/loadtest1.js: -------------------------------------------------------------------------------- 1 | import http from 'k6/http'; 2 | import {check, sleep} from 'k6'; 3 | export const options = { 4 | noConnectionReuse: true, 5 | vus: 50, 6 | iterations: 50 7 | }; 8 | 9 | export default function() { 10 | const params = { 11 | headers: { 'Authorization': __ENV.TOKEN }, 12 | }; 13 | let res = http.get('http://localhost:8080/api/v9/gateway', params); 14 | check(res, { 'success': (r) => r.status >= 200 && r.status < 400 }); 15 | 16 | let res2 = http.get('http://localhost:8080/api/v9/guilds/203039963636301824', params); 17 | check(res2, { 'success': (r) => r.status >= 200 && r.status < 400 }); 18 | 19 | let res3 = http.get('http://localhost:8080/api/v9/guilds/203039963636301824/channels', params); 20 | check(res3, { 'success': (r) => r.status >= 200 && r.status < 400 }); 21 | } -------------------------------------------------------------------------------- /lib/bucketpath.go: -------------------------------------------------------------------------------- 1 | package lib 2 | 3 | import ( 4 | "encoding/base64" 5 | "strings" 6 | "time" 7 | "unicode/utf8" 8 | ) 9 | 10 | const ( 11 | MajorUnknown = "unk" 12 | MajorChannels = "channels" 13 | MajorGuilds = "guilds" 14 | MajorWebhooks = "webhooks" 15 | MajorInvites = "invites" 16 | MajorInteractions = "interactions" 17 | ) 18 | 19 | func IsSnowflake(str string) bool { 20 | l := len(str) 21 | if l < 17 || l > 20 { 22 | return false 23 | } 24 | for _, d := range str { 25 | if d < '0' || d > '9' { 26 | return false 27 | } 28 | } 29 | return true 30 | } 31 | 32 | func IsNumericInput(str string) bool { 33 | for _, d := range str { 34 | if d < '0' || d > '9' { 35 | return false 36 | } 37 | } 38 | return true 39 | } 40 | 41 | func GetMetricsPath(route string) string { 42 | route = GetOptimisticBucketPath(route, "") 43 | var path = "" 44 | parts := strings.Split(route, "/") 45 | 46 | if strings.HasPrefix(route, "/invite/!") { 47 | return "/invite/!" 48 | } 49 | 50 | for _, part := range parts { 51 | if part == "" { continue } 52 | if IsNumericInput(part) { 53 | path += "/!" 54 | } else { 55 | path += "/" + part 56 | } 57 | } 58 | 59 | if !utf8.ValidString(path) { 60 | logger.Warn("Non utf-8 path detected, Prometheus only supports utf-8, invalid runes will be replaced with @ in metrics. Path: " + path) 61 | path = strings.ToValidUTF8(path, "@") 62 | } 63 | 64 | return path 65 | } 66 | 67 | func GetOptimisticBucketPath(url string, method string) string { 68 | bucket := strings.Builder{} 69 | bucket.WriteByte('/') 70 | cleanUrl := strings.SplitN(url, "?", 1)[0] 71 | if strings.HasPrefix(cleanUrl, "/api/v") { 72 | cleanUrl = strings.ReplaceAll(cleanUrl, "/api/v", "") 73 | l := len(cleanUrl) 74 | i := strings.Index(cleanUrl, "/") 75 | cleanUrl = cleanUrl[i+1:l] 76 | } else { 77 | // Handle unversioned endpoints 78 | cleanUrl = strings.ReplaceAll(cleanUrl, "/api/", "") 79 | } 80 | 81 | parts := strings.Split(cleanUrl, "/") 82 | numParts := len(parts) 83 | 84 | if numParts <= 1 { 85 | return cleanUrl 86 | } 87 | 88 | currMajor := MajorUnknown 89 | // ! stands for any replaceable id 90 | switch parts[0] { 91 | case MajorChannels: 92 | if numParts == 2 { 93 | // Return the same bucket for all reqs to /channels/id 94 | // In this case, the discord bucket is the same regardless of the id 95 | bucket.WriteString(MajorChannels) 96 | bucket.WriteString("/!") 97 | return bucket.String() 98 | } 99 | bucket.WriteString(MajorChannels) 100 | bucket.WriteByte('/') 101 | bucket.WriteString(parts[1]) 102 | currMajor = MajorChannels 103 | case MajorInvites: 104 | bucket.WriteString(MajorInvites) 105 | bucket.WriteString("/!") 106 | currMajor = MajorInvites 107 | case MajorGuilds: 108 | // guilds/:guildId/channels share the same bucket for all guilds 109 | if numParts == 3 && parts[2] == "channels" { 110 | return "/" + MajorGuilds + "/!/channels" 111 | } 112 | fallthrough 113 | case MajorInteractions: 114 | if numParts == 4 && parts[3] == "callback" { 115 | return "/" + MajorInteractions + "/" + parts[1] + "/!/callback" 116 | } 117 | fallthrough 118 | case MajorWebhooks: 119 | fallthrough 120 | default: 121 | bucket.WriteString(parts[0]) 122 | bucket.WriteByte('/') 123 | bucket.WriteString(parts[1]) 124 | currMajor = parts[0] 125 | } 126 | 127 | if numParts == 2 { 128 | return bucket.String() 129 | } 130 | 131 | // At this point, the major + id part is already accounted for 132 | // In this loop, we only need to strip all remaining snowflakes, emoji names and webhook tokens(optional) 133 | for idx, part := range parts[2:] { 134 | if IsSnowflake(part) { 135 | // Custom rule for messages older than 14d 136 | if currMajor == MajorChannels && parts[idx - 1] == "messages" && method == "DELETE" { 137 | createdAt, _ := GetSnowflakeCreatedAt(part) 138 | if createdAt.Before(time.Now().Add(-1 * 14 * 24 * time.Hour)) { 139 | bucket.WriteString("/!14dmsg") 140 | } else if createdAt.After(time.Now().Add(-1 * 10 * time.Second)) { 141 | bucket.WriteString("/!10smsg") 142 | } 143 | continue 144 | } 145 | bucket.WriteString("/!") 146 | } else { 147 | if currMajor == MajorChannels && part == "reactions" { 148 | // reaction put/delete fall under a different bucket from other reaction endpoints 149 | if method == "PUT" || method == "DELETE" { 150 | bucket.WriteString("/reactions/!modify") 151 | break 152 | } 153 | //All other reaction endpoints falls under the same bucket, so it's irrelevant if the user 154 | //is passing userid, emoji, etc. 155 | bucket.WriteString("/reactions/!/!") 156 | //Reactions can only be followed by emoji/userid combo, since we don't care, break 157 | break 158 | } 159 | 160 | // Strip webhook tokens, or extract interaction ID 161 | if len(part) >= 64 { 162 | // aW50ZXJhY3Rpb246 is base64 for "interaction:" 163 | if !strings.HasPrefix(part, "aW50ZXJhY3Rpb246") { 164 | bucket.WriteString("/!") 165 | continue 166 | } 167 | 168 | var interactionId string 169 | 170 | // fix padding 171 | if i := len(part) % 4; i != 0 { 172 | part += strings.Repeat("=", 4-i) 173 | } 174 | 175 | decodedPart, err := base64.StdEncoding.DecodeString(part) 176 | if err != nil { 177 | interactionId = "Unknown" 178 | } else { 179 | interactionId = strings.Split(string(decodedPart), ":")[1] 180 | } 181 | 182 | bucket.WriteByte('/') 183 | bucket.WriteString(interactionId) 184 | continue 185 | } 186 | 187 | 188 | // Strip webhook tokens and interaction tokens 189 | if (currMajor == MajorWebhooks || currMajor == MajorInteractions) && len(part) >= 64 { 190 | bucket.WriteString("/!") 191 | continue 192 | } 193 | bucket.WriteByte('/') 194 | bucket.WriteString(part) 195 | } 196 | } 197 | 198 | return bucket.String() 199 | } -------------------------------------------------------------------------------- /lib/bucketpath_test.go: -------------------------------------------------------------------------------- 1 | package lib 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | ) 7 | 8 | func TestPaths(t *testing.T) { 9 | var tests = []struct { 10 | path, method, want string 11 | }{ 12 | // Guild Major 13 | {"/api/v9/guilds/103039963636301824", "GET", "/guilds/103039963636301824"}, 14 | // Channel major 15 | {"/api/v8/channels/203039963636301824", "GET", "/channels/!"}, 16 | {"/api/v7/channels/203039963636301824/pins", "GET", "/channels/203039963636301824/pins"}, 17 | {"/api/v6/channels/872712139712913438/messages/872712150509047809/reactions/%F0%9F%98%8B", "GET", "/channels/872712139712913438/messages/!/reactions/!/!"}, 18 | {"/api/v10/channels/872712139712913438/messages/872712150509047809/reactions/PandaOhShit:863985751205085195", "GET", "/channels/872712139712913438/messages/!/reactions/!/!"}, 19 | {"/api/v9/channels/872712139712913438/messages/872712150509047809/reactions/PandaOhShit:863985751205085195", "PUT", "/channels/872712139712913438/messages/!/reactions/!modify"}, 20 | {"/api/v9/channels/872712139712913438/messages/872712150509047809/reactions/PandaOhShit:863985751205085195", "DELETE", "/channels/872712139712913438/messages/!/reactions/!modify"}, 21 | {"/api/v9/channels/872712139712913438/messages/872712150509047809/reactions/PandaOhShit:863985751205085195/@me", "DELETE", "/channels/872712139712913438/messages/!/reactions/!modify"}, 22 | {"/api/v9/channels/872712139712913438/messages/872712150509047809/reactions/PandaOhShit:863985751205085195/203039963636301824", "DELETE", "/channels/872712139712913438/messages/!/reactions/!modify"}, 23 | // Hooks major 24 | {"/api/v9/webhooks/203039963636301824", "GET", "/webhooks/203039963636301824"}, 25 | {"/api/v9/webhooks/203039963636301824/VSOzAqY1OZFF5WJVtbIzFtmjGupk-84Hn0A_ZzToF_CHsPIeCk0Q9Uok_mjxR0dNtApI", "POST", "/webhooks/203039963636301824/!"}, 26 | // Invites major 27 | {"/api/v9/invites/dyno", "GET", "/invites/!"}, 28 | // Interactions major 29 | {"/api/v9/interactions/203039963636301824/aW50ZXJhY3Rpb246ODg3NTU5MDA01AY4NTUxNDU0OnZwS3QycDhvREk2aVF3U1BqN2prcXBkRmNqNlp4VEhGRjZvSVlXSGh4WG4yb3l6Z3B6NTBPNVc3OHphV05OULLMOHBMa2RTZmVKd3lzVDA2b2h3OTUxaFJ4QlN0dkxXallPcmhnSHNJb0tSV0M5ZzY1NkN4VGRvemFOSHY4b05c/callback", "GET", "/interactions/203039963636301824/!/callback"}, 30 | // Interaction followup webhooks 31 | {"/api/v10/webhooks/203039963636301824/aW50ZXJhY3Rpb246MTEwMzA0OTQyMDkzMDU2ODMyMjpOZUllWHdNU2J4RXBFMHVYRjBpU0pHMDdEb3BhM3ZlYklBODlMUmtlUXlRbzlpZzYyTnpLU0dqdWlyVlBvZnBSUlJHbUJHYlJ0N29MbE9KQUJVTFk4bTR4UzFtZEpEeXJyY0hBUERmTEhKVE9wRkNzU1FFWUkwTnlpWFY2WHdrRg/messages/@original", "POST", "/webhooks/203039963636301824/1103049420930568322/messages/@original"}, 32 | // No known major 33 | {"/api/v9/invalid/203039963636301824", "GET", "/invalid/203039963636301824"}, 34 | {"/api/v9/invalid/203039963636301824/route/203039963636301824", "GET", "/invalid/203039963636301824/route/!"}, 35 | //Special case for /guilds/:id/channels 36 | {"/api/v9/guilds/203039963636301824/channels", "GET", "/guilds/!/channels"}, 37 | // Wierd routes 38 | {"/api/v9/guilds/templates/203039963636301824", "GET", "/guilds/templates/!"}, 39 | // Unversioned routes 40 | {"/api/webhooks/203039963636301824/VSOzAqY1OZFF5WJVtbIzFtmjGupk-84Hn0A_ZzToF_CHsPIeCk0Q9Uok_mjxR0dNtApI", "POST", "/webhooks/203039963636301824/!"}, 41 | {"/api/interactions/203039963636301824/aW50ZXJhY3Rpb246ODg3NTU5MDA01AY4NTUxNDU0OnZwS3QycDhvREk2aVF3U1BqN2prcXBkRmNqNlp4VEhGRjZvSVlXSGh4WG4yb3l6Z3B6NTBPNVc3OHphV05OULLMOHBMa2RTZmVKd3lzVDA2b2h3OTUxaFJ4QlN0dkxXallPcmhnSHNJb0tSV0M5ZzY1NkN4VGRvemFOSHY4b05c/callback", "GET", "/interactions/203039963636301824/!/callback"}, 42 | {"/api/channels/872712139712913438/messages/872712150509047809/reactions/PandaOhShit:863985751205085195", "GET", "/channels/872712139712913438/messages/!/reactions/!/!"}, 43 | {"/api/invites/dyno", "GET", "/invites/!"}, 44 | // Application commands 45 | {"/api/v9/applications/203039963636301824/commands", "GET", "/applications/203039963636301824/commands"}, 46 | {"/api/v9/applications/203039963636301824/commands/203039963636301824", "GET", "/applications/203039963636301824/commands/!"}, 47 | } 48 | for _, tt := range tests { 49 | testname := fmt.Sprintf("%s-%s", tt.method, tt.path) 50 | t.Run(testname, func(t *testing.T) { 51 | bucket := GetOptimisticBucketPath(tt.path, tt.method) 52 | if bucket != tt.want { 53 | t.Errorf("Expected %s but got %s", tt.want, bucket) 54 | } 55 | }) 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /lib/discord.go: -------------------------------------------------------------------------------- 1 | package lib 2 | 3 | import ( 4 | "context" 5 | "crypto/tls" 6 | "encoding/json" 7 | "errors" 8 | "github.com/sirupsen/logrus" 9 | "io" 10 | "io/ioutil" 11 | "math" 12 | "net" 13 | "net/http" 14 | "strconv" 15 | "strings" 16 | "time" 17 | ) 18 | 19 | var client *http.Client 20 | 21 | var contextTimeout time.Duration 22 | 23 | var globalOverrideMap = make(map[string]uint) 24 | 25 | var disableRestLimitDetection = false 26 | 27 | type BotGatewayResponse struct { 28 | SessionStartLimit map[string]int `json:"session_start_limit"` 29 | } 30 | 31 | type BotUserResponse struct { 32 | Id string `json:"id"` 33 | Username string `json:"username"` 34 | Discrim string `json:"discriminator"` 35 | } 36 | 37 | func createTransport(ip string, disableHttp2 bool) http.RoundTripper { 38 | var transport http.Transport 39 | if ip == "" { 40 | // http.DefaultTransport options 41 | transport = http.Transport{ 42 | Proxy: http.ProxyFromEnvironment, 43 | DialContext: (&net.Dialer{ 44 | Timeout: 30 * time.Second, 45 | KeepAlive: 30 * time.Second, 46 | }).DialContext, 47 | ForceAttemptHTTP2: true, 48 | MaxIdleConns: 1000, 49 | IdleConnTimeout: 90 * time.Second, 50 | TLSHandshakeTimeout: 10 * time.Second, 51 | ExpectContinueTimeout: 1 * time.Second, 52 | } 53 | } else { 54 | addr, err := net.ResolveTCPAddr("tcp", ip+":0") 55 | 56 | if err != nil { 57 | panic(err) 58 | } 59 | 60 | dialer := &net.Dialer{ 61 | LocalAddr: addr, 62 | Timeout: 30 * time.Second, 63 | KeepAlive: 30 * time.Second, 64 | } 65 | 66 | dialContext := func(ctx context.Context, network, addr string) (net.Conn, error) { 67 | conn, err := dialer.Dial(network, addr) 68 | return conn, err 69 | } 70 | 71 | transport = http.Transport{ 72 | ForceAttemptHTTP2: true, 73 | MaxIdleConns: 1000, 74 | IdleConnTimeout: 90 * time.Second, 75 | TLSHandshakeTimeout: 10 * time.Second, 76 | ExpectContinueTimeout: 2 * time.Second, 77 | DialContext: dialContext, 78 | ResponseHeaderTimeout: 0, 79 | } 80 | } 81 | 82 | if disableHttp2 { 83 | transport.TLSNextProto = map[string]func(string, *tls.Conn) http.RoundTripper{} 84 | transport.ForceAttemptHTTP2 = false 85 | } 86 | 87 | return &transport 88 | } 89 | 90 | func parseGlobalOverrides(overrides string) { 91 | // Format: ":,: 92 | 93 | if overrides == "" { 94 | return 95 | } 96 | 97 | overrideList := strings.Split(overrides, ",") 98 | for _, override := range overrideList { 99 | opts := strings.Split(override, ":") 100 | if len(opts) != 2 { 101 | panic("Invalid bot global ratelimit overrides") 102 | } 103 | 104 | limit, err := strconv.ParseInt(opts[1], 10, 32) 105 | 106 | if err != nil { 107 | panic("Failed to parse global ratelimit overrides") 108 | } 109 | 110 | globalOverrideMap[opts[0]] = uint(limit) 111 | } 112 | } 113 | 114 | func ConfigureDiscordHTTPClient(ip string, timeout time.Duration, disableHttp2 bool, globalOverrides string, disableRestDetection bool) { 115 | transport := createTransport(ip, disableHttp2) 116 | client = &http.Client{ 117 | Transport: transport, 118 | Timeout: 90 * time.Second, 119 | } 120 | 121 | contextTimeout = timeout 122 | 123 | disableRestLimitDetection = disableRestDetection 124 | 125 | parseGlobalOverrides(globalOverrides) 126 | } 127 | 128 | func GetBotGlobalLimit(token string, user *BotUserResponse) (uint, error) { 129 | if token == "" { 130 | return math.MaxUint32, nil 131 | } 132 | 133 | if user != nil { 134 | limitOverride, ok := globalOverrideMap[user.Id] 135 | if ok { 136 | return limitOverride, nil 137 | } 138 | } 139 | 140 | if strings.HasPrefix(token, "Bearer") { 141 | return 50, nil 142 | } 143 | 144 | if disableRestLimitDetection { 145 | return 50, nil 146 | } 147 | 148 | bot, err := doDiscordReq(context.Background(), "/api/v9/gateway/bot", "GET", nil, map[string][]string{"Authorization": {token}}, "") 149 | 150 | if err != nil { 151 | return 0, err 152 | } 153 | 154 | switch { 155 | case bot.StatusCode == 401: 156 | // In case a 401 is encountered, we return math.MaxUint32 to allow requests through to fail fast 157 | return math.MaxUint32, errors.New("invalid token - nirn-proxy") 158 | case bot.StatusCode == 429: 159 | return 0, errors.New("429 on gateway/bot") 160 | case bot.StatusCode == 500: 161 | return 0, errors.New("500 on gateway/bot") 162 | } 163 | 164 | body, _ := ioutil.ReadAll(bot.Body) 165 | 166 | var s BotGatewayResponse 167 | 168 | err = json.Unmarshal(body, &s) 169 | if err != nil { 170 | return 0, err 171 | } 172 | 173 | concurrency := s.SessionStartLimit["max_concurrency"] 174 | 175 | if concurrency == 1 { 176 | return 50, nil 177 | } else { 178 | if 25*concurrency > 500 { 179 | return uint(25 * concurrency), nil 180 | } 181 | return 500, nil 182 | } 183 | } 184 | 185 | func GetBotUser(token string) (*BotUserResponse, error) { 186 | if token == "" { 187 | return nil, errors.New("no token provided") 188 | } 189 | 190 | bot, err := doDiscordReq(context.Background(), "/api/v9/users/@me", "GET", nil, map[string][]string{"Authorization": {token}}, "") 191 | 192 | if err != nil { 193 | return nil, err 194 | } 195 | 196 | switch { 197 | case bot.StatusCode == 429: 198 | return nil, errors.New("429 on users/@me") 199 | case bot.StatusCode == 500: 200 | return nil, errors.New("500 on users/@me") 201 | } 202 | 203 | body, _ := ioutil.ReadAll(bot.Body) 204 | 205 | var s BotUserResponse 206 | 207 | err = json.Unmarshal(body, &s) 208 | if err != nil { 209 | return nil, err 210 | } 211 | 212 | return &s, nil 213 | } 214 | 215 | func doDiscordReq(ctx context.Context, path string, method string, body io.ReadCloser, header http.Header, query string) (*http.Response, error) { 216 | discordReq, err := http.NewRequestWithContext(ctx, method, "https://discord.com"+path+"?"+query, body) 217 | if err != nil { 218 | return nil, err 219 | } 220 | 221 | discordReq.Header = header 222 | startTime := time.Now() 223 | discordResp, err := client.Do(discordReq) 224 | 225 | identifier := ctx.Value("identifier") 226 | if identifier == nil { 227 | // Queues always have an identifier, if there's none in the context, we called the method from outside a queue 228 | identifier = "Internal" 229 | } 230 | 231 | if err == nil { 232 | route := GetMetricsPath(path) 233 | status := discordResp.Status 234 | method := discordResp.Request.Method 235 | elapsed := time.Since(startTime).Seconds() 236 | 237 | if discordResp.StatusCode == 429 { 238 | if discordResp.Header.Get("x-ratelimit-scope") == "shared" { 239 | status = "429 Shared" 240 | } 241 | } 242 | 243 | RequestHistogram.With(map[string]string{"route": route, "status": status, "method": method, "clientId": identifier.(string)}).Observe(elapsed) 244 | } 245 | return discordResp, err 246 | } 247 | 248 | func ProcessRequest(ctx context.Context, item *QueueItem) (*http.Response, error) { 249 | req := item.Req 250 | res := *item.Res 251 | 252 | ctx, cancel := context.WithTimeout(ctx, contextTimeout) 253 | defer cancel() 254 | discordResp, err := doDiscordReq(ctx, req.URL.Path, req.Method, req.Body, req.Header.Clone(), req.URL.RawQuery) 255 | 256 | if err != nil { 257 | if ctx.Err() == context.DeadlineExceeded { 258 | res.WriteHeader(408) 259 | } else { 260 | res.WriteHeader(500) 261 | } 262 | _, _ = res.Write([]byte(err.Error())) 263 | return nil, err 264 | } 265 | 266 | logger.WithFields(logrus.Fields{ 267 | "method": req.Method, 268 | "path": req.URL.String(), 269 | "status": discordResp.Status, 270 | // TODO: Remove this when 429s are not a problem anymore 271 | "discordBucket": discordResp.Header.Get("x-ratelimit-bucket"), 272 | }).Debug("Discord request") 273 | 274 | err = CopyResponseToResponseWriter(discordResp, item.Res) 275 | 276 | if err != nil { 277 | return nil, err 278 | } 279 | 280 | return discordResp, nil 281 | } 282 | -------------------------------------------------------------------------------- /lib/distributed_global.go: -------------------------------------------------------------------------------- 1 | package lib 2 | 3 | import ( 4 | "context" 5 | "errors" 6 | "github.com/Clever/leakybucket" 7 | "github.com/Clever/leakybucket/memory" 8 | "github.com/sirupsen/logrus" 9 | "net/http" 10 | "strconv" 11 | "sync" 12 | "time" 13 | ) 14 | 15 | type ClusterGlobalRateLimiter struct { 16 | sync.RWMutex 17 | globalBucketsMap map[uint64]*leakybucket.Bucket 18 | memStorage *memory.Storage 19 | } 20 | 21 | func NewClusterGlobalRateLimiter() *ClusterGlobalRateLimiter { 22 | memStorage := memory.New() 23 | return &ClusterGlobalRateLimiter{ 24 | memStorage: memStorage, 25 | globalBucketsMap: make(map[uint64]*leakybucket.Bucket), 26 | } 27 | } 28 | 29 | func (c *ClusterGlobalRateLimiter) Take(botHash uint64, botLimit uint) { 30 | bucket := *c.getOrCreate(botHash, botLimit) 31 | takeGlobal: 32 | _, err := bucket.Add(1) 33 | if err != nil { 34 | reset := bucket.Reset() 35 | logger.WithFields(logrus.Fields{ 36 | "waitTime": time.Until(reset), 37 | }).Trace("Failed to grab global token, sleeping for a bit") 38 | time.Sleep(time.Until(reset)) 39 | goto takeGlobal 40 | } 41 | } 42 | 43 | func (c *ClusterGlobalRateLimiter) getOrCreate(botHash uint64, botLimit uint) *leakybucket.Bucket { 44 | c.RLock() 45 | b, ok := c.globalBucketsMap[botHash] 46 | c.RUnlock() 47 | if !ok { 48 | c.Lock() 49 | // Check if it wasn't created while we didnt hold the exclusive lock 50 | b, ok = c.globalBucketsMap[botHash] 51 | if ok { 52 | c.Unlock() 53 | return b 54 | } 55 | 56 | globalBucket, _ := c.memStorage.Create(strconv.FormatUint(botHash, 10), botLimit, 1 * time.Second) 57 | c.globalBucketsMap[botHash] = &globalBucket 58 | c.Unlock() 59 | return &globalBucket 60 | } else { 61 | return b 62 | } 63 | } 64 | 65 | 66 | func (c *ClusterGlobalRateLimiter) FireGlobalRequest(ctx context.Context, addr string, botHash uint64, botLimit uint) error { 67 | globalReq, err := http.NewRequestWithContext(ctx, "GET", "http://" + addr + "/nirn/global", nil) 68 | if err != nil { 69 | return err 70 | } 71 | 72 | globalReq.Header.Set("bot-hash", strconv.FormatUint(botHash, 10)) 73 | globalReq.Header.Set("bot-limit", strconv.FormatUint(uint64(botLimit), 10)) 74 | 75 | // The node handling the request will only return if we grabbed a token or an error was thrown 76 | resp, err := client.Do(globalReq) 77 | logger.Trace("Got go-ahead for global") 78 | 79 | if err != nil { 80 | return err 81 | } 82 | 83 | if resp.StatusCode != 200 { 84 | return errors.New("global request failed with status " + resp.Status) 85 | } 86 | 87 | return nil 88 | } -------------------------------------------------------------------------------- /lib/env.go: -------------------------------------------------------------------------------- 1 | package lib 2 | 3 | import ( 4 | "os" 5 | "strconv" 6 | ) 7 | 8 | func EnvGet(name string, defaultVal string) string { 9 | val := os.Getenv(name) 10 | if val == "" { 11 | return defaultVal 12 | } 13 | return val 14 | } 15 | 16 | func EnvGetBool(name string, defaultVal bool) bool { 17 | val := os.Getenv(name) 18 | if val == "" { 19 | return defaultVal 20 | } 21 | 22 | if val != "true" && val != "false" { 23 | panic("Invalid env var, expected true or false, got " + val + " for " + name) 24 | } 25 | return val == "true" 26 | } 27 | 28 | 29 | func EnvMustGet(name string) string { 30 | val := os.Getenv(name) 31 | if val == "" { 32 | panic("ENV var " + name + " is empty") 33 | } 34 | return val 35 | } 36 | 37 | func EnvGetInt(name string, defaultVal int) int { 38 | val := os.Getenv(name) 39 | if val == "" { 40 | return defaultVal 41 | } 42 | 43 | valParsed, err := strconv.ParseInt(val, 10, 64) 44 | if err != nil { 45 | panic("Failed to parse " + name) 46 | } 47 | return int(valParsed) 48 | } -------------------------------------------------------------------------------- /lib/http.go: -------------------------------------------------------------------------------- 1 | package lib 2 | 3 | import ( 4 | "io/ioutil" 5 | "net/http" 6 | "strings" 7 | ) 8 | 9 | func copyHeader(dst, src http.Header) { 10 | dst["Date"] = nil 11 | dst["Content-Type"] = nil 12 | for k, vv := range src { 13 | for _, v := range vv { 14 | if k != "Content-Length" { 15 | dst[strings.ToLower(k)] = []string{v} 16 | } 17 | } 18 | } 19 | } 20 | 21 | func CopyResponseToResponseWriter(resp *http.Response, respWriter *http.ResponseWriter) error { 22 | writer := *respWriter 23 | body, err := ioutil.ReadAll(resp.Body) 24 | if err != nil { 25 | writer.WriteHeader(500) 26 | _, _ = writer.Write([]byte(err.Error())) 27 | return err 28 | } 29 | 30 | copyHeader(writer.Header(), resp.Header) 31 | writer.WriteHeader(resp.StatusCode) 32 | 33 | _, err = writer.Write(body) 34 | if err != nil { 35 | return err 36 | } 37 | return nil 38 | } -------------------------------------------------------------------------------- /lib/logger.go: -------------------------------------------------------------------------------- 1 | package lib 2 | 3 | import ( 4 | "github.com/sirupsen/logrus" 5 | "regexp" 6 | ) 7 | 8 | type GlobalHook struct { 9 | } 10 | 11 | var loggerHookRegex = regexp.MustCompile("(\\/[0-9]{17,26}\\/)[a-zA-Z0-9\\-_]{63,}") 12 | 13 | func (h *GlobalHook) Levels() []logrus.Level { 14 | return logrus.AllLevels 15 | } 16 | 17 | func (h *GlobalHook) Fire(e *logrus.Entry) error { 18 | e.Message = loggerHookRegex.ReplaceAllString(e.Message, "$1:token") 19 | if e.Data["path"] != nil { 20 | e.Data["path"] = loggerHookRegex.ReplaceAllString(e.Data["path"].(string), "$1:token") 21 | } 22 | if logrus.ErrorLevel >= e.Level { 23 | ErrorCounter.Inc() 24 | } 25 | return nil 26 | } 27 | 28 | var logger *logrus.Logger 29 | 30 | func SetLogger(l *logrus.Logger) { 31 | logger = l 32 | logger.AddHook(&GlobalHook{}) 33 | } 34 | -------------------------------------------------------------------------------- /lib/memberlist.go: -------------------------------------------------------------------------------- 1 | package lib 2 | 3 | import ( 4 | "github.com/hashicorp/memberlist" 5 | "os" 6 | "time" 7 | ) 8 | 9 | func InitMemberList(knownMembers []string, port int, proxyPort string, manager *QueueManager) *memberlist.Memberlist { 10 | config := memberlist.DefaultLANConfig() 11 | config.BindPort = port 12 | config.AdvertisePort = port 13 | config.Delegate = NirnDelegate{ 14 | proxyPort: proxyPort, 15 | } 16 | 17 | config.Events = manager.GetEventDelegate() 18 | 19 | //DEBUG CODE 20 | if os.Getenv("NODE_NAME") != "" { 21 | config.Name = os.Getenv("NODE_NAME") 22 | config.DeadNodeReclaimTime = 1 * time.Nanosecond 23 | } 24 | 25 | list, err := memberlist.Create(config) 26 | if err != nil { 27 | panic("Failed to create memberlist: " + err.Error()) 28 | } 29 | 30 | manager.SetCluster(list, proxyPort) 31 | 32 | _, err = list.Join(knownMembers) 33 | if err != nil { 34 | logger.Info("Failed to join existing cluster, ok if this is the first node") 35 | logger.Error(err) 36 | } 37 | 38 | var members string 39 | for _, member := range list.Members() { 40 | members += member.Name + " " 41 | } 42 | 43 | logger.Info("Connected to cluster nodes: [ " + members + "]") 44 | return list 45 | } -------------------------------------------------------------------------------- /lib/memberlist_delegate.go: -------------------------------------------------------------------------------- 1 | package lib 2 | 3 | import "github.com/hashicorp/memberlist" 4 | 5 | type NirnDelegate struct { 6 | memberlist.Delegate 7 | proxyPort string 8 | } 9 | 10 | func (d NirnDelegate) NodeMeta(limit int) []byte { 11 | return []byte(d.proxyPort) 12 | } 13 | 14 | func (d NirnDelegate) NotifyMsg(msg []byte) {} 15 | 16 | func (d NirnDelegate) GetBroadcasts(overhead int, limit int) [][]byte { 17 | return [][]byte{} 18 | } 19 | 20 | func (d NirnDelegate) LocalState(join bool) []byte { 21 | return []byte{} 22 | } 23 | 24 | func (d NirnDelegate) MergeRemoteState(buf []byte, join bool) {} 25 | -------------------------------------------------------------------------------- /lib/memberlist_events.go: -------------------------------------------------------------------------------- 1 | package lib 2 | 3 | import "github.com/hashicorp/memberlist" 4 | 5 | type NirnEvents struct { 6 | memberlist.EventDelegate 7 | OnJoin func(node *memberlist.Node) 8 | OnLeave func(node *memberlist.Node) 9 | } 10 | 11 | func formatNodeInfo(node *memberlist.Node) string { 12 | return node.Name + " - " + node.Address() + " - listenport: " + string(node.Meta) 13 | } 14 | 15 | func (d NirnEvents) NotifyJoin(node *memberlist.Node) { 16 | logger.Info("Node joined the cluster: " + formatNodeInfo(node)) 17 | d.OnJoin(node) 18 | } 19 | func (d NirnEvents) NotifyLeave(node *memberlist.Node) { 20 | logger.Info("Node left the cluster: " + formatNodeInfo(node)) 21 | d.OnLeave(node) 22 | } 23 | func (d NirnEvents) NotifyUpdate(node *memberlist.Node) {} -------------------------------------------------------------------------------- /lib/metrics.go: -------------------------------------------------------------------------------- 1 | package lib 2 | 3 | import ( 4 | "github.com/prometheus/client_golang/prometheus" 5 | "github.com/prometheus/client_golang/prometheus/promauto" 6 | "github.com/prometheus/client_golang/prometheus/promhttp" 7 | "net/http" 8 | ) 9 | 10 | var ( 11 | ErrorCounter = promauto.NewCounter(prometheus.CounterOpts{ 12 | Name: "nirn_proxy_error", 13 | Help: "The total number of errors when processing requests", 14 | }) 15 | 16 | RequestHistogram = prometheus.NewHistogramVec(prometheus.HistogramOpts{ 17 | Name: "nirn_proxy_requests", 18 | Help: "Request histogram", 19 | Buckets: []float64{.1, .25, 1, 2.5, 5, 20}, 20 | }, []string{"method", "status", "route", "clientId"}) 21 | 22 | ConnectionsOpen = promauto.NewGaugeVec(prometheus.GaugeOpts{ 23 | Name: "nirn_proxy_open_connections", 24 | Help: "Gauge for client connections currently open with the proxy", 25 | }, []string{"method", "route"}) 26 | 27 | RequestsRoutedSent = promauto.NewCounter(prometheus.CounterOpts{ 28 | Name: "nirn_proxy_requests_routed_sent", 29 | Help: "Counter for requests routed from this node into other nodes", 30 | }) 31 | 32 | RequestsRoutedRecv = promauto.NewCounter(prometheus.CounterOpts{ 33 | Name: "nirn_proxy_requests_routed_received", 34 | Help: "Counter for requests received from other nodes", 35 | }) 36 | 37 | RequestsRoutedError = promauto.NewCounter(prometheus.CounterOpts{ 38 | Name: "nirn_proxy_requests_routed_error", 39 | Help: "Counter for failed requests routed from this node", 40 | }) 41 | ) 42 | 43 | func StartMetrics(addr string) { 44 | prometheus.MustRegister(RequestHistogram) 45 | http.Handle("/metrics", promhttp.Handler()) 46 | logger.Info("Starting metrics server on " + addr) 47 | err := http.ListenAndServe(addr, nil) 48 | if err != nil { 49 | logger.Error(err) 50 | return 51 | } 52 | } -------------------------------------------------------------------------------- /lib/profile.go: -------------------------------------------------------------------------------- 1 | package lib 2 | 3 | import ( 4 | "net/http" 5 | _ "net/http/pprof" 6 | ) 7 | 8 | func StartProfileServer() { 9 | logger.Info("Profiling endpoints loaded on :7654") 10 | http.ListenAndServe(":7654", nil) 11 | } -------------------------------------------------------------------------------- /lib/queue.go: -------------------------------------------------------------------------------- 1 | package lib 2 | 3 | import ( 4 | "context" 5 | "errors" 6 | "github.com/Clever/leakybucket" 7 | "github.com/Clever/leakybucket/memory" 8 | "github.com/sirupsen/logrus" 9 | "net/http" 10 | "strconv" 11 | "strings" 12 | "sync" 13 | "sync/atomic" 14 | "time" 15 | ) 16 | 17 | type QueueItem struct { 18 | Req *http.Request 19 | Res *http.ResponseWriter 20 | doneChan chan *http.Response 21 | errChan chan error 22 | } 23 | 24 | type QueueChannel struct { 25 | ch chan *QueueItem 26 | lastUsed time.Time 27 | } 28 | 29 | type RequestQueue struct { 30 | sync.RWMutex 31 | globalLockedUntil *int64 32 | // bucket path hash as key 33 | queues map[uint64]*QueueChannel 34 | processor func(ctx context.Context, item *QueueItem) (*http.Response, error) 35 | globalBucket leakybucket.Bucket 36 | // bufferSize Defines the size of the request channel buffer for each bucket 37 | bufferSize int 38 | user *BotUserResponse 39 | identifier string 40 | isTokenInvalid *int64 41 | botLimit uint 42 | queueType QueueType 43 | } 44 | 45 | func NewRequestQueue(processor func(ctx context.Context, item *QueueItem) (*http.Response, error), token string, bufferSize int) (*RequestQueue, error) { 46 | queueType := NoAuth 47 | var user *BotUserResponse 48 | var err error 49 | if !strings.HasPrefix(token, "Bearer") { 50 | user, err = GetBotUser(token) 51 | if err != nil && token != "" { 52 | return nil, err 53 | } 54 | } else { 55 | queueType = Bearer 56 | } 57 | 58 | limit, err := GetBotGlobalLimit(token, user) 59 | memStorage := memory.New() 60 | globalBucket, _ := memStorage.Create("global", limit, 1*time.Second) 61 | if err != nil { 62 | if strings.HasPrefix(err.Error(), "invalid token") { 63 | // Return a queue that will only return 401s 64 | var invalid = new(int64) 65 | *invalid = 999 66 | return &RequestQueue{ 67 | queues: make(map[uint64]*QueueChannel), 68 | processor: processor, 69 | globalBucket: globalBucket, 70 | globalLockedUntil: new(int64), 71 | bufferSize: bufferSize, 72 | user: nil, 73 | identifier: "InvalidTokenQueue", 74 | isTokenInvalid: invalid, 75 | botLimit: limit, 76 | }, nil 77 | } 78 | 79 | return nil, err 80 | } 81 | 82 | identifier := "NoAuth" 83 | if user != nil { 84 | queueType = Bot 85 | identifier = user.Username + "#" + user.Discrim 86 | } 87 | 88 | if queueType == Bearer { 89 | identifier = "Bearer" 90 | } 91 | 92 | ret := &RequestQueue{ 93 | queues: make(map[uint64]*QueueChannel), 94 | processor: processor, 95 | globalBucket: globalBucket, 96 | globalLockedUntil: new(int64), 97 | bufferSize: bufferSize, 98 | user: user, 99 | identifier: identifier, 100 | isTokenInvalid: new(int64), 101 | botLimit: limit, 102 | queueType: queueType, 103 | } 104 | 105 | if queueType != Bearer { 106 | logger.WithFields(logrus.Fields{"globalLimit": limit, "identifier": identifier, "bufferSize": bufferSize}).Info("Created new queue") 107 | // Only sweep bot queues, bearer queues get completely destroyed and hold way less endpoints 108 | go ret.tickSweep() 109 | } else { 110 | logger.WithFields(logrus.Fields{"globalLimit": limit, "identifier": identifier, "bufferSize": bufferSize}).Debug("Created new bearer queue") 111 | } 112 | 113 | return ret, nil 114 | } 115 | 116 | func (q *RequestQueue) destroy() { 117 | q.Lock() 118 | defer q.Unlock() 119 | logger.Debug("Destroying queue") 120 | for _, val := range q.queues { 121 | close(val.ch) 122 | } 123 | } 124 | 125 | func (q *RequestQueue) sweep() { 126 | q.Lock() 127 | defer q.Unlock() 128 | logger.Info("Sweep start") 129 | sweptEntries := 0 130 | for key, val := range q.queues { 131 | if time.Since(val.lastUsed) > 10*time.Minute { 132 | close(val.ch) 133 | delete(q.queues, key) 134 | sweptEntries++ 135 | } 136 | } 137 | logger.WithFields(logrus.Fields{"sweptEntries": sweptEntries}).Info("Finished sweep") 138 | } 139 | 140 | func (q *RequestQueue) tickSweep() { 141 | t := time.NewTicker(5 * time.Minute) 142 | 143 | for range t.C { 144 | q.sweep() 145 | } 146 | } 147 | 148 | func safeSend(queue *QueueChannel, value *QueueItem) { 149 | defer func() { 150 | if recover() != nil { 151 | value.errChan <- errors.New("failed to send due to closed channel, sending 429 for client to retry") 152 | Generate429(value.Res) 153 | } 154 | }() 155 | 156 | queue.ch <- value 157 | } 158 | 159 | func (q *RequestQueue) Queue(req *http.Request, res *http.ResponseWriter, path string, pathHash uint64) error { 160 | logger.WithFields(logrus.Fields{ 161 | "bucket": path, 162 | "path": req.URL.Path, 163 | "method": req.Method, 164 | }).Trace("Inbound request") 165 | 166 | ch := q.getQueueChannel(path, pathHash) 167 | 168 | doneChan := make(chan *http.Response) 169 | errChan := make(chan error) 170 | 171 | safeSend(ch, &QueueItem{req, res, doneChan, errChan}) 172 | 173 | select { 174 | case <-doneChan: 175 | return nil 176 | case err := <-errChan: 177 | return err 178 | } 179 | } 180 | 181 | func (q *RequestQueue) getQueueChannel(path string, pathHash uint64) *QueueChannel { 182 | t := time.Now() 183 | q.Lock() 184 | defer q.Unlock() 185 | ch, ok := q.queues[pathHash] 186 | if !ok { 187 | ch = &QueueChannel{ 188 | ch: make(chan *QueueItem, q.bufferSize), 189 | lastUsed: t, 190 | } 191 | q.queues[pathHash] = ch 192 | // It's important that we only have 1 goroutine per channel 193 | go q.subscribe(ch, path, pathHash) 194 | } else { 195 | ch.lastUsed = t 196 | } 197 | return ch 198 | } 199 | 200 | func parseHeaders(headers *http.Header, preferRetryAfter bool) (int64, int64, time.Duration, bool, error) { 201 | if headers == nil { 202 | return 0, 0, 0, false, errors.New("null headers") 203 | } 204 | 205 | limit := headers.Get("x-ratelimit-limit") 206 | remaining := headers.Get("x-ratelimit-remaining") 207 | resetAfter := headers.Get("x-ratelimit-reset-after") 208 | retryAfter := headers.Get("retry-after") 209 | if resetAfter == "" || (preferRetryAfter && retryAfter != "") { 210 | // Globals return no x-ratelimit-reset-after headers, shared ratelimits have a wrong reset-after 211 | // this is the best option without parsing the body 212 | resetAfter = headers.Get("retry-after") 213 | } 214 | isGlobal := headers.Get("x-ratelimit-global") == "true" 215 | 216 | var resetParsed float64 217 | var reset time.Duration = 0 218 | var err error 219 | if resetAfter != "" { 220 | resetParsed, err = strconv.ParseFloat(resetAfter, 64) 221 | if err != nil { 222 | return 0, 0, 0, false, err 223 | } 224 | 225 | // Convert to MS instead of seconds to preserve decimal precision 226 | reset = time.Duration(int(resetParsed*1000)) * time.Millisecond 227 | } 228 | 229 | if isGlobal { 230 | return 0, 0, reset, isGlobal, nil 231 | } 232 | 233 | if limit == "" { 234 | return 0, 0, reset, false, nil 235 | } 236 | 237 | limitParsed, err := strconv.ParseInt(limit, 10, 32) 238 | if err != nil { 239 | return 0, 0, 0, false, err 240 | } 241 | 242 | remainingParsed, err := strconv.ParseInt(remaining, 10, 32) 243 | if err != nil { 244 | return 0, 0, 0, false, err 245 | } 246 | 247 | return limitParsed, remainingParsed, reset, isGlobal, nil 248 | } 249 | 250 | func return404webhook(item *QueueItem) { 251 | res := *item.Res 252 | res.WriteHeader(404) 253 | body := "{\n \"message\": \"Unknown Webhook\",\n \"code\": 10015\n}" 254 | _, err := res.Write([]byte(body)) 255 | if err != nil { 256 | item.errChan <- err 257 | return 258 | } 259 | item.doneChan <- nil 260 | 261 | } 262 | 263 | func return401(item *QueueItem) { 264 | res := *item.Res 265 | res.WriteHeader(401) 266 | body := "{\n\t\"message\": \"401: Unauthorized\",\n\t\"code\": 0\n}" 267 | _, err := res.Write([]byte(body)) 268 | if err != nil { 269 | item.errChan <- err 270 | return 271 | } 272 | item.doneChan <- nil 273 | } 274 | 275 | func isInteraction(url string) bool { 276 | parts := strings.Split(strings.SplitN(url, "?", 1)[0], "/") 277 | for _, p := range parts { 278 | if len(p) > 128 { 279 | return true 280 | } 281 | } 282 | return false 283 | } 284 | 285 | func (q *RequestQueue) subscribe(ch *QueueChannel, path string, pathHash uint64) { 286 | // This function has 1 goroutine for each bucket path 287 | // Locking here is not needed 288 | 289 | //Only used for logging 290 | var prevRem int64 = 0 291 | var prevReset time.Duration = 0 292 | 293 | // Fail fast path for webhook 404s 294 | var ret404 = false 295 | for item := range ch.ch { 296 | ctx := context.WithValue(item.Req.Context(), "identifier", q.identifier) 297 | if ret404 { 298 | return404webhook(item) 299 | continue 300 | } 301 | 302 | if atomic.LoadInt64(q.isTokenInvalid) > 0 { 303 | return401(item) 304 | continue 305 | } 306 | 307 | resp, err := q.processor(ctx, item) 308 | if err != nil { 309 | item.errChan <- err 310 | continue 311 | } 312 | 313 | scope := resp.Header.Get("x-ratelimit-scope") 314 | 315 | _, remaining, resetAfter, isGlobal, err := parseHeaders(&resp.Header, scope != "user") 316 | 317 | if isGlobal { 318 | //Lock global 319 | sw := atomic.CompareAndSwapInt64(q.globalLockedUntil, 0, time.Now().Add(resetAfter).UnixNano()) 320 | if sw { 321 | logger.WithFields(logrus.Fields{ 322 | "until": time.Now().Add(resetAfter), 323 | "resetAfter": resetAfter, 324 | }).Warn("Global reached, locking") 325 | } 326 | } 327 | 328 | if err != nil { 329 | item.errChan <- err 330 | continue 331 | } 332 | item.doneChan <- resp 333 | 334 | if resp.StatusCode == 429 && scope != "shared" { 335 | logger.WithFields(logrus.Fields{ 336 | "prevRemaining": prevRem, 337 | "prevResetAfter": prevReset, 338 | "remaining": remaining, 339 | "resetAfter": resetAfter, 340 | "bucket": path, 341 | "route": item.Req.URL.String(), 342 | "method": item.Req.Method, 343 | "isGlobal": isGlobal, 344 | "pathHash": pathHash, 345 | // TODO: Remove this when 429s are not a problem anymore 346 | "discordBucket": resp.Header.Get("x-ratelimit-bucket"), 347 | "ratelimitScope": resp.Header.Get("x-ratelimit-scope"), 348 | }).Warn("Unexpected 429") 349 | } 350 | 351 | if resp.StatusCode == 404 && strings.HasPrefix(path, "/webhooks/") && !isInteraction(item.Req.URL.String()) { 352 | logger.WithFields(logrus.Fields{ 353 | "bucket": path, 354 | "route": item.Req.URL.String(), 355 | "method": item.Req.Method, 356 | }).Info("Setting fail fast 404 for webhook") 357 | ret404 = true 358 | } 359 | 360 | if resp.StatusCode == 401 && !isInteraction(item.Req.URL.String()) && q.queueType != NoAuth { 361 | // Permanently lock this queue 362 | logger.WithFields(logrus.Fields{ 363 | "bucket": path, 364 | "route": item.Req.URL.String(), 365 | "method": item.Req.Method, 366 | "identifier": q.identifier, 367 | "status": resp.StatusCode, 368 | }).Error("Received 401 during normal operation, assuming token is invalidated, locking bucket permanently") 369 | 370 | if EnvGet("DISABLE_401_LOCK", "false") != "true" { 371 | atomic.StoreInt64(q.isTokenInvalid, 999) 372 | } 373 | } 374 | 375 | // Prevent reaction bucket from being stuck 376 | if resp.StatusCode == 429 && scope == "shared" && (path == "/channels/!/messages/!/reactions/!modify" || path == "/channels/!/messages/!/reactions/!/!") { 377 | prevRem, prevReset = remaining, resetAfter 378 | continue 379 | } 380 | 381 | if remaining == 0 || resp.StatusCode == 429 { 382 | duration := time.Until(time.Now().Add(resetAfter)) 383 | time.Sleep(duration) 384 | } 385 | prevRem, prevReset = remaining, resetAfter 386 | } 387 | } 388 | -------------------------------------------------------------------------------- /lib/queue_manager.go: -------------------------------------------------------------------------------- 1 | package lib 2 | 3 | import ( 4 | "context" 5 | "errors" 6 | lru "github.com/hashicorp/golang-lru" 7 | "github.com/hashicorp/memberlist" 8 | "github.com/sirupsen/logrus" 9 | "net/http" 10 | "sort" 11 | "strconv" 12 | "strings" 13 | "sync" 14 | "time" 15 | ) 16 | 17 | type QueueType int64 18 | 19 | const ( 20 | Bot QueueType = iota 21 | NoAuth 22 | Bearer 23 | ) 24 | 25 | // Some routes that have @me on the path don't really spread out through the cluster, causing issues 26 | // and exacerbating tail latency hits from Discord. Only routes with no ratelimit headers should be put here 27 | var pathsToRouteLocally = map[uint64]struct{}{ 28 | HashCRC64("/users/@me/channels"): {}, 29 | HashCRC64("/users/@me"): {}, 30 | } 31 | 32 | type QueueManager struct { 33 | sync.RWMutex 34 | queues map[string]*RequestQueue 35 | bearerQueues *lru.Cache 36 | bearerMu sync.RWMutex 37 | bufferSize int 38 | cluster *memberlist.Memberlist 39 | clusterGlobalRateLimiter *ClusterGlobalRateLimiter 40 | orderedClusterMembers []string 41 | nameToAddressMap map[string]string 42 | localNodeName string 43 | localNodeIP string 44 | localNodeProxyListenAddr string 45 | } 46 | 47 | func onEvictLruItem(key interface{}, value interface{}) { 48 | go value.(*RequestQueue).destroy() 49 | } 50 | 51 | func NewQueueManager(bufferSize int, maxBearerLruSize int) *QueueManager { 52 | bearerMap, err := lru.NewWithEvict(maxBearerLruSize, onEvictLruItem) 53 | 54 | if err != nil { 55 | panic(err) 56 | } 57 | 58 | q := &QueueManager{ 59 | queues: make(map[string]*RequestQueue), 60 | bearerQueues: bearerMap, 61 | bufferSize: bufferSize, 62 | cluster: nil, 63 | clusterGlobalRateLimiter: NewClusterGlobalRateLimiter(), 64 | } 65 | 66 | return q 67 | } 68 | 69 | func (m *QueueManager) Shutdown() { 70 | if m.cluster != nil { 71 | m.cluster.Leave(30 * time.Second) 72 | } 73 | } 74 | 75 | func (m *QueueManager) reindexMembers() { 76 | if m.cluster == nil { 77 | logger.Warn("reindexMembers called but cluster is nil") 78 | return 79 | } 80 | 81 | m.Lock() 82 | defer m.Unlock() 83 | m.bearerMu.Lock() 84 | defer m.bearerMu.Unlock() 85 | 86 | members := m.cluster.Members() 87 | var orderedMembers []string 88 | nameToAddressMap := make(map[string]string) 89 | for _, m := range members { 90 | orderedMembers = append(orderedMembers, m.Name) 91 | nameToAddressMap[m.Name] = m.Addr.String() + ":" + string(m.Meta) 92 | } 93 | sort.Strings(orderedMembers) 94 | 95 | m.orderedClusterMembers = orderedMembers 96 | m.nameToAddressMap = nameToAddressMap 97 | } 98 | 99 | func (m *QueueManager) onNodeJoin(node *memberlist.Node) { 100 | // Running in goroutine prevents a deadlock inside memberlist 101 | go m.reindexMembers() 102 | } 103 | func (m *QueueManager) onNodeLeave(node *memberlist.Node) { 104 | // Running in goroutine prevents a deadlock inside memberlist 105 | go m.reindexMembers() 106 | } 107 | 108 | func (m *QueueManager) GetEventDelegate() *NirnEvents { 109 | return &NirnEvents{ 110 | OnJoin: m.onNodeJoin, 111 | OnLeave: m.onNodeLeave, 112 | } 113 | } 114 | 115 | func (m *QueueManager) SetCluster(cluster *memberlist.Memberlist, proxyPort string) { 116 | m.cluster = cluster 117 | m.localNodeName = cluster.LocalNode().Name 118 | m.localNodeIP = cluster.LocalNode().Addr.String() 119 | m.localNodeProxyListenAddr = m.localNodeIP + ":" + proxyPort 120 | m.reindexMembers() 121 | } 122 | 123 | func (m *QueueManager) calculateRoute(pathHash uint64) string { 124 | if m.cluster == nil { 125 | // Route to self, proxy in stand-alone mode 126 | return "" 127 | } 128 | 129 | if pathHash == 0 { 130 | return "" 131 | } 132 | 133 | if _, ok := pathsToRouteLocally[pathHash]; ok { 134 | return "" 135 | } 136 | 137 | m.RLock() 138 | defer m.RUnlock() 139 | m.bearerMu.RLock() 140 | defer m.bearerMu.RUnlock() 141 | 142 | members := m.orderedClusterMembers 143 | count := uint64(len(members)) 144 | 145 | if count == 0 { 146 | return "" 147 | } 148 | 149 | chosenIndex := pathHash % count 150 | addr := m.nameToAddressMap[members[chosenIndex]] 151 | if addr == m.localNodeProxyListenAddr { 152 | return "" 153 | } 154 | return addr 155 | } 156 | 157 | func (m *QueueManager) routeRequest(addr string, req *http.Request) (*http.Response, error) { 158 | nodeReq, err := http.NewRequestWithContext(req.Context(), req.Method, "http://"+addr+req.URL.Path+"?"+req.URL.RawQuery, req.Body) 159 | nodeReq.Header = req.Header.Clone() 160 | nodeReq.Header.Set("nirn-routed-to", addr) 161 | if err != nil { 162 | return nil, err 163 | } 164 | 165 | logger.WithFields(logrus.Fields{ 166 | "to": addr, 167 | "path": req.URL.Path, 168 | "method": req.Method, 169 | }).Trace("Routing request to node in cluster") 170 | resp, err := client.Do(nodeReq) 171 | logger.WithFields(logrus.Fields{ 172 | "to": addr, 173 | "path": req.URL.Path, 174 | "method": req.Method, 175 | }).Trace("Received response from node") 176 | if err == nil { 177 | RequestsRoutedSent.Inc() 178 | } else { 179 | RequestsRoutedError.Inc() 180 | } 181 | 182 | return resp, err 183 | } 184 | 185 | func Generate429(resp *http.ResponseWriter) { 186 | writer := *resp 187 | writer.Header().Set("generated-by-proxy", "true") 188 | writer.Header().Set("x-ratelimit-scope", "user") 189 | writer.Header().Set("x-ratelimit-limit", "1") 190 | writer.Header().Set("x-ratelimit-remaining", "0") 191 | writer.Header().Set("x-ratelimit-reset", strconv.FormatInt(time.Now().Add(1*time.Second).Unix(), 10)) 192 | writer.Header().Set("x-ratelimit-after", "1") 193 | writer.Header().Set("retry-after", "1") 194 | writer.Header().Set("content-type", "application/json") 195 | writer.WriteHeader(429) 196 | writer.Write([]byte("{\n\t\"global\": false,\n\t\"message\": \"You are being rate limited.\",\n\t\"retry_after\": 1\n}")) 197 | } 198 | 199 | func (m *QueueManager) getOrCreateBotQueue(token string) (*RequestQueue, error) { 200 | m.RLock() 201 | q, ok := m.queues[token] 202 | m.RUnlock() 203 | 204 | if !ok { 205 | m.Lock() 206 | defer m.Unlock() 207 | // Check if it wasn't created while we didn't hold the lock 208 | q, ok = m.queues[token] 209 | if !ok { 210 | var err error 211 | q, err = NewRequestQueue(ProcessRequest, token, m.bufferSize) 212 | 213 | if err != nil { 214 | return nil, err 215 | } 216 | 217 | m.queues[token] = q 218 | } 219 | } 220 | 221 | return q, nil 222 | } 223 | 224 | func (m *QueueManager) getOrCreateBearerQueue(token string) (*RequestQueue, error) { 225 | m.bearerMu.RLock() 226 | q, ok := m.bearerQueues.Get(token) 227 | m.bearerMu.RUnlock() 228 | 229 | if !ok { 230 | m.bearerMu.Lock() 231 | defer m.bearerMu.Unlock() 232 | // Check if it wasn't created while we didn't hold the lock 233 | q, ok = m.bearerQueues.Get(token) 234 | if !ok { 235 | var err error 236 | q, err = NewRequestQueue(ProcessRequest, token, 5) 237 | 238 | if err != nil { 239 | return nil, err 240 | } 241 | 242 | m.bearerQueues.Add(token, q) 243 | } 244 | } 245 | 246 | return q.(*RequestQueue), nil 247 | } 248 | 249 | func (m *QueueManager) DiscordRequestHandler(resp http.ResponseWriter, req *http.Request) { 250 | reqStart := time.Now() 251 | metricsPath := GetMetricsPath(req.URL.Path) 252 | ConnectionsOpen.With(map[string]string{"route": metricsPath, "method": req.Method}).Inc() 253 | defer ConnectionsOpen.With(map[string]string{"route": metricsPath, "method": req.Method}).Dec() 254 | 255 | token := req.Header.Get("Authorization") 256 | routingHash, path, queueType := m.GetRequestRoutingInfo(req, token) 257 | 258 | m.fulfillRequest(&resp, req, queueType, path, routingHash, token, reqStart) 259 | } 260 | 261 | func (m *QueueManager) GetRequestRoutingInfo(req *http.Request, token string) (routingHash uint64, path string, queueType QueueType) { 262 | path = GetOptimisticBucketPath(req.URL.Path, req.Method) 263 | queueType = NoAuth 264 | if strings.HasPrefix(token, "Bearer") { 265 | queueType = Bearer 266 | routingHash = HashCRC64(token) 267 | } else { 268 | queueType = Bot 269 | routingHash = HashCRC64(path) 270 | } 271 | return 272 | } 273 | 274 | func (m *QueueManager) fulfillRequest(resp *http.ResponseWriter, req *http.Request, queueType QueueType, path string, pathHash uint64, token string, reqStart time.Time) { 275 | logEntry := logger.WithField("clientIp", req.RemoteAddr) 276 | forwdFor := req.Header.Get("X-Forwarded-For") 277 | if forwdFor != "" { 278 | logEntry = logEntry.WithField("forwardedFor", forwdFor) 279 | } 280 | routeTo := m.calculateRoute(pathHash) 281 | 282 | routeToHeader := req.Header.Get("nirn-routed-to") 283 | req.Header.Del("nirn-routed-to") 284 | 285 | if routeToHeader != "" { 286 | RequestsRoutedRecv.Inc() 287 | } 288 | 289 | var err error 290 | if routeTo == "" || routeToHeader != "" { 291 | var q *RequestQueue 292 | var err error 293 | if queueType == Bearer { 294 | q, err = m.getOrCreateBearerQueue(token) 295 | } else { 296 | q, err = m.getOrCreateBotQueue(token) 297 | } 298 | 299 | if err != nil { 300 | if strings.HasPrefix(err.Error(), "429") { 301 | Generate429(resp) 302 | logEntry.WithFields(logrus.Fields{"function": "getOrCreateQueue", "queueType": queueType}).Warn(err) 303 | } else { 304 | (*resp).WriteHeader(500) 305 | (*resp).Write([]byte(err.Error())) 306 | ErrorCounter.Inc() 307 | logEntry.WithFields(logrus.Fields{"function": "getOrCreateQueue", "queueType": queueType}).Error(err) 308 | } 309 | return 310 | } 311 | 312 | if q.identifier != "NoAuth" { 313 | var botHash uint64 = 0 314 | if q.user != nil { 315 | botHash = HashCRC64(q.user.Id) 316 | } 317 | 318 | botLimit := q.botLimit 319 | globalRouteTo := m.calculateRoute(botHash) 320 | 321 | if globalRouteTo == "" || queueType == Bearer { 322 | m.clusterGlobalRateLimiter.Take(botHash, botLimit) 323 | } else { 324 | err = m.clusterGlobalRateLimiter.FireGlobalRequest(req.Context(), globalRouteTo, botHash, botLimit) 325 | if err != nil { 326 | logEntry.WithField("function", "FireGlobalRequest").Error(err) 327 | ErrorCounter.Inc() 328 | Generate429(resp) 329 | return 330 | } 331 | } 332 | } 333 | err = q.Queue(req, resp, path, pathHash) 334 | if err != nil { 335 | log := logEntry.WithField("function", "Queue") 336 | if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) { 337 | log.WithField("waitedFor", time.Since(reqStart)).Warn(err) 338 | } else { 339 | log.Error(err) 340 | } 341 | } 342 | } else { 343 | var res *http.Response 344 | res, err = m.routeRequest(routeTo, req) 345 | if err == nil { 346 | err = CopyResponseToResponseWriter(res, resp) 347 | if err != nil { 348 | logEntry.WithField("function", "CopyResponseToResponseWriter").Error(err) 349 | } 350 | } else { 351 | logEntry = logEntry.WithField("function", "routeRequest") 352 | if !errors.Is(err, context.Canceled) { 353 | logEntry.Error(err) 354 | } else { 355 | logEntry.Warn(err) 356 | } 357 | // if it's a context canceled on the client it won't get the 429 anyway, if it's within the cluster we should retry 358 | Generate429(resp) 359 | } 360 | } 361 | } 362 | 363 | func (m *QueueManager) HandleGlobal(w http.ResponseWriter, r *http.Request) { 364 | botHashStr := r.Header.Get("bot-hash") 365 | botLimitStr := r.Header.Get("bot-limit") 366 | 367 | botHash, err := strconv.ParseUint(botHashStr, 10, 64) 368 | if err != nil { 369 | w.WriteHeader(400) 370 | return 371 | } 372 | 373 | botLimit, err := strconv.ParseUint(botLimitStr, 10, 64) 374 | if err != nil { 375 | w.WriteHeader(400) 376 | return 377 | } 378 | 379 | m.clusterGlobalRateLimiter.Take(botHash, uint(botLimit)) 380 | logger.Trace("Returned OK for global request") 381 | } 382 | 383 | func (m *QueueManager) CreateMux() *http.ServeMux { 384 | mux := http.NewServeMux() 385 | mux.HandleFunc("/", m.DiscordRequestHandler) 386 | mux.HandleFunc("/nirn/global", m.HandleGlobal) 387 | mux.HandleFunc("/nirn/healthz", func(writer http.ResponseWriter, request *http.Request) { 388 | writer.WriteHeader(200) 389 | }) 390 | return mux 391 | } 392 | -------------------------------------------------------------------------------- /lib/util.go: -------------------------------------------------------------------------------- 1 | package lib 2 | 3 | import ( 4 | "encoding/base64" 5 | "hash/crc64" 6 | "strconv" 7 | "strings" 8 | "time" 9 | ) 10 | 11 | var table = crc64.MakeTable(crc64.ISO) 12 | 13 | func HashCRC64(data string) uint64 { 14 | h := crc64.New(table) 15 | h.Write([]byte(data)) 16 | return h.Sum64() 17 | } 18 | 19 | const EpochDiscord = 1420070400000 20 | 21 | func GetSnowflakeCreatedAt(snowflake string) (time.Time, error) { 22 | parsedId, err := strconv.ParseUint(snowflake, 10, 64) 23 | if err != nil { 24 | return time.Now(), err 25 | } 26 | epoch := (parsedId >> uint64(22)) + EpochDiscord 27 | return time.Unix(int64(epoch)/1000, 0), nil 28 | } 29 | 30 | func GetBotId(token string) string { 31 | var clientId string 32 | if token == "" { 33 | clientId = "NoAuth" 34 | } else { 35 | token = strings.ReplaceAll(token, "Bot ", "") 36 | token = strings.ReplaceAll(token, "Bearer ", "") 37 | token = strings.Split(token, ".")[0] 38 | token, err := base64.StdEncoding.DecodeString(token) 39 | if err != nil { 40 | clientId = "Unknown" 41 | } else { 42 | clientId = string(token) 43 | } 44 | } 45 | return clientId 46 | } -------------------------------------------------------------------------------- /lib/util_test.go: -------------------------------------------------------------------------------- 1 | package lib 2 | 3 | import ( 4 | "strconv" 5 | "testing" 6 | ) 7 | 8 | const knownData = "test data" 9 | // Calculated using ISO table 10 | const knownHash = 10232006911339297906 11 | 12 | func TestHashWorks(t *testing.T) { 13 | HashCRC64(knownData) 14 | } 15 | 16 | //Test for correctness 17 | func TestHashIsConsistent(t *testing.T) { 18 | ret := HashCRC64(knownData) 19 | if ret != knownHash { 20 | t.Errorf("Invalid hash returned") 21 | } 22 | } 23 | 24 | //Test for consistency when function is used for other data 25 | func TestHashIsConsistentAcrossMultipleRuns(t *testing.T) { 26 | for i := 0; i < 50000; i++ { 27 | HashCRC64(strconv.Itoa(i)) 28 | } 29 | 30 | ret := HashCRC64(knownData) 31 | if ret != knownHash { 32 | t.Errorf("Invalid hash returned") 33 | } 34 | } 35 | 36 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "github.com/germanoeich/nirn-proxy/lib" 6 | "github.com/hashicorp/memberlist" 7 | _ "github.com/joho/godotenv/autoload" 8 | "github.com/sirupsen/logrus" 9 | "net" 10 | "net/http" 11 | "os" 12 | "os/signal" 13 | "strings" 14 | "syscall" 15 | "time" 16 | ) 17 | 18 | var logger = logrus.New() 19 | 20 | // token : queue map 21 | var bufferSize = 50 22 | 23 | func setupLogger() { 24 | logLevel := lib.EnvGet("LOG_LEVEL", "info") 25 | lvl, err := logrus.ParseLevel(logLevel) 26 | 27 | if err != nil { 28 | panic("Failed to parse log level") 29 | } 30 | 31 | logger.SetLevel(lvl) 32 | lib.SetLogger(logger) 33 | } 34 | 35 | func initCluster(proxyPort string, manager *lib.QueueManager) *memberlist.Memberlist { 36 | port := lib.EnvGetInt("CLUSTER_PORT", 7946) 37 | 38 | memberEnv := os.Getenv("CLUSTER_MEMBERS") 39 | dns := os.Getenv("CLUSTER_DNS") 40 | 41 | if memberEnv == "" && dns == "" { 42 | logger.Info("Running in stand-alone mode") 43 | return nil 44 | } 45 | 46 | logger.Info("Attempting to create/join cluster") 47 | var members []string 48 | if memberEnv != "" { 49 | members = strings.Split(memberEnv, ",") 50 | } else { 51 | ips, err := net.LookupIP(dns) 52 | if err != nil { 53 | logger.Panic(err) 54 | } 55 | 56 | if len(ips) == 0 { 57 | logger.Panic("no ips returned by dns") 58 | } 59 | 60 | for _, ip := range ips { 61 | members = append(members, ip.String()) 62 | } 63 | } 64 | 65 | return lib.InitMemberList(members, port, proxyPort, manager) 66 | } 67 | 68 | func main() { 69 | outboundIp := os.Getenv("OUTBOUND_IP") 70 | 71 | timeout := lib.EnvGetInt("REQUEST_TIMEOUT", 5000) 72 | 73 | disableHttp2 := lib.EnvGetBool("DISABLE_HTTP_2", true) 74 | 75 | globalOverrides := lib.EnvGet("BOT_RATELIMIT_OVERRIDES", "") 76 | 77 | disableGlobalRatelimitDetection := lib.EnvGetBool("DISABLE_GLOBAL_RATELIMIT_DETECTION", false) 78 | 79 | lib.ConfigureDiscordHTTPClient(outboundIp, time.Duration(timeout)*time.Millisecond, disableHttp2, globalOverrides, disableGlobalRatelimitDetection) 80 | 81 | port := lib.EnvGet("PORT", "8080") 82 | bindIp := lib.EnvGet("BIND_IP", "0.0.0.0") 83 | 84 | setupLogger() 85 | 86 | bufferSize = lib.EnvGetInt("BUFFER_SIZE", 50) 87 | maxBearerLruSize := lib.EnvGetInt("MAX_BEARER_COUNT", 1024) 88 | 89 | manager := lib.NewQueueManager(bufferSize, maxBearerLruSize) 90 | 91 | mux := manager.CreateMux() 92 | 93 | s := &http.Server{ 94 | Addr: bindIp + ":" + port, 95 | Handler: mux, 96 | ReadHeaderTimeout: 10 * time.Second, 97 | IdleTimeout: 10 * time.Second, 98 | WriteTimeout: 1 * time.Hour, 99 | MaxHeaderBytes: 1 << 20, 100 | } 101 | 102 | if os.Getenv("ENABLE_PPROF") == "true" { 103 | go lib.StartProfileServer() 104 | } 105 | 106 | if os.Getenv("ENABLE_METRICS") != "false" { 107 | port := lib.EnvGet("METRICS_PORT", "9000") 108 | go lib.StartMetrics(bindIp + ":" + port) 109 | } 110 | 111 | done := make(chan os.Signal, 1) 112 | signal.Notify(done, os.Interrupt, syscall.SIGINT, syscall.SIGTERM) 113 | 114 | go func() { 115 | if err := s.ListenAndServe(); err != nil && err != http.ErrServerClosed { 116 | logger.WithFields(logrus.Fields{"function": "http.ListenAndServe"}).Panic(err) 117 | } 118 | }() 119 | 120 | logger.Info("Started proxy on " + bindIp + ":" + port) 121 | 122 | // Wait for the http server to ready before joining the cluster 123 | <-time.After(1 * time.Second) 124 | initCluster(port, manager) 125 | 126 | <-done 127 | logger.Info("Server received shutdown signal") 128 | 129 | logger.Info("Broadcasting leave message to cluster, if in cluster mode") 130 | manager.Shutdown() 131 | 132 | logger.Info("Gracefully shutting down HTTP server") 133 | 134 | ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) 135 | defer cancel() 136 | 137 | if err := s.Shutdown(ctx); err != nil { 138 | logger.WithFields(logrus.Fields{"function": "http.Shutdown"}).Error(err) 139 | } 140 | 141 | logger.Info("Bye bye") 142 | } 143 | --------------------------------------------------------------------------------