From bbca0cc048a1ca4bcde464b77195b14f07bf27d7 Mon Sep 17 00:00:00 2001 From: Andrew Svoboda Date: Mon, 24 Jun 2019 09:41:07 +0100 Subject: [PATCH] Use built in client http caching (#129) * Use built in client http caching * Use LRU cache implementation; set some defaults and config * Use human readable cache sizes --- .gitignore | 1 + Gopkg.lock | 31 +- config/bulldozer.example.yml | 5 + server/config.go | 6 + server/server.go | 9 + vendor/github.com/c2h5oh/datasize/LICENSE | 21 + vendor/github.com/c2h5oh/datasize/datasize.go | 217 +++++++ vendor/github.com/die-net/lrucache/LICENSE | 201 +++++++ .../github.com/die-net/lrucache/lrucache.go | 146 +++++ .../gregjones/httpcache/LICENSE.txt | 7 + .../gregjones/httpcache/httpcache.go | 551 ++++++++++++++++++ .../go-githubapp/githubapp/client_creator.go | 190 +++++- .../go-githubapp/githubapp/middleware.go | 35 ++ 13 files changed, 1387 insertions(+), 33 deletions(-) create mode 100644 vendor/github.com/c2h5oh/datasize/LICENSE create mode 100644 vendor/github.com/c2h5oh/datasize/datasize.go create mode 100644 vendor/github.com/die-net/lrucache/LICENSE create mode 100644 vendor/github.com/die-net/lrucache/lrucache.go create mode 100644 vendor/github.com/gregjones/httpcache/LICENSE.txt create mode 100644 vendor/github.com/gregjones/httpcache/httpcache.go diff --git a/.gitignore b/.gitignore index 3389d4572..a892d6ee2 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,4 @@ *.iws build/ +config/bulldozer.yml diff --git a/Gopkg.lock b/Gopkg.lock index 20b79a5d0..536c0367a 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -25,6 +25,14 @@ revision = "3f4e9b1898e6b65e31827d5dccb97d91d59feaa3" version = "v0.1.2" +[[projects]] + branch = "master" + digest = "1:2755397479777565ae0c383f63be30e8975da63805281283bdde46d73bed9a7d" + name = "github.com/c2h5oh/datasize" + packages = ["."] + pruneopts = "NUT" + revision = "4eba002a5eaea69cf8d235a388fc6b65ae68d2dd" + [[projects]] digest = "1:ffe9824d294da03b391f44e1ae8281281b4afc1bdaa9588c9097785e3af10cec" name = "github.com/davecgh/go-spew" @@ -41,6 +49,14 @@ revision = "06ea1031745cb8b3dab3f6a236daf2b0aa468b7e" version = "v3.2.0" +[[projects]] + branch = "master" + digest = "1:ea77235a4b2c30ec49399bc8376fcb9ceab8b7726b7426e845fc651ae56af5f5" + name = "github.com/die-net/lrucache" + packages = ["."] + pruneopts = "NUT" + revision = "19a39ef22a11a471b23c3beb9cb39903f6cff332" + [[projects]] digest = "1:b4303d38d92c00af6603f3b865a9bd20e3c50cebe55489e5aeb721c26750e375" name = "github.com/google/go-github" @@ -57,6 +73,14 @@ revision = "44c6ddd0a2342c386950e880b658017258da92fc" version = "v1.0.0" +[[projects]] + branch = "master" + digest = "1:a2b4fa8b538f6e42d0f38cbdef92e771072d7a64a97ff1512da95554ab2680a1" + name = "github.com/gregjones/httpcache" + packages = ["."] + pruneopts = "NUT" + revision = "901d90724c7919163f472a9812253fb26761123d" + [[projects]] digest = "1:52094d0f8bdf831d1a2401e9b6fee5795fdc0b2a2d1f8bb1980834c289e79129" name = "github.com/hashicorp/golang-lru" @@ -90,11 +114,11 @@ [[projects]] branch = "develop" - digest = "1:630fd596c926c094f1bd904cefb5a80497e169df35635356239ad709f76f2af9" + digest = "1:a48a15781028337572d7fae6818d362623ece5ce697e4b576b6ba671a867f151" name = "github.com/palantir/go-githubapp" packages = ["githubapp"] pruneopts = "NUT" - revision = "a3a32b23c2f767a61fccfcf51f334cb66c3f37ac" + revision = "18a0cc3dee67ff3fec3e0926e40ff1bfb76f189b" [[projects]] digest = "1:14715f705ff5dfe0ffd6571d7d201dd8e921030f8070321a79380d8ca4ec1a24" @@ -241,7 +265,10 @@ analyzer-name = "dep" analyzer-version = 1 input-imports = [ + "github.com/c2h5oh/datasize", + "github.com/die-net/lrucache", "github.com/google/go-github/github", + "github.com/gregjones/httpcache", "github.com/palantir/go-baseapp/baseapp", "github.com/palantir/go-baseapp/baseapp/datadog", "github.com/palantir/go-baseapp/pkg/errfmt", diff --git a/config/bulldozer.example.yml b/config/bulldozer.example.yml index 0769e88b7..1c1d5bbd6 100644 --- a/config/bulldozer.example.yml +++ b/config/bulldozer.example.yml @@ -14,6 +14,11 @@ logging: # Choose from: debug, info, warn, error level: debug +# Options for the HTTP Cache +cache: + # The maximum size of the cache (specified in human readable units) + max_size: 50 MB + # Options for connecting to GitHub github: # The URL of the GitHub homepage diff --git a/server/config.go b/server/config.go index d6274dbc5..b76fddc6f 100644 --- a/server/config.go +++ b/server/config.go @@ -15,6 +15,7 @@ package server import ( + "github.com/c2h5oh/datasize" "github.com/palantir/go-baseapp/baseapp" "github.com/palantir/go-baseapp/baseapp/datadog" "github.com/palantir/go-githubapp/githubapp" @@ -35,6 +36,7 @@ type Config struct { Options Options `yaml:"options"` Logging LoggingConfig `yaml:"logging"` Datadog datadog.Config `yaml:"datadog"` + Cache CacheConfig `yaml:"cache"` } type LoggingConfig struct { @@ -42,6 +44,10 @@ type LoggingConfig struct { Text bool `yaml:"text"` } +type CacheConfig struct { + MaxSize datasize.ByteSize `yaml:"max_size"` +} + type Options struct { AppName string `yaml:"app_name"` ConfigurationPath string `yaml:"configuration_path"` diff --git a/server/server.go b/server/server.go index 2226f636b..2f5f9a5b2 100644 --- a/server/server.go +++ b/server/server.go @@ -17,6 +17,9 @@ package server import ( "fmt" + "github.com/c2h5oh/datasize" + "github.com/die-net/lrucache" + "github.com/gregjones/httpcache" "github.com/palantir/go-baseapp/baseapp" "github.com/palantir/go-baseapp/baseapp/datadog" "github.com/palantir/go-githubapp/githubapp" @@ -48,10 +51,16 @@ func New(c *Config) (*Server, error) { return nil, errors.Wrap(err, "failed to initialize base server") } + maxSize := int64(50 * datasize.MB) + if c.Cache.MaxSize != 0 { + maxSize = int64(c.Cache.MaxSize) + } + userAgent := fmt.Sprintf("%s/%s", c.Options.AppName, version.GetVersion()) clientCreator, err := githubapp.NewDefaultCachingClientCreator( c.Github, githubapp.WithClientUserAgent(userAgent), + githubapp.WithClientCaching(true, func() httpcache.Cache { return lrucache.New(maxSize, 0) }), githubapp.WithClientMiddleware( githubapp.ClientLogging(zerolog.DebugLevel), githubapp.ClientMetrics(base.Registry()), diff --git a/vendor/github.com/c2h5oh/datasize/LICENSE b/vendor/github.com/c2h5oh/datasize/LICENSE new file mode 100644 index 000000000..f2ba916e6 --- /dev/null +++ b/vendor/github.com/c2h5oh/datasize/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Maciej Lisiewski + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/c2h5oh/datasize/datasize.go b/vendor/github.com/c2h5oh/datasize/datasize.go new file mode 100644 index 000000000..675478816 --- /dev/null +++ b/vendor/github.com/c2h5oh/datasize/datasize.go @@ -0,0 +1,217 @@ +package datasize + +import ( + "errors" + "fmt" + "strconv" + "strings" +) + +type ByteSize uint64 + +const ( + B ByteSize = 1 + KB = B << 10 + MB = KB << 10 + GB = MB << 10 + TB = GB << 10 + PB = TB << 10 + EB = PB << 10 + + fnUnmarshalText string = "UnmarshalText" + maxUint64 uint64 = (1 << 64) - 1 + cutoff uint64 = maxUint64 / 10 +) + +var ErrBits = errors.New("unit with capital unit prefix and lower case unit (b) - bits, not bytes ") + +func (b ByteSize) Bytes() uint64 { + return uint64(b) +} + +func (b ByteSize) KBytes() float64 { + v := b / KB + r := b % KB + return float64(v) + float64(r)/float64(KB) +} + +func (b ByteSize) MBytes() float64 { + v := b / MB + r := b % MB + return float64(v) + float64(r)/float64(MB) +} + +func (b ByteSize) GBytes() float64 { + v := b / GB + r := b % GB + return float64(v) + float64(r)/float64(GB) +} + +func (b ByteSize) TBytes() float64 { + v := b / TB + r := b % TB + return float64(v) + float64(r)/float64(TB) +} + +func (b ByteSize) PBytes() float64 { + v := b / PB + r := b % PB + return float64(v) + float64(r)/float64(PB) +} + +func (b ByteSize) EBytes() float64 { + v := b / EB + r := b % EB + return float64(v) + float64(r)/float64(EB) +} + +func (b ByteSize) String() string { + switch { + case b == 0: + return fmt.Sprint("0B") + case b%EB == 0: + return fmt.Sprintf("%dEB", b/EB) + case b%PB == 0: + return fmt.Sprintf("%dPB", b/PB) + case b%TB == 0: + return fmt.Sprintf("%dTB", b/TB) + case b%GB == 0: + return fmt.Sprintf("%dGB", b/GB) + case b%MB == 0: + return fmt.Sprintf("%dMB", b/MB) + case b%KB == 0: + return fmt.Sprintf("%dKB", b/KB) + default: + return fmt.Sprintf("%dB", b) + } +} + +func (b ByteSize) HR() string { + return b.HumanReadable() +} + +func (b ByteSize) HumanReadable() string { + switch { + case b > EB: + return fmt.Sprintf("%.1f EB", b.EBytes()) + case b > PB: + return fmt.Sprintf("%.1f PB", b.PBytes()) + case b > TB: + return fmt.Sprintf("%.1f TB", b.TBytes()) + case b > GB: + return fmt.Sprintf("%.1f GB", b.GBytes()) + case b > MB: + return fmt.Sprintf("%.1f MB", b.MBytes()) + case b > KB: + return fmt.Sprintf("%.1f KB", b.KBytes()) + default: + return fmt.Sprintf("%d B", b) + } +} + +func (b ByteSize) MarshalText() ([]byte, error) { + return []byte(b.String()), nil +} + +func (b *ByteSize) UnmarshalText(t []byte) error { + var val uint64 + var unit string + + // copy for error message + t0 := t + + var c byte + var i int + +ParseLoop: + for i < len(t) { + c = t[i] + switch { + case '0' <= c && c <= '9': + if val > cutoff { + goto Overflow + } + + c = c - '0' + val *= 10 + + if val > val+uint64(c) { + // val+v overflows + goto Overflow + } + val += uint64(c) + i++ + + default: + if i == 0 { + goto SyntaxError + } + break ParseLoop + } + } + + unit = strings.TrimSpace(string(t[i:])) + switch unit { + case "Kb", "Mb", "Gb", "Tb", "Pb", "Eb": + goto BitsError + } + unit = strings.ToLower(unit) + switch unit { + case "", "b", "byte": + // do nothing - already in bytes + + case "k", "kb", "kilo", "kilobyte", "kilobytes": + if val > maxUint64/uint64(KB) { + goto Overflow + } + val *= uint64(KB) + + case "m", "mb", "mega", "megabyte", "megabytes": + if val > maxUint64/uint64(MB) { + goto Overflow + } + val *= uint64(MB) + + case "g", "gb", "giga", "gigabyte", "gigabytes": + if val > maxUint64/uint64(GB) { + goto Overflow + } + val *= uint64(GB) + + case "t", "tb", "tera", "terabyte", "terabytes": + if val > maxUint64/uint64(TB) { + goto Overflow + } + val *= uint64(TB) + + case "p", "pb", "peta", "petabyte", "petabytes": + if val > maxUint64/uint64(PB) { + goto Overflow + } + val *= uint64(PB) + + case "E", "EB", "e", "eb", "eB": + if val > maxUint64/uint64(EB) { + goto Overflow + } + val *= uint64(EB) + + default: + goto SyntaxError + } + + *b = ByteSize(val) + return nil + +Overflow: + *b = ByteSize(maxUint64) + return &strconv.NumError{fnUnmarshalText, string(t0), strconv.ErrRange} + +SyntaxError: + *b = 0 + return &strconv.NumError{fnUnmarshalText, string(t0), strconv.ErrSyntax} + +BitsError: + *b = 0 + return &strconv.NumError{fnUnmarshalText, string(t0), ErrBits} +} diff --git a/vendor/github.com/die-net/lrucache/LICENSE b/vendor/github.com/die-net/lrucache/LICENSE new file mode 100644 index 000000000..8dada3eda --- /dev/null +++ b/vendor/github.com/die-net/lrucache/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/die-net/lrucache/lrucache.go b/vendor/github.com/die-net/lrucache/lrucache.go new file mode 100644 index 000000000..65074885d --- /dev/null +++ b/vendor/github.com/die-net/lrucache/lrucache.go @@ -0,0 +1,146 @@ +// Package lrucache provides a byte-size-limited implementation of +// httpcache.Cache that stores data in memory. +package lrucache + +import ( + "container/list" + "sync" + "time" +) + +// LruCache is a thread-safe, in-memory httpcache.Cache that evicts the +// least recently used entries from memory when either MaxSize (in bytes) +// limit would be exceeded or (if set) the entries are older than MaxAge (in +// seconds). Use the New constructor to create one. +type LruCache struct { + MaxSize int64 + MaxAge int64 + + mu sync.Mutex + cache map[string]*list.Element + lru *list.List // Front is least-recent + size int64 +} + +// New creates an LruCache that will restrict itself to maxSize bytes of +// memory. If maxAge > 0, entries will also be expired after maxAge +// seconds. +func New(maxSize, maxAge int64) *LruCache { + c := &LruCache{ + MaxSize: maxSize, + MaxAge: maxAge, + lru: list.New(), + cache: make(map[string]*list.Element), + } + + return c +} + +// Get returns the []byte representation of a cached response and a bool +// set to true if the key was found. +func (c *LruCache) Get(key string) ([]byte, bool) { + c.mu.Lock() + + le, ok := c.cache[key] + if !ok { + c.mu.Unlock() // Avoiding defer overhead + return nil, false + } + + if c.MaxAge > 0 && le.Value.(*entry).expires <= time.Now().Unix() { + c.deleteElement(le) + c.maybeDeleteOldest() + + c.mu.Unlock() // Avoiding defer overhead + return nil, false + } + + c.lru.MoveToBack(le) + value := le.Value.(*entry).value + + c.mu.Unlock() // Avoiding defer overhead + return value, true +} + +// Set stores the []byte representation of a response for a given key. +func (c *LruCache) Set(key string, value []byte) { + c.mu.Lock() + + expires := int64(0) + if c.MaxAge > 0 { + expires = time.Now().Unix() + c.MaxAge + } + + if le, ok := c.cache[key]; ok { + c.lru.MoveToBack(le) + e := le.Value.(*entry) + c.size += int64(len(value)) - int64(len(e.value)) + e.value = value + e.expires = expires + } else { + e := &entry{key: key, value: value, expires: expires} + c.cache[key] = c.lru.PushBack(e) + c.size += e.size() + } + + c.maybeDeleteOldest() + + c.mu.Unlock() +} + +// Delete removes the value associated with a key. +func (c *LruCache) Delete(key string) { + c.mu.Lock() + + if le, ok := c.cache[key]; ok { + c.deleteElement(le) + } + + c.mu.Unlock() +} + +// Size returns the estimated current memory usage of LruCache. +func (c *LruCache) Size() int64 { + c.mu.Lock() + size := c.size + c.mu.Unlock() + + return size +} + +func (c *LruCache) maybeDeleteOldest() { + for c.size > c.MaxSize { + le := c.lru.Front() + if le == nil { + panic("LruCache: non-zero size but empty lru") + } + c.deleteElement(le) + } + + if c.MaxAge > 0 { + now := time.Now().Unix() + for le := c.lru.Front(); le != nil && le.Value.(*entry).expires <= now; le = c.lru.Front() { + c.deleteElement(le) + } + } +} + +func (c *LruCache) deleteElement(le *list.Element) { + c.lru.Remove(le) + e := le.Value.(*entry) + delete(c.cache, e.key) + c.size -= e.size() +} + +// Rough estimate of map + entry object + string + byte slice overheads in bytes. +const entryOverhead = 168 + +type entry struct { + key string + value []byte + expires int64 +} + +func (e *entry) size() int64 { + return entryOverhead + int64(len(e.key)) + int64(len(e.value)) +} diff --git a/vendor/github.com/gregjones/httpcache/LICENSE.txt b/vendor/github.com/gregjones/httpcache/LICENSE.txt new file mode 100644 index 000000000..81316beb0 --- /dev/null +++ b/vendor/github.com/gregjones/httpcache/LICENSE.txt @@ -0,0 +1,7 @@ +Copyright © 2012 Greg Jones (greg.jones@gmail.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/vendor/github.com/gregjones/httpcache/httpcache.go b/vendor/github.com/gregjones/httpcache/httpcache.go new file mode 100644 index 000000000..b41a63d1f --- /dev/null +++ b/vendor/github.com/gregjones/httpcache/httpcache.go @@ -0,0 +1,551 @@ +// Package httpcache provides a http.RoundTripper implementation that works as a +// mostly RFC-compliant cache for http responses. +// +// It is only suitable for use as a 'private' cache (i.e. for a web-browser or an API-client +// and not for a shared proxy). +// +package httpcache + +import ( + "bufio" + "bytes" + "errors" + "io" + "io/ioutil" + "net/http" + "net/http/httputil" + "strings" + "sync" + "time" +) + +const ( + stale = iota + fresh + transparent + // XFromCache is the header added to responses that are returned from the cache + XFromCache = "X-From-Cache" +) + +// A Cache interface is used by the Transport to store and retrieve responses. +type Cache interface { + // Get returns the []byte representation of a cached response and a bool + // set to true if the value isn't empty + Get(key string) (responseBytes []byte, ok bool) + // Set stores the []byte representation of a response against a key + Set(key string, responseBytes []byte) + // Delete removes the value associated with the key + Delete(key string) +} + +// cacheKey returns the cache key for req. +func cacheKey(req *http.Request) string { + if req.Method == http.MethodGet { + return req.URL.String() + } else { + return req.Method + " " + req.URL.String() + } +} + +// CachedResponse returns the cached http.Response for req if present, and nil +// otherwise. +func CachedResponse(c Cache, req *http.Request) (resp *http.Response, err error) { + cachedVal, ok := c.Get(cacheKey(req)) + if !ok { + return + } + + b := bytes.NewBuffer(cachedVal) + return http.ReadResponse(bufio.NewReader(b), req) +} + +// MemoryCache is an implemtation of Cache that stores responses in an in-memory map. +type MemoryCache struct { + mu sync.RWMutex + items map[string][]byte +} + +// Get returns the []byte representation of the response and true if present, false if not +func (c *MemoryCache) Get(key string) (resp []byte, ok bool) { + c.mu.RLock() + resp, ok = c.items[key] + c.mu.RUnlock() + return resp, ok +} + +// Set saves response resp to the cache with key +func (c *MemoryCache) Set(key string, resp []byte) { + c.mu.Lock() + c.items[key] = resp + c.mu.Unlock() +} + +// Delete removes key from the cache +func (c *MemoryCache) Delete(key string) { + c.mu.Lock() + delete(c.items, key) + c.mu.Unlock() +} + +// NewMemoryCache returns a new Cache that will store items in an in-memory map +func NewMemoryCache() *MemoryCache { + c := &MemoryCache{items: map[string][]byte{}} + return c +} + +// Transport is an implementation of http.RoundTripper that will return values from a cache +// where possible (avoiding a network request) and will additionally add validators (etag/if-modified-since) +// to repeated requests allowing servers to return 304 / Not Modified +type Transport struct { + // The RoundTripper interface actually used to make requests + // If nil, http.DefaultTransport is used + Transport http.RoundTripper + Cache Cache + // If true, responses returned from the cache will be given an extra header, X-From-Cache + MarkCachedResponses bool +} + +// NewTransport returns a new Transport with the +// provided Cache implementation and MarkCachedResponses set to true +func NewTransport(c Cache) *Transport { + return &Transport{Cache: c, MarkCachedResponses: true} +} + +// Client returns an *http.Client that caches responses. +func (t *Transport) Client() *http.Client { + return &http.Client{Transport: t} +} + +// varyMatches will return false unless all of the cached values for the headers listed in Vary +// match the new request +func varyMatches(cachedResp *http.Response, req *http.Request) bool { + for _, header := range headerAllCommaSepValues(cachedResp.Header, "vary") { + header = http.CanonicalHeaderKey(header) + if header != "" && req.Header.Get(header) != cachedResp.Header.Get("X-Varied-"+header) { + return false + } + } + return true +} + +// RoundTrip takes a Request and returns a Response +// +// If there is a fresh Response already in cache, then it will be returned without connecting to +// the server. +// +// If there is a stale Response, then any validators it contains will be set on the new request +// to give the server a chance to respond with NotModified. If this happens, then the cached Response +// will be returned. +func (t *Transport) RoundTrip(req *http.Request) (resp *http.Response, err error) { + cacheKey := cacheKey(req) + cacheable := (req.Method == "GET" || req.Method == "HEAD") && req.Header.Get("range") == "" + var cachedResp *http.Response + if cacheable { + cachedResp, err = CachedResponse(t.Cache, req) + } else { + // Need to invalidate an existing value + t.Cache.Delete(cacheKey) + } + + transport := t.Transport + if transport == nil { + transport = http.DefaultTransport + } + + if cacheable && cachedResp != nil && err == nil { + if t.MarkCachedResponses { + cachedResp.Header.Set(XFromCache, "1") + } + + if varyMatches(cachedResp, req) { + // Can only use cached value if the new request doesn't Vary significantly + freshness := getFreshness(cachedResp.Header, req.Header) + if freshness == fresh { + return cachedResp, nil + } + + if freshness == stale { + var req2 *http.Request + // Add validators if caller hasn't already done so + etag := cachedResp.Header.Get("etag") + if etag != "" && req.Header.Get("etag") == "" { + req2 = cloneRequest(req) + req2.Header.Set("if-none-match", etag) + } + lastModified := cachedResp.Header.Get("last-modified") + if lastModified != "" && req.Header.Get("last-modified") == "" { + if req2 == nil { + req2 = cloneRequest(req) + } + req2.Header.Set("if-modified-since", lastModified) + } + if req2 != nil { + req = req2 + } + } + } + + resp, err = transport.RoundTrip(req) + if err == nil && req.Method == "GET" && resp.StatusCode == http.StatusNotModified { + // Replace the 304 response with the one from cache, but update with some new headers + endToEndHeaders := getEndToEndHeaders(resp.Header) + for _, header := range endToEndHeaders { + cachedResp.Header[header] = resp.Header[header] + } + resp = cachedResp + } else if (err != nil || (cachedResp != nil && resp.StatusCode >= 500)) && + req.Method == "GET" && canStaleOnError(cachedResp.Header, req.Header) { + // In case of transport failure and stale-if-error activated, returns cached content + // when available + return cachedResp, nil + } else { + if err != nil || resp.StatusCode != http.StatusOK { + t.Cache.Delete(cacheKey) + } + if err != nil { + return nil, err + } + } + } else { + reqCacheControl := parseCacheControl(req.Header) + if _, ok := reqCacheControl["only-if-cached"]; ok { + resp = newGatewayTimeoutResponse(req) + } else { + resp, err = transport.RoundTrip(req) + if err != nil { + return nil, err + } + } + } + + if cacheable && canStore(parseCacheControl(req.Header), parseCacheControl(resp.Header)) { + for _, varyKey := range headerAllCommaSepValues(resp.Header, "vary") { + varyKey = http.CanonicalHeaderKey(varyKey) + fakeHeader := "X-Varied-" + varyKey + reqValue := req.Header.Get(varyKey) + if reqValue != "" { + resp.Header.Set(fakeHeader, reqValue) + } + } + switch req.Method { + case "GET": + // Delay caching until EOF is reached. + resp.Body = &cachingReadCloser{ + R: resp.Body, + OnEOF: func(r io.Reader) { + resp := *resp + resp.Body = ioutil.NopCloser(r) + respBytes, err := httputil.DumpResponse(&resp, true) + if err == nil { + t.Cache.Set(cacheKey, respBytes) + } + }, + } + default: + respBytes, err := httputil.DumpResponse(resp, true) + if err == nil { + t.Cache.Set(cacheKey, respBytes) + } + } + } else { + t.Cache.Delete(cacheKey) + } + return resp, nil +} + +// ErrNoDateHeader indicates that the HTTP headers contained no Date header. +var ErrNoDateHeader = errors.New("no Date header") + +// Date parses and returns the value of the Date header. +func Date(respHeaders http.Header) (date time.Time, err error) { + dateHeader := respHeaders.Get("date") + if dateHeader == "" { + err = ErrNoDateHeader + return + } + + return time.Parse(time.RFC1123, dateHeader) +} + +type realClock struct{} + +func (c *realClock) since(d time.Time) time.Duration { + return time.Since(d) +} + +type timer interface { + since(d time.Time) time.Duration +} + +var clock timer = &realClock{} + +// getFreshness will return one of fresh/stale/transparent based on the cache-control +// values of the request and the response +// +// fresh indicates the response can be returned +// stale indicates that the response needs validating before it is returned +// transparent indicates the response should not be used to fulfil the request +// +// Because this is only a private cache, 'public' and 'private' in cache-control aren't +// signficant. Similarly, smax-age isn't used. +func getFreshness(respHeaders, reqHeaders http.Header) (freshness int) { + respCacheControl := parseCacheControl(respHeaders) + reqCacheControl := parseCacheControl(reqHeaders) + if _, ok := reqCacheControl["no-cache"]; ok { + return transparent + } + if _, ok := respCacheControl["no-cache"]; ok { + return stale + } + if _, ok := reqCacheControl["only-if-cached"]; ok { + return fresh + } + + date, err := Date(respHeaders) + if err != nil { + return stale + } + currentAge := clock.since(date) + + var lifetime time.Duration + var zeroDuration time.Duration + + // If a response includes both an Expires header and a max-age directive, + // the max-age directive overrides the Expires header, even if the Expires header is more restrictive. + if maxAge, ok := respCacheControl["max-age"]; ok { + lifetime, err = time.ParseDuration(maxAge + "s") + if err != nil { + lifetime = zeroDuration + } + } else { + expiresHeader := respHeaders.Get("Expires") + if expiresHeader != "" { + expires, err := time.Parse(time.RFC1123, expiresHeader) + if err != nil { + lifetime = zeroDuration + } else { + lifetime = expires.Sub(date) + } + } + } + + if maxAge, ok := reqCacheControl["max-age"]; ok { + // the client is willing to accept a response whose age is no greater than the specified time in seconds + lifetime, err = time.ParseDuration(maxAge + "s") + if err != nil { + lifetime = zeroDuration + } + } + if minfresh, ok := reqCacheControl["min-fresh"]; ok { + // the client wants a response that will still be fresh for at least the specified number of seconds. + minfreshDuration, err := time.ParseDuration(minfresh + "s") + if err == nil { + currentAge = time.Duration(currentAge + minfreshDuration) + } + } + + if maxstale, ok := reqCacheControl["max-stale"]; ok { + // Indicates that the client is willing to accept a response that has exceeded its expiration time. + // If max-stale is assigned a value, then the client is willing to accept a response that has exceeded + // its expiration time by no more than the specified number of seconds. + // If no value is assigned to max-stale, then the client is willing to accept a stale response of any age. + // + // Responses served only because of a max-stale value are supposed to have a Warning header added to them, + // but that seems like a hassle, and is it actually useful? If so, then there needs to be a different + // return-value available here. + if maxstale == "" { + return fresh + } + maxstaleDuration, err := time.ParseDuration(maxstale + "s") + if err == nil { + currentAge = time.Duration(currentAge - maxstaleDuration) + } + } + + if lifetime > currentAge { + return fresh + } + + return stale +} + +// Returns true if either the request or the response includes the stale-if-error +// cache control extension: https://tools.ietf.org/html/rfc5861 +func canStaleOnError(respHeaders, reqHeaders http.Header) bool { + respCacheControl := parseCacheControl(respHeaders) + reqCacheControl := parseCacheControl(reqHeaders) + + var err error + lifetime := time.Duration(-1) + + if staleMaxAge, ok := respCacheControl["stale-if-error"]; ok { + if staleMaxAge != "" { + lifetime, err = time.ParseDuration(staleMaxAge + "s") + if err != nil { + return false + } + } else { + return true + } + } + if staleMaxAge, ok := reqCacheControl["stale-if-error"]; ok { + if staleMaxAge != "" { + lifetime, err = time.ParseDuration(staleMaxAge + "s") + if err != nil { + return false + } + } else { + return true + } + } + + if lifetime >= 0 { + date, err := Date(respHeaders) + if err != nil { + return false + } + currentAge := clock.since(date) + if lifetime > currentAge { + return true + } + } + + return false +} + +func getEndToEndHeaders(respHeaders http.Header) []string { + // These headers are always hop-by-hop + hopByHopHeaders := map[string]struct{}{ + "Connection": {}, + "Keep-Alive": {}, + "Proxy-Authenticate": {}, + "Proxy-Authorization": {}, + "Te": {}, + "Trailers": {}, + "Transfer-Encoding": {}, + "Upgrade": {}, + } + + for _, extra := range strings.Split(respHeaders.Get("connection"), ",") { + // any header listed in connection, if present, is also considered hop-by-hop + if strings.Trim(extra, " ") != "" { + hopByHopHeaders[http.CanonicalHeaderKey(extra)] = struct{}{} + } + } + endToEndHeaders := []string{} + for respHeader := range respHeaders { + if _, ok := hopByHopHeaders[respHeader]; !ok { + endToEndHeaders = append(endToEndHeaders, respHeader) + } + } + return endToEndHeaders +} + +func canStore(reqCacheControl, respCacheControl cacheControl) (canStore bool) { + if _, ok := respCacheControl["no-store"]; ok { + return false + } + if _, ok := reqCacheControl["no-store"]; ok { + return false + } + return true +} + +func newGatewayTimeoutResponse(req *http.Request) *http.Response { + var braw bytes.Buffer + braw.WriteString("HTTP/1.1 504 Gateway Timeout\r\n\r\n") + resp, err := http.ReadResponse(bufio.NewReader(&braw), req) + if err != nil { + panic(err) + } + return resp +} + +// cloneRequest returns a clone of the provided *http.Request. +// The clone is a shallow copy of the struct and its Header map. +// (This function copyright goauth2 authors: https://code.google.com/p/goauth2) +func cloneRequest(r *http.Request) *http.Request { + // shallow copy of the struct + r2 := new(http.Request) + *r2 = *r + // deep copy of the Header + r2.Header = make(http.Header) + for k, s := range r.Header { + r2.Header[k] = s + } + return r2 +} + +type cacheControl map[string]string + +func parseCacheControl(headers http.Header) cacheControl { + cc := cacheControl{} + ccHeader := headers.Get("Cache-Control") + for _, part := range strings.Split(ccHeader, ",") { + part = strings.Trim(part, " ") + if part == "" { + continue + } + if strings.ContainsRune(part, '=') { + keyval := strings.Split(part, "=") + cc[strings.Trim(keyval[0], " ")] = strings.Trim(keyval[1], ",") + } else { + cc[part] = "" + } + } + return cc +} + +// headerAllCommaSepValues returns all comma-separated values (each +// with whitespace trimmed) for header name in headers. According to +// Section 4.2 of the HTTP/1.1 spec +// (http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2), +// values from multiple occurrences of a header should be concatenated, if +// the header's value is a comma-separated list. +func headerAllCommaSepValues(headers http.Header, name string) []string { + var vals []string + for _, val := range headers[http.CanonicalHeaderKey(name)] { + fields := strings.Split(val, ",") + for i, f := range fields { + fields[i] = strings.TrimSpace(f) + } + vals = append(vals, fields...) + } + return vals +} + +// cachingReadCloser is a wrapper around ReadCloser R that calls OnEOF +// handler with a full copy of the content read from R when EOF is +// reached. +type cachingReadCloser struct { + // Underlying ReadCloser. + R io.ReadCloser + // OnEOF is called with a copy of the content of R when EOF is reached. + OnEOF func(io.Reader) + + buf bytes.Buffer // buf stores a copy of the content of R. +} + +// Read reads the next len(p) bytes from R or until R is drained. The +// return value n is the number of bytes read. If R has no data to +// return, err is io.EOF and OnEOF is called with a full copy of what +// has been read so far. +func (r *cachingReadCloser) Read(p []byte) (n int, err error) { + n, err = r.R.Read(p) + r.buf.Write(p[:n]) + if err == io.EOF { + r.OnEOF(bytes.NewReader(r.buf.Bytes())) + } + return n, err +} + +func (r *cachingReadCloser) Close() error { + return r.R.Close() +} + +// NewMemoryCacheTransport returns a new Transport using the in-memory cache implementation +func NewMemoryCacheTransport() *Transport { + c := NewMemoryCache() + t := NewTransport(c) + return t +} diff --git a/vendor/github.com/palantir/go-githubapp/githubapp/client_creator.go b/vendor/github.com/palantir/go-githubapp/githubapp/client_creator.go index 8eec178a3..c4765bd9b 100644 --- a/vendor/github.com/palantir/go-githubapp/githubapp/client_creator.go +++ b/vendor/github.com/palantir/go-githubapp/githubapp/client_creator.go @@ -19,10 +19,12 @@ import ( "fmt" "net/http" "net/url" + "regexp" "strings" "github.com/bradleyfalzon/ghinstallation" "github.com/google/go-github/github" + "github.com/gregjones/httpcache" "github.com/pkg/errors" "github.com/shurcooL/githubv4" "golang.org/x/oauth2" @@ -84,6 +86,14 @@ type ClientCreator interface { NewTokenV4Client(token string) (*githubv4.Client, error) } +var ( + maxAgeRegex = regexp.MustCompile(`max-age=\d+`) +) + +type key string + +const installationKey = key("installationID") + // NewClientCreator returns a ClientCreator that creates a GitHub client for // installations of the app specified by the provided arguments. func NewClientCreator(v3BaseURL, v4BaseURL string, integrationID int, privKeyBytes []byte, opts ...ClientOption) ClientCreator { @@ -109,19 +119,21 @@ func NewClientCreator(v3BaseURL, v4BaseURL string, integrationID int, privKeyByt } type clientCreator struct { - v3BaseURL string - v4BaseURL string - integrationID int - privKeyBytes []byte - userAgent string - middleware []ClientMiddleware + v3BaseURL string + v4BaseURL string + integrationID int + privKeyBytes []byte + userAgent string + middleware []ClientMiddleware + cacheFunc func() httpcache.Cache + alwaysValidate bool } var _ ClientCreator = &clientCreator{} type ClientOption func(c *clientCreator) -// ClientMiddleware modifes the transport of a GitHub client to add common +// ClientMiddleware modifies the transport of a GitHub client to add common // functionality, like logging or metrics collection. type ClientMiddleware func(http.RoundTripper) http.RoundTripper @@ -132,6 +144,18 @@ func WithClientUserAgent(agent string) ClientOption { } } +// WithClientCaching sets an HTTP cache for all created clients +// using the provided cache implementation +// If alwaysValidate is true, the cache validates all saved responses before returning them. +// Otherwise, it respects the caching headers returned by GitHub. +// https://developer.github.com/v3/#conditional-requests +func WithClientCaching(alwaysValidate bool, cache func() httpcache.Cache) ClientOption { + return func(c *clientCreator) { + c.cacheFunc = cache + c.alwaysValidate = alwaysValidate + } +} + // WithClientMiddleware adds middleware that is applied to all created clients. func WithClientMiddleware(middleware ...ClientMiddleware) ClientOption { return func(c *clientCreator) { @@ -140,61 +164,96 @@ func WithClientMiddleware(middleware ...ClientMiddleware) ClientOption { } func (c *clientCreator) NewAppClient() (*github.Client, error) { - itr, err := ghinstallation.NewAppsTransport(http.DefaultTransport, c.integrationID, c.privKeyBytes) + base := &http.Client{Transport: http.DefaultTransport} + + installation, transportError := newAppInstallation(c.integrationID, c.privKeyBytes, c.v3BaseURL) + middleware := append(c.middleware, installation) + if c.cacheFunc != nil { + middleware = append(middleware, cache(c.cacheFunc), cacheControl(c.alwaysValidate)) + } + + client, err := c.newClient(base, middleware, "application", 0) if err != nil { return nil, err } - - itr.BaseURL = strings.TrimSuffix(c.v3BaseURL, "/") - return c.newClient(&http.Client{Transport: itr}, "application") + if *transportError != nil { + return nil, *transportError + } + return client, nil } func (c *clientCreator) NewAppV4Client() (*githubv4.Client, error) { - itr, err := ghinstallation.NewAppsTransport(http.DefaultTransport, c.integrationID, c.privKeyBytes) + base := &http.Client{Transport: http.DefaultTransport} + + installation, transportError := newAppInstallation(c.integrationID, c.privKeyBytes, c.v3BaseURL) + + // The v4 API primarily uses POST requests (except for introspection queries) + // which we cannot cache, so don't construct the middleware + middleware := append(c.middleware, installation) + + client, err := c.newV4Client(base, middleware, "application", 0) if err != nil { return nil, err } - - // leaving the v3 URL since this is used to refresh the token, not make queries - itr.BaseURL = strings.TrimSuffix(c.v3BaseURL, "/") - return c.newV4Client(&http.Client{Transport: itr}, "application") + if *transportError != nil { + return nil, *transportError + } + return client, nil } func (c *clientCreator) NewInstallationClient(installationID int64) (*github.Client, error) { - itr, err := ghinstallation.New(http.DefaultTransport, c.integrationID, int(installationID), c.privKeyBytes) + base := &http.Client{Transport: http.DefaultTransport} + + installation, transportError := newInstallation(c.integrationID, int(installationID), c.privKeyBytes, c.v3BaseURL) + middleware := append(c.middleware, installation) + if c.cacheFunc != nil { + middleware = append(middleware, cache(c.cacheFunc), cacheControl(c.alwaysValidate)) + } + + client, err := c.newClient(base, middleware, fmt.Sprintf("installation: %d", installationID), installationID) if err != nil { return nil, err } - - itr.BaseURL = strings.TrimSuffix(c.v3BaseURL, "/") - return c.newClient(&http.Client{Transport: itr}, fmt.Sprintf("installation: %d", installationID)) + if *transportError != nil { + return nil, *transportError + } + return client, nil } func (c *clientCreator) NewInstallationV4Client(installationID int64) (*githubv4.Client, error) { - itr, err := ghinstallation.New(http.DefaultTransport, c.integrationID, int(installationID), c.privKeyBytes) + base := &http.Client{Transport: http.DefaultTransport} + + installation, transportError := newInstallation(c.integrationID, int(installationID), c.privKeyBytes, c.v3BaseURL) + + // The v4 API primarily uses POST requests (except for introspection queries) + // which we cannot cache, so don't construct the middleware + middleware := append(c.middleware, installation) + + client, err := c.newV4Client(base, middleware, fmt.Sprintf("installation: %d", installationID), installationID) if err != nil { return nil, err } - - // leaving the v3 URL since this is used to refresh the token, not make queries - itr.BaseURL = strings.TrimSuffix(c.v3BaseURL, "/") - return c.newV4Client(&http.Client{Transport: itr}, fmt.Sprintf("installation: %d", installationID)) + if *transportError != nil { + return nil, *transportError + } + return client, nil } func (c *clientCreator) NewTokenClient(token string) (*github.Client, error) { ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token}) tc := oauth2.NewClient(context.Background(), ts) - return c.newClient(tc, "oauth token") + return c.newClient(tc, c.middleware, "oauth token", 0) } func (c *clientCreator) NewTokenV4Client(token string) (*githubv4.Client, error) { ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token}) tc := oauth2.NewClient(context.Background(), ts) - return c.newV4Client(tc, "oauth token") + return c.newV4Client(tc, c.middleware, "oauth token", 0) } -func (c *clientCreator) newClient(base *http.Client, details string) (*github.Client, error) { - applyMiddleware(base, c.middleware) +func (c *clientCreator) newClient(base *http.Client, middleware []ClientMiddleware, details string, installID int64) (*github.Client, error) { + middleware = append(middleware, setInstallationID(installID)) + applyMiddleware(base, middleware) baseURL, err := url.Parse(c.v3BaseURL) if err != nil { @@ -208,10 +267,10 @@ func (c *clientCreator) newClient(base *http.Client, details string) (*github.Cl return client, nil } -func (c *clientCreator) newV4Client(base *http.Client, details string) (*githubv4.Client, error) { +func (c *clientCreator) newV4Client(base *http.Client, middleware []ClientMiddleware, details string, installID int64) (*githubv4.Client, error) { ua := makeUserAgent(c.userAgent, details) - middleware := append([]ClientMiddleware{setUserAgentHeader(ua)}, c.middleware...) + middleware = append([]ClientMiddleware{setUserAgentHeader(ua)}, middleware...) applyMiddleware(base, middleware) v4BaseURL, err := url.Parse(c.v4BaseURL) @@ -229,6 +288,66 @@ func applyMiddleware(base *http.Client, middleware []ClientMiddleware) { } } +func newAppInstallation(integrationID int, privKeyBytes []byte, v3BaseURL string) (ClientMiddleware, *error) { + var transportError error + installation := func(next http.RoundTripper) http.RoundTripper { + itr, err := ghinstallation.NewAppsTransport(next, integrationID, privKeyBytes) + if err != nil { + transportError = err + return next + } + // leaving the v3 URL since this is used to refresh the token, not make queries + itr.BaseURL = strings.TrimSuffix(v3BaseURL, "/") + return itr + } + return installation, &transportError +} + +func newInstallation(integrationID, installationID int, privKeyBytes []byte, v3BaseURL string) (ClientMiddleware, *error) { + var transportError error + installation := func(next http.RoundTripper) http.RoundTripper { + itr, err := ghinstallation.New(next, integrationID, installationID, privKeyBytes) + if err != nil { + transportError = err + return next + } + // leaving the v3 URL since this is used to refresh the token, not make queries + itr.BaseURL = strings.TrimSuffix(v3BaseURL, "/") + return itr + } + return installation, &transportError +} + +func cache(cacheFunc func() httpcache.Cache) ClientMiddleware { + return func(next http.RoundTripper) http.RoundTripper { + return &httpcache.Transport{ + Transport: next, + Cache: cacheFunc(), + MarkCachedResponses: true, + } + } +} + +func cacheControl(alwaysValidate bool) ClientMiddleware { + return func(next http.RoundTripper) http.RoundTripper { + if !alwaysValidate { + return next + } + return roundTripperFunc(func(r *http.Request) (*http.Response, error) { + resp, err := next.RoundTrip(r) + + // Force validation to occur when the cache is disabled by setting max-age=0, + // as the cache results will always appear as stale + cacheControl := resp.Header.Get("Cache-Control") + if cacheControl != "" { + newCacheControl := maxAgeRegex.ReplaceAllString(cacheControl, "max-age=0") + resp.Header.Set("Cache-Control", newCacheControl) + } + return resp, err + }) + } +} + func makeUserAgent(base, details string) string { if base == "" { base = "github-base-app/undefined" @@ -236,6 +355,15 @@ func makeUserAgent(base, details string) string { return fmt.Sprintf("%s (%s)", base, details) } +func setInstallationID(installationID int64) ClientMiddleware { + return func(next http.RoundTripper) http.RoundTripper { + return roundTripperFunc(func(r *http.Request) (*http.Response, error) { + r = r.WithContext(context.WithValue(r.Context(), installationKey, installationID)) + return next.RoundTrip(r) + }) + } +} + func setUserAgentHeader(agent string) ClientMiddleware { return func(next http.RoundTripper) http.RoundTripper { return roundTripperFunc(func(r *http.Request) (*http.Response, error) { diff --git a/vendor/github.com/palantir/go-githubapp/githubapp/middleware.go b/vendor/github.com/palantir/go-githubapp/githubapp/middleware.go index 6ecfab1e4..2f7dfe5e1 100644 --- a/vendor/github.com/palantir/go-githubapp/githubapp/middleware.go +++ b/vendor/github.com/palantir/go-githubapp/githubapp/middleware.go @@ -15,9 +15,12 @@ package githubapp import ( + "fmt" "net/http" + "strconv" "time" + "github.com/gregjones/httpcache" "github.com/rcrowley/go-metrics" "github.com/rs/zerolog" ) @@ -28,6 +31,11 @@ const ( MetricsKeyRequests3xx = "github.requests.3xx" MetricsKeyRequests4xx = "github.requests.4xx" MetricsKeyRequests5xx = "github.requests.5xx" + + MetricsKeyRequestsCached = "github.requests.cached" + + MetricsKeyRateLimit = "github.rate.limit" + MetricsKeyRateLimitRemaining = "github.rate.remaining" ) // ClientMetrics creates client middleware that records metrics about all @@ -39,6 +47,7 @@ func ClientMetrics(registry metrics.Registry) ClientMiddleware { MetricsKeyRequests3xx, MetricsKeyRequests4xx, MetricsKeyRequests5xx, + MetricsKeyRequestsCached, } { // Use GetOrRegister for thread-safety when creating multiple // RoundTrippers that share the same registry @@ -47,6 +56,11 @@ func ClientMetrics(registry metrics.Registry) ClientMiddleware { return func(next http.RoundTripper) http.RoundTripper { return roundTripperFunc(func(r *http.Request) (*http.Response, error) { + installationID, ok := r.Context().Value(installationKey).(int64) + if !ok { + installationID = 0 + } + res, err := next.RoundTrip(r) if res != nil { @@ -54,6 +68,17 @@ func ClientMetrics(registry metrics.Registry) ClientMiddleware { if key := bucketStatus(res.StatusCode); key != "" { registry.Get(key).(metrics.Counter).Inc(1) } + + if res.Header.Get(httpcache.XFromCache) != "" { + registry.Get(MetricsKeyRequestsCached).(metrics.Counter).Inc(1) + } + + limitMetric := fmt.Sprintf("%s[installation:%d]", MetricsKeyRateLimit, installationID) + remainingMetric := fmt.Sprintf("%s[installation:%d]", MetricsKeyRateLimitRemaining, installationID) + + // Headers from https://developer.github.com/v3/#rate-limiting + updateRegistryForHeader(res.Header, "X-RateLimit-Limit", metrics.GetOrRegisterGauge(limitMetric, registry)) + updateRegistryForHeader(res.Header, "X-RateLimit-Remaining", metrics.GetOrRegisterGauge(remainingMetric, registry)) } return res, err @@ -61,6 +86,16 @@ func ClientMetrics(registry metrics.Registry) ClientMiddleware { } } +func updateRegistryForHeader(headers http.Header, header string, metric metrics.Gauge) { + headerString := headers.Get(header) + if headerString != "" { + headerVal, err := strconv.ParseInt(headerString, 10, 64) + if err == nil { + metric.Update(headerVal) + } + } +} + func bucketStatus(status int) string { switch { case status >= 200 && status < 300: