pax_global_header00006660000000000000000000000064146557607140014531gustar00rootroot0000000000000052 comment=54242073ec609cbf6a8ce5f2d43c879553d3020e golang-github-grafana-gomemcache-0.0~git20240805.fdaf6a9/000077500000000000000000000000001465576071400225505ustar00rootroot00000000000000golang-github-grafana-gomemcache-0.0~git20240805.fdaf6a9/.github/000077500000000000000000000000001465576071400241105ustar00rootroot00000000000000golang-github-grafana-gomemcache-0.0~git20240805.fdaf6a9/.github/workflows/000077500000000000000000000000001465576071400261455ustar00rootroot00000000000000golang-github-grafana-gomemcache-0.0~git20240805.fdaf6a9/.github/workflows/test.yml000066400000000000000000000013301465576071400276440ustar00rootroot00000000000000name: Test on: - pull_request jobs: test: runs-on: ubuntu-latest steps: - name: Set up Go 1.22 uses: actions/setup-go@v5 with: go-version: 1.22 - name: Check out code uses: actions/checkout@v4 - name: Install Memcached run: sudo apt-get install -y memcached - name: Run Tests run: go test -v -race ./... lint: name: Lint runs-on: ubuntu-latest steps: - name: Set up Go 1.22 uses: actions/setup-go@v5 with: go-version: 1.22 - name: Check out code uses: actions/checkout@v4 - name: Lint uses: golangci/golangci-lint-action@v6 with: version: v1.59.1 golang-github-grafana-gomemcache-0.0~git20240805.fdaf6a9/.gitignore000066400000000000000000000000141465576071400245330ustar00rootroot00000000000000_* *.out *~ golang-github-grafana-gomemcache-0.0~git20240805.fdaf6a9/LICENSE000066400000000000000000000261361465576071400235650ustar00rootroot00000000000000 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. golang-github-grafana-gomemcache-0.0~git20240805.fdaf6a9/README.md000066400000000000000000000014021465576071400240240ustar00rootroot00000000000000## About This is a memcache client library for the Go programming language (http://golang.org/). ## Installing ### Using *go get* $ go get github.com/grafana/gomemcache/memcache After this command *gomemcache* is ready to use. Its source will be in: $GOPATH/src/github.com/grafana/gomemcache/memcache ## Example import ( "github.com/grafana/gomemcache/memcache" ) func main() { mc := memcache.New("10.0.0.1:11211", "10.0.0.2:11211", "10.0.0.3:11212") mc.Set(&memcache.Item{Key: "foo", Value: []byte("my value")}) it, err := mc.Get("foo") ... } ## Full docs, see: See https://godoc.org/github.com/grafana/gomemcache/memcache Or run: $ godoc github.com/grafana/gomemcache/memcache golang-github-grafana-gomemcache-0.0~git20240805.fdaf6a9/go.mod000066400000000000000000000000561465576071400236570ustar00rootroot00000000000000module github.com/grafana/gomemcache go 1.22 golang-github-grafana-gomemcache-0.0~git20240805.fdaf6a9/go.sum000066400000000000000000000000001465576071400236710ustar00rootroot00000000000000golang-github-grafana-gomemcache-0.0~git20240805.fdaf6a9/memcache/000077500000000000000000000000001465576071400243125ustar00rootroot00000000000000golang-github-grafana-gomemcache-0.0~git20240805.fdaf6a9/memcache/memcache.go000066400000000000000000000657151465576071400264210ustar00rootroot00000000000000/* Copyright 2011 Google Inc. 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. */ // Package memcache provides a client for the memcached cache server. package memcache import ( "bufio" "bytes" "context" "errors" "fmt" "io" "math" "net" "strconv" "strings" "sync" "time" ) // Similar to: // https://godoc.org/google.golang.org/appengine/memcache var ( // ErrCacheMiss means that a Get failed because the item wasn't present. ErrCacheMiss = errors.New("memcache: cache miss") // ErrCASConflict means that a CompareAndSwap call failed due to the // cached value being modified between the Get and the CompareAndSwap. // If the cached value was simply evicted rather than replaced, // ErrNotStored will be returned instead. ErrCASConflict = errors.New("memcache: compare-and-swap conflict") // ErrNotStored means that a conditional write operation (i.e. Add or // CompareAndSwap) failed because the condition was not satisfied. ErrNotStored = errors.New("memcache: item not stored") // ErrServerError means that a server error occurred. ErrServerError = errors.New("memcache: server error") // ErrNoStats means that no statistics were available. ErrNoStats = errors.New("memcache: no statistics available") // ErrMalformedKey is returned when an invalid key is used. // Keys must be at maximum 250 bytes long and not // contain whitespace or control characters. ErrMalformedKey = errors.New("malformed: key is too long or contains invalid characters") // ErrNoServers is returned when no servers are configured or available. ErrNoServers = errors.New("memcache: no servers configured or available") ) const ( // DefaultTimeout is the default socket read/write timeout. DefaultTimeout = 100 * time.Millisecond // DefaultMaxIdleConns is the default maximum number of idle connections // kept for any single address. DefaultMaxIdleConns = 2 // releaseIdleConnsCheckFrequency is how frequently to check if there are idle // connections to release, in order to honor the configured min conns headroom. releaseIdleConnsCheckFrequency = time.Minute // defaultRecentlyUsedConnsThreshold is the default grace period given to an // idle connection to consider it "recently used". The default value has been // set equal to the default TCP TIME_WAIT timeout in linux. defaultRecentlyUsedConnsThreshold = 2 * time.Minute // defaultReconnectCronTimeout is how often the client will attempt to reestablish // connection to the server when initialized with NewWithBackgroundReconnect defaultReconnectCronTimeout = 10 * time.Minute ) const buffered = 8 // arbitrary buffered channel size, for readability // resumableError returns true if err is only a protocol-level cache error. // This is used to determine whether or not a server connection should // be re-used or not. If an error occurs, by default we don't reuse the // connection, unless it was just a cache error. func resumableError(err error) bool { switch err { case ErrCacheMiss, ErrCASConflict, ErrNotStored, ErrMalformedKey: return true } return false } func legalKey(key string) bool { if len(key) > 250 { return false } for i := 0; i < len(key); i++ { if key[i] <= ' ' || key[i] == 0x7f { return false } } return true } var ( crlf = []byte("\r\n") resultOK = []byte("OK\r\n") resultStored = []byte("STORED\r\n") resultNotStored = []byte("NOT_STORED\r\n") resultExists = []byte("EXISTS\r\n") resultNotFound = []byte("NOT_FOUND\r\n") resultDeleted = []byte("DELETED\r\n") resultEnd = []byte("END\r\n") resultOk = []byte("OK\r\n") resultTouched = []byte("TOUCHED\r\n") resultClientErrorPrefix = []byte("CLIENT_ERROR ") versionPrefix = []byte("VERSION") valuePrefix = []byte("VALUE ") ) // New returns a memcache client using the provided server(s) // with equal weight. If a server is listed multiple times, // it gets a proportional amount of weight. func New(server ...string) *Client { ss := new(ServerList) _ = ss.SetServers(server...) c := NewFromSelector(ss) c.serverList = append(c.serverList, server...) return c } // NewWithBackgroundReconnect returns the same thing as New(server ...string), but takes a context and timeout to initiate a bakground reconnect cron func NewWithBackgroundReconnect(ctx context.Context, interval time.Duration, server ...string) *Client { c := New(server...) if interval == 0 { interval = defaultReconnectCronTimeout } ticker := time.NewTicker(interval) // periodically ping the provided servers -- if there are timeouts, it will trigger a reconnect attempt go func() { for { select { case <-ctx.Done(): ticker.Stop() return case <-ticker.C: _ = c.Ping() } } }() return c } // NewFromSelector returns a new Client using the provided ServerSelector. func NewFromSelector(ss ServerSelector) *Client { c := &Client{ selector: ss, closed: make(chan struct{}), } go c.releaseIdleConnectionsUntilClosed() return c } // Client is a memcache client. // It is safe for unlocked use by multiple concurrent goroutines. type Client struct { // DialTimeout specifies a custom dialer used to dial new connections to a server. DialTimeout func(network, address string, timeout time.Duration) (net.Conn, error) // Timeout specifies the socket read/write timeout. // If zero, DefaultTimeout is used. Timeout time.Duration // ConnectTimeout specifies the timeout for new connections. // If zero, DefaultTimeout is used. ConnectTimeout time.Duration // MinIdleConnsHeadroomPercentage specifies the percentage of minimum number of idle connections // that should be kept open, compared to the number of free but recently used connections. // If there are idle connections but none of them has been recently used, then all idle // connections get closed. // // If the configured value is negative, idle connections are never closed. MinIdleConnsHeadroomPercentage float64 // MaxIdleConns specifies the maximum number of idle connections that will // be maintained per address. If less than one, DefaultMaxIdleConns will be // used. // // Consider your expected traffic rates and latency carefully. This should // be set to a number higher than your peak parallel requests. MaxIdleConns int // WriteBufferSizeBytes specifies the size of the write buffer (in bytes). The buffer // is allocated for each connection. If <= 0, the default value of 4KB will be used. WriteBufferSizeBytes int // ReadBufferSizeBytes specifies the size of the read buffer (in bytes). The buffer // is allocated for each connection. If <= 0, the default value of 4KB will be used. ReadBufferSizeBytes int // recentlyUsedConnsThreshold is the default grace period given to an // idle connection to consider it "recently used". Recently used connections // are never closed even if idle. // // This field is used for testing. recentlyUsedConnsThreshold time.Duration // closed channel gets closed once the Client.Close() is called. Once closed, // resources should be released. closed chan struct{} closeOnce sync.Once selector ServerSelector lk sync.Mutex freeconn map[string][]*conn serverList []string reconnectLock sync.Mutex } // Item is an item to be got or stored in a memcached server. type Item struct { // Key is the Item's key (250 bytes maximum). Key string // Value is the Item's value. Value []byte // Flags are server-opaque flags whose semantics are entirely // up to the app. Flags uint32 // Expiration is the cache expiration time, in seconds: either a relative // time from now (up to 1 month), or an absolute Unix epoch time. // Zero means the Item has no expiration time. Expiration int32 // Compare and swap ID. casid uint64 } // conn is a connection to a server. type conn struct { nc net.Conn rw *bufio.ReadWriter addr net.Addr c *Client // The timestamp since when this connection is idle. This is used to close // idle connections. idleSince time.Time } // release returns this connection back to the client's free pool func (cn *conn) release() { cn.c.putFreeConn(cn.addr, cn) } func (cn *conn) extendDeadline() { _ = cn.nc.SetDeadline(time.Now().Add(cn.c.netTimeout())) } // condRelease releases this connection if the error pointed to by err // is nil (not an error) or is only a protocol level error (e.g. a // cache miss). The purpose is to not recycle TCP connections that // are bad. func (cn *conn) condRelease(err *error) { if *err == nil || resumableError(*err) { cn.release() } else { cn.nc.Close() } } func (c *Client) putFreeConn(addr net.Addr, cn *conn) { c.lk.Lock() defer c.lk.Unlock() if c.freeconn == nil { c.freeconn = make(map[string][]*conn) } freelist := c.freeconn[addr.String()] if len(freelist) >= c.maxIdleConns() { cn.nc.Close() return } cn.idleSince = time.Now() c.freeconn[addr.String()] = append(freelist, cn) } func (c *Client) getFreeConn(addr net.Addr) (cn *conn, ok bool) { c.lk.Lock() defer c.lk.Unlock() if c.freeconn == nil { return nil, false } freelist, ok := c.freeconn[addr.String()] if !ok || len(freelist) == 0 { return nil, false } // Pop the connection from the end of the list. This way we prefer to always reuse // the same connections, so that the min idle connections logic is effective. cn = freelist[len(freelist)-1] c.freeconn[addr.String()] = freelist[:len(freelist)-1] return cn, true } func (c *Client) netTimeout() time.Duration { if c.Timeout != 0 { return c.Timeout } return DefaultTimeout } func (c *Client) connectTimeout() time.Duration { if c.ConnectTimeout != 0 { return c.ConnectTimeout } return DefaultTimeout } func (c *Client) maxIdleConns() int { if c.MaxIdleConns > 0 { return c.MaxIdleConns } return DefaultMaxIdleConns } func (c *Client) Close() { c.closeOnce.Do(func() { close(c.closed) }) } func (c *Client) releaseIdleConnectionsUntilClosed() { for { select { case <-time.After(releaseIdleConnsCheckFrequency): c.releaseIdleConnections() case <-c.closed: return } } } func (c *Client) releaseIdleConnections() { var toClose []io.Closer // Nothing to do if min idle connections headroom is disabled (negative value). minIdleHeadroomPercentage := c.MinIdleConnsHeadroomPercentage if minIdleHeadroomPercentage < 0 { return } // Get the recently used connections threshold, falling back to the default one. recentlyUsedThreshold := c.recentlyUsedConnsThreshold if recentlyUsedThreshold == 0 { recentlyUsedThreshold = defaultRecentlyUsedConnsThreshold } c.lk.Lock() for addr, freeConnections := range c.freeconn { numIdle := 0 // Count the number of idle connections. Since the least used connections are at the beginning // of the list, we can stop searching as soon as we find a non-idle connection. for _, freeConn := range freeConnections { if time.Since(freeConn.idleSince) < recentlyUsedThreshold { break } numIdle++ } // Compute the number of connections to close. It keeps a number of idle connections equal to // the configured headroom. numRecentlyUsed := len(freeConnections) - numIdle numIdleToKeep := int(math.Max(0, math.Ceil(float64(numRecentlyUsed)*minIdleHeadroomPercentage/100))) numIdleToClose := numIdle - numIdleToKeep if numIdleToClose <= 0 { continue } // Close idle connections. for i := 0; i < numIdleToClose; i++ { toClose = append(toClose, freeConnections[i].nc) } c.freeconn[addr] = c.freeconn[addr][numIdleToClose:] } // Release the lock and then close the connections. c.lk.Unlock() for _, freeConn := range toClose { freeConn.Close() } } // ConnectTimeoutError is the error type used when it takes // too long to connect to the desired host. This level of // detail can generally be ignored. type ConnectTimeoutError struct { Addr net.Addr } func (cte *ConnectTimeoutError) Error() string { return "memcache: connect timeout to " + cte.Addr.String() } func (c *Client) dial(addr net.Addr) (net.Conn, error) { dialTimeout := c.DialTimeout if dialTimeout == nil { dialTimeout = net.DialTimeout } nc, err := dialTimeout(addr.Network(), addr.String(), c.connectTimeout()) if err == nil { return nc, nil } if ne, ok := err.(net.Error); ok && ne.Timeout() { // In the case of a timeout, we might need to reestablish a connection to one or more servers, for example in case of an IP change // Fire this off in a goroutine so it doesn't delay a response back to the client c.backgroundReconnect() return nil, &ConnectTimeoutError{addr} } return nil, err } func (c *Client) getConn(addr net.Addr) (*conn, error) { var ( writer *bufio.Writer reader *bufio.Reader ) cn, ok := c.getFreeConn(addr) if ok { cn.extendDeadline() return cn, nil } nc, err := c.dial(addr) if err != nil { return nil, err } // Init buffered writer. if c.WriteBufferSizeBytes > 0 { writer = bufio.NewWriterSize(nc, c.WriteBufferSizeBytes) } else { writer = bufio.NewWriter(nc) } // Init buffered reader. if c.ReadBufferSizeBytes > 0 { reader = bufio.NewReaderSize(nc, c.ReadBufferSizeBytes) } else { reader = bufio.NewReader(nc) } cn = &conn{ nc: nc, addr: addr, rw: bufio.NewReadWriter(reader, writer), c: c, } cn.extendDeadline() return cn, nil } func (c *Client) onItem(item *Item, fn func(*Client, *bufio.ReadWriter, *Item) error) error { addr, err := c.selector.PickServer(item.Key) if err != nil { return err } cn, err := c.getConn(addr) if err != nil { return err } defer cn.condRelease(&err) if err = fn(c, cn.rw, item); err != nil { return err } return nil } func (c *Client) FlushAll() error { return c.selector.Each(c.flushAllFromAddr) } // Get gets the item for the given key. ErrCacheMiss is returned for a // memcache cache miss. The key must be at most 250 bytes in length. func (c *Client) Get(key string, opts ...Option) (item *Item, err error) { options := newOptions(opts...) err = c.withKeyAddr(key, func(addr net.Addr) error { return c.getFromAddr(addr, []string{key}, options, func(it *Item) { item = it }) }) if err == nil && item == nil { err = ErrCacheMiss } return } // Touch updates the expiry for the given key. The seconds parameter is either // a Unix timestamp or, if seconds is less than 1 month, the number of seconds // into the future at which time the item will expire. Zero means the item has // no expiration time. ErrCacheMiss is returned if the key is not in the cache. // The key must be at most 250 bytes in length. func (c *Client) Touch(key string, seconds int32) (err error) { return c.withKeyAddr(key, func(addr net.Addr) error { return c.touchFromAddr(addr, []string{key}, seconds) }) } func (c *Client) withKeyAddr(key string, fn func(net.Addr) error) (err error) { if !legalKey(key) { return ErrMalformedKey } addr, err := c.selector.PickServer(key) if err != nil { return err } return fn(addr) } func (c *Client) withAddrRw(addr net.Addr, fn func(*conn) error) (err error) { cn, err := c.getConn(addr) if err != nil { return err } defer cn.condRelease(&err) return fn(cn) } func (c *Client) withKeyRw(key string, fn func(*conn) error) error { return c.withKeyAddr(key, func(addr net.Addr) error { return c.withAddrRw(addr, fn) }) } func (c *Client) getFromAddr(addr net.Addr, keys []string, opts *Options, cb func(*Item)) error { return c.withAddrRw(addr, func(conn *conn) error { rw := conn.rw if _, err := fmt.Fprintf(rw, "gets %s\r\n", strings.Join(keys, " ")); err != nil { return err } if err := rw.Flush(); err != nil { return err } if err := c.parseGetResponse(rw.Reader, conn, opts, cb); err != nil { return err } return nil }) } // flushAllFromAddr send the flush_all command to the given addr func (c *Client) flushAllFromAddr(addr net.Addr) error { return c.withAddrRw(addr, func(conn *conn) error { rw := conn.rw if _, err := fmt.Fprintf(rw, "flush_all\r\n"); err != nil { return err } if err := rw.Flush(); err != nil { return err } line, err := rw.ReadSlice('\n') if err != nil { return err } switch { case bytes.Equal(line, resultOk): break default: return fmt.Errorf("memcache: unexpected response line from flush_all: %q", string(line)) } return nil }) } // ping sends the version command to the given addr func (c *Client) ping(addr net.Addr) error { return c.withAddrRw(addr, func(conn *conn) error { rw := conn.rw if _, err := fmt.Fprintf(rw, "version\r\n"); err != nil { return err } if err := rw.Flush(); err != nil { return err } line, err := rw.ReadSlice('\n') if err != nil { return err } switch { case bytes.HasPrefix(line, versionPrefix): break default: return fmt.Errorf("memcache: unexpected response line from ping: %q", string(line)) } return nil }) } func (c *Client) touchFromAddr(addr net.Addr, keys []string, expiration int32) error { return c.withAddrRw(addr, func(conn *conn) error { rw := conn.rw for _, key := range keys { if _, err := fmt.Fprintf(rw, "touch %s %d\r\n", key, expiration); err != nil { return err } if err := rw.Flush(); err != nil { return err } line, err := rw.ReadSlice('\n') if err != nil { return err } switch { case bytes.Equal(line, resultTouched): break case bytes.Equal(line, resultNotFound): return ErrCacheMiss default: return fmt.Errorf("memcache: unexpected response line from touch: %q", string(line)) } } return nil }) } // GetMulti is a batch version of Get. The returned map from keys to // items may have fewer elements than the input slice, due to memcache // cache misses. Each key must be at most 250 bytes in length. // If no error is returned, the returned map will also be non-nil. func (c *Client) GetMulti(keys []string, opts ...Option) (map[string]*Item, error) { options := newOptions(opts...) var lk sync.Mutex m := make(map[string]*Item, len(keys)) addItemToMap := func(it *Item) { lk.Lock() defer lk.Unlock() m[it.Key] = it } keyMap := make(map[net.Addr][]string) for _, key := range keys { if !legalKey(key) { return nil, ErrMalformedKey } addr, err := c.selector.PickServer(key) if err != nil { return nil, err } keyMap[addr] = append(keyMap[addr], key) } ch := make(chan error, buffered) for addr, keys := range keyMap { go func(addr net.Addr, keys []string) { err := c.getFromAddr(addr, keys, options, addItemToMap) ch <- err }(addr, keys) } var err error for range keyMap { if ge := <-ch; ge != nil { err = ge } } return m, err } // parseGetResponse reads a GET response from r and calls cb for each // read and allocated Item func (c *Client) parseGetResponse(r *bufio.Reader, conn *conn, opts *Options, cb func(*Item)) error { for { // extend deadline before each additional call, otherwise all cumulative calls use the same overall deadline conn.extendDeadline() line, err := r.ReadSlice('\n') if err != nil { return err } if bytes.Equal(line, resultEnd) { return nil } it := new(Item) size, err := scanGetResponseLine(line, it) if err != nil { return err } buffSize := size + 2 buff := opts.Alloc.Get(buffSize) it.Value = (*buff)[:buffSize] _, err = io.ReadFull(r, it.Value) if err != nil { opts.Alloc.Put(buff) return err } if !bytes.HasSuffix(it.Value, crlf) { opts.Alloc.Put(buff) return fmt.Errorf("memcache: corrupt get result read") } it.Value = it.Value[:size] cb(it) } } // scanGetResponseLine populates it and returns the declared size of the item. // It does not read the bytes of the item. func scanGetResponseLine(line []byte, it *Item) (size int, err error) { errf := func(line []byte) (int, error) { return -1, fmt.Errorf("memcache: unexpected line in get response: %q", line) } if !bytes.HasPrefix(line, valuePrefix) || !bytes.HasSuffix(line, []byte("\r\n")) { return errf(line) } s := string(line[6 : len(line)-2]) var rest string var found bool it.Key, rest, found = cut(s, ' ') if !found { return errf(line) } val, rest, found := cut(rest, ' ') if !found { return errf(line) } flags64, err := strconv.ParseUint(val, 10, 32) if err != nil { return errf(line) } it.Flags = uint32(flags64) val, rest, found = cut(rest, ' ') size64, err := strconv.ParseUint(val, 10, 32) if err != nil { return errf(line) } if !found { // final CAS ID is optional. return int(size64), nil } it.casid, err = strconv.ParseUint(rest, 10, 64) if err != nil { return errf(line) } return int(size64), nil } // Similar to strings.Cut in Go 1.18, but sep can only be 1 byte. func cut(s string, sep byte) (before, after string, found bool) { if i := strings.IndexByte(s, sep); i >= 0 { return s[:i], s[i+1:], true } return s, "", false } // Set writes the given item, unconditionally. func (c *Client) Set(item *Item) error { return c.onItem(item, (*Client).set) } func (c *Client) set(rw *bufio.ReadWriter, item *Item) error { return c.populateOne(rw, "set", item) } // Add writes the given item, if no value already exists for its // key. ErrNotStored is returned if that condition is not met. func (c *Client) Add(item *Item) error { return c.onItem(item, (*Client).add) } func (c *Client) add(rw *bufio.ReadWriter, item *Item) error { return c.populateOne(rw, "add", item) } // Replace writes the given item, but only if the server *does* // already hold data for this key func (c *Client) Replace(item *Item) error { return c.onItem(item, (*Client).replace) } func (c *Client) replace(rw *bufio.ReadWriter, item *Item) error { return c.populateOne(rw, "replace", item) } // CompareAndSwap writes the given item that was previously returned // by Get, if the value was neither modified or evicted between the // Get and the CompareAndSwap calls. The item's Key should not change // between calls but all other item fields may differ. ErrCASConflict // is returned if the value was modified in between the // calls. ErrNotStored is returned if the value was evicted in between // the calls. func (c *Client) CompareAndSwap(item *Item) error { return c.onItem(item, (*Client).cas) } func (c *Client) cas(rw *bufio.ReadWriter, item *Item) error { return c.populateOne(rw, "cas", item) } func (c *Client) populateOne(rw *bufio.ReadWriter, verb string, item *Item) error { if !legalKey(item.Key) { return ErrMalformedKey } var err error if verb == "cas" { _, err = fmt.Fprintf(rw, "%s %s %d %d %d %d\r\n", verb, item.Key, item.Flags, item.Expiration, len(item.Value), item.casid) } else { _, err = fmt.Fprintf(rw, "%s %s %d %d %d\r\n", verb, item.Key, item.Flags, item.Expiration, len(item.Value)) } if err != nil { return err } if _, err = rw.Write(item.Value); err != nil { return err } if _, err := rw.Write(crlf); err != nil { return err } if err := rw.Flush(); err != nil { return err } line, err := rw.ReadSlice('\n') if err != nil { return err } switch { case bytes.Equal(line, resultStored): return nil case bytes.Equal(line, resultNotStored): return ErrNotStored case bytes.Equal(line, resultExists): return ErrCASConflict case bytes.Equal(line, resultNotFound): return ErrCacheMiss } return fmt.Errorf("memcache: unexpected response line from %q: %q", verb, string(line)) } func writeReadLine(rw *bufio.ReadWriter, format string, args ...interface{}) ([]byte, error) { _, err := fmt.Fprintf(rw, format, args...) if err != nil { return nil, err } if err := rw.Flush(); err != nil { return nil, err } line, err := rw.ReadSlice('\n') return line, err } func writeExpectf(rw *bufio.ReadWriter, expect []byte, format string, args ...interface{}) error { line, err := writeReadLine(rw, format, args...) if err != nil { return err } switch { case bytes.Equal(line, resultOK): return nil case bytes.Equal(line, expect): return nil case bytes.Equal(line, resultNotStored): return ErrNotStored case bytes.Equal(line, resultExists): return ErrCASConflict case bytes.Equal(line, resultNotFound): return ErrCacheMiss } return fmt.Errorf("memcache: unexpected response line: %q", string(line)) } // Delete deletes the item with the provided key. The error ErrCacheMiss is // returned if the item didn't already exist in the cache. func (c *Client) Delete(key string) error { return c.withKeyRw(key, func(conn *conn) error { return writeExpectf(conn.rw, resultDeleted, "delete %s\r\n", key) }) } // DeleteAll deletes all items in the cache. func (c *Client) DeleteAll() error { return c.withKeyRw("", func(conn *conn) error { return writeExpectf(conn.rw, resultDeleted, "flush_all\r\n") }) } // Ping checks all instances if they are alive. Returns error if any // of them is down. func (c *Client) Ping() error { return c.selector.Each(c.ping) } // Increment atomically increments key by delta. The return value is // the new value after being incremented or an error. If the value // didn't exist in memcached the error is ErrCacheMiss. The value in // memcached must be an decimal number, or an error will be returned. // On 64-bit overflow, the new value wraps around. func (c *Client) Increment(key string, delta uint64) (newValue uint64, err error) { return c.incrDecr("incr", key, delta) } // Decrement atomically decrements key by delta. The return value is // the new value after being decremented or an error. If the value // didn't exist in memcached the error is ErrCacheMiss. The value in // memcached must be an decimal number, or an error will be returned. // On underflow, the new value is capped at zero and does not wrap // around. func (c *Client) Decrement(key string, delta uint64) (newValue uint64, err error) { return c.incrDecr("decr", key, delta) } func (c *Client) incrDecr(verb, key string, delta uint64) (uint64, error) { var val uint64 err := c.withKeyRw(key, func(conn *conn) error { rw := conn.rw line, err := writeReadLine(rw, "%s %s %d\r\n", verb, key, delta) if err != nil { return err } switch { case bytes.Equal(line, resultNotFound): return ErrCacheMiss case bytes.HasPrefix(line, resultClientErrorPrefix): errMsg := line[len(resultClientErrorPrefix) : len(line)-2] return errors.New("memcache: client error: " + string(errMsg)) } val, err = strconv.ParseUint(string(line[:len(line)-2]), 10, 64) if err != nil { return err } return nil }) return val, err } // backgroundReconnect makes an asyncronous attempt to reconnect to the provided server list and reset all open connections func (c *Client) backgroundReconnect() { go func() { c.reconnectLock.Lock() defer c.reconnectLock.Unlock() if sl, ok := c.selector.(*ServerList); ok { if err := sl.SetServers(c.serverList...); err == nil { c.lk.Lock() defer c.lk.Unlock() // close all open connections before deleting them for _, cs := range c.freeconn { for _, conn := range cs { conn.nc.Close() } } c.freeconn = make(map[string][]*conn) } } }() } golang-github-grafana-gomemcache-0.0~git20240805.fdaf6a9/memcache/memcache_test.go000066400000000000000000000432271465576071400274520ustar00rootroot00000000000000/* Copyright 2011 Google Inc. 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. */ // Package memcache provides a client for the memcached cache server. package memcache import ( "bufio" "fmt" "io" "net" "os" "os/exec" "path" "strings" "sync" "testing" "time" ) const testServer = "localhost:11211" func setup(t *testing.T) bool { c, err := net.Dial("tcp", testServer) if err != nil { t.Skipf("skipping test; no server running at %s", testServer) } _, _ = c.Write([]byte("flush_all\r\n")) c.Close() return true } func TestLocalhost(t *testing.T) { if !setup(t) { return } c := New(testServer) t.Cleanup(c.Close) testWithClient(t, c) } // Run the memcached binary as a child process and connect to its unix socket. func TestUnixSocket(t *testing.T) { sock := path.Join(t.TempDir(), fmt.Sprintf("test-gomemcache-%d.sock", os.Getpid())) cmd := exec.Command("memcached", "-s", sock) if err := cmd.Start(); err != nil { t.Skipf("skipping test; couldn't find memcached") return } defer func() { _ = cmd.Process.Kill() _ = cmd.Wait() }() // Wait a bit for the socket to appear. for i := 0; i < 10; i++ { if _, err := os.Stat(sock); err == nil { break } time.Sleep(time.Duration(25*i) * time.Millisecond) } c := New(sock) t.Cleanup(c.Close) testWithClient(t, c) } func mustSetF(t *testing.T, c *Client) func(*Item) { return func(it *Item) { if err := c.Set(it); err != nil { t.Fatalf("failed to Set %#v: %v", *it, err) } } } func testWithClient(t *testing.T, c *Client) { checkErr := func(err error, format string, args ...interface{}) { if err != nil { t.Fatalf(format, args...) } } mustSet := mustSetF(t, c) t.Run("get and set", func(t *testing.T) { foo := &Item{Key: "foo", Value: []byte("fooval"), Flags: 123} err := c.Set(foo) checkErr(err, "first set(foo): %v", err) err = c.Set(foo) checkErr(err, "second set(foo): %v", err) it, err := c.Get("foo") checkErr(err, "get(foo): %v", err) if it.Key != "foo" { t.Errorf("get(foo) Key = %q, want foo", it.Key) } if string(it.Value) != "fooval" { t.Errorf("get(foo) Value = %q, want fooval", string(it.Value)) } if it.Flags != 123 { t.Errorf("get(foo) Flags = %v, want 123", it.Flags) } }) t.Run("get and set unicode key", func(t *testing.T) { quxKey := "Hello_世界" qux := &Item{Key: quxKey, Value: []byte("hello world")} err := c.Set(qux) checkErr(err, "first set(Hello_世界): %v", err) it, err := c.Get(quxKey) checkErr(err, "get(Hello_世界): %v", err) if it.Key != quxKey { t.Errorf("get(Hello_世界) Key = %q, want Hello_世界", it.Key) } if string(it.Value) != "hello world" { t.Errorf("get(Hello_世界) Value = %q, want hello world", string(it.Value)) } }) t.Run("set malformed keys", func(t *testing.T) { malFormed := &Item{Key: "foo bar", Value: []byte("foobarval")} err := c.Set(malFormed) if err != ErrMalformedKey { t.Errorf("set(foo bar) should return ErrMalformedKey instead of %v", err) } malFormed = &Item{Key: "foo" + string(rune(0x7f)), Value: []byte("foobarval")} err = c.Set(malFormed) if err != ErrMalformedKey { t.Errorf("set(foo<0x7f>) should return ErrMalformedKey instead of %v", err) } }) t.Run("add", func(t *testing.T) { bar := &Item{Key: "bar", Value: []byte("barval")} err := c.Add(bar) checkErr(err, "first add(foo): %v", err) if err := c.Add(bar); err != ErrNotStored { t.Fatalf("second add(foo) want ErrNotStored, got %v", err) } }) t.Run("replace", func(t *testing.T) { baz := &Item{Key: "baz", Value: []byte("bazvalue")} if err := c.Replace(baz); err != ErrNotStored { t.Fatalf("expected replace(baz) to return ErrNotStored, got %v", err) } bar := &Item{Key: "bar", Value: []byte("barval")} err := c.Replace(bar) checkErr(err, "replaced(foo): %v", err) }) t.Run("getmulti", func(t *testing.T) { m, err := c.GetMulti([]string{"foo", "bar"}) checkErr(err, "GetMulti: %v", err) if g, e := len(m), 2; g != e { t.Errorf("GetMulti: got len(map) = %d, want = %d", g, e) } if _, ok := m["foo"]; !ok { t.Fatalf("GetMulti: didn't get key 'foo'") } if _, ok := m["bar"]; !ok { t.Fatalf("GetMulti: didn't get key 'bar'") } if g, e := string(m["foo"].Value), "fooval"; g != e { t.Errorf("GetMulti: foo: got %q, want %q", g, e) } if g, e := string(m["bar"].Value), "barval"; g != e { t.Errorf("GetMulti: bar: got %q, want %q", g, e) } }) t.Run("delete", func(t *testing.T) { err := c.Delete("foo") checkErr(err, "Delete: %v", err) _, err = c.Get("foo") if err != ErrCacheMiss { t.Errorf("post-Delete want ErrCacheMiss, got %v", err) } }) t.Run("incr decr", func(t *testing.T) { mustSet(&Item{Key: "num", Value: []byte("42")}) n, err := c.Increment("num", 8) checkErr(err, "Increment num + 8: %v", err) if n != 50 { t.Fatalf("Increment num + 8: want=50, got=%d", n) } n, err = c.Decrement("num", 49) checkErr(err, "Decrement: %v", err) if n != 1 { t.Fatalf("Decrement 49: want=1, got=%d", n) } err = c.Delete("num") checkErr(err, "delete num: %v", err) _, err = c.Increment("num", 1) if err != ErrCacheMiss { t.Fatalf("increment post-delete: want ErrCacheMiss, got %v", err) } mustSet(&Item{Key: "num", Value: []byte("not-numeric")}) _, err = c.Increment("num", 1) if err == nil || !strings.Contains(err.Error(), "client error") { t.Fatalf("increment non-number: want client error, got %v", err) } }) t.Run("delete all", func(t *testing.T) { err := c.DeleteAll() checkErr(err, "DeleteAll: %v", err) _, err = c.Get("bar") if err != ErrCacheMiss { t.Errorf("post-DeleteAll want ErrCacheMiss, got %v", err) } }) t.Run("ping", func(t *testing.T) { err := c.Ping() checkErr(err, "error ping: %s", err) }) t.Run("touch", func(t *testing.T) { testTouchWithClient(t, c) }) t.Run("get with allocator", func(t *testing.T) { foo := &Item{Key: "foo", Value: []byte("fooval"), Flags: 123} err := c.Set(foo) checkErr(err, "first set(foo): %v", err) alloc := newTestAllocator(len(foo.Value) + 2) it, err := c.Get("foo", WithAllocator(alloc)) checkErr(err, "get(foo): %v", err) t.Cleanup(func() { alloc.Put(&it.Value) }) if it.Key != "foo" { t.Errorf("get(foo) Key = %q, want foo", it.Key) } if string(it.Value) != "fooval" { t.Errorf("get(foo) Value = %q, want fooval", string(it.Value)) } if alloc.numGets != 1 { t.Errorf("get(foo) num gets from Allocator = %d, want 1", alloc.numGets) } }) } func testTouchWithClient(t *testing.T, c *Client) { mustSet := mustSetF(t, c) const secondsToExpiry = int32(2) // We will set foo and bar to expire in 2 seconds, then we'll keep touching // foo every second // After 3 seconds, we expect foo to be available, and bar to be expired foo := &Item{Key: "foo", Value: []byte("fooval"), Expiration: secondsToExpiry} bar := &Item{Key: "bar", Value: []byte("barval"), Expiration: secondsToExpiry} setTime := time.Now() mustSet(foo) mustSet(bar) for s := 0; s < 3; s++ { time.Sleep(1 * time.Second) err := c.Touch(foo.Key, secondsToExpiry) if nil != err { t.Errorf("error touching foo: %v", err.Error()) } } _, err := c.Get("foo") if err != nil { if err == ErrCacheMiss { t.Fatalf("touching failed to keep item foo alive") } else { t.Fatalf("unexpected error retrieving foo after touching: %v", err.Error()) } } _, err = c.Get("bar") if nil == err { t.Fatalf("item bar did not expire within %v seconds", time.Since(setTime).Seconds()) } else { if err != ErrCacheMiss { t.Fatalf("unexpected error retrieving bar: %v", err.Error()) } } } func TestClient_releaseIdleConnections(t *testing.T) { const recentlyUsedThreshold = 2 * time.Second getClientWithMinIdleConnsHeadroomPercentage := func(t *testing.T, headroomPercentage float64) *Client { c := New(testServer) t.Cleanup(c.Close) c.MinIdleConnsHeadroomPercentage = headroomPercentage c.MaxIdleConns = 100 c.recentlyUsedConnsThreshold = recentlyUsedThreshold return c } getConn := func(c *Client) *conn { addr, err := c.selector.PickServer("test") if err != nil { t.Fatalf("unexpected error picking server: %v", err.Error()) } connection, err := c.getConn(addr) if err != nil { t.Fatalf("unexpected error getting connection: %v", err.Error()) } return connection } countFreeConns := func(c *Client) (recentlyUsed, idle int) { c.lk.Lock() defer c.lk.Unlock() for _, freeConnections := range c.freeconn { for _, freeConn := range freeConnections { if time.Since(freeConn.idleSince) >= c.recentlyUsedConnsThreshold { idle++ } else { recentlyUsed++ } } } return } t.Run("noop if there are no free connections", func(t *testing.T) { c := getClientWithMinIdleConnsHeadroomPercentage(t, 50) c.releaseIdleConnections() numRecentlyUsed, numIdle := countFreeConns(c) if numRecentlyUsed != 0 { t.Fatalf("expected %d recently used connections but got %d", 0, numRecentlyUsed) } if numIdle != 0 { t.Fatalf("expected %d idle connections but got %d", 0, numIdle) } }) t.Run("should not release recently used connections", func(t *testing.T) { c := getClientWithMinIdleConnsHeadroomPercentage(t, 50) conn1 := getConn(c) conn2 := getConn(c) conn1.release() conn2.release() c.releaseIdleConnections() numRecentlyUsed, numIdle := countFreeConns(c) if numRecentlyUsed != 2 { t.Fatalf("expected %d recently used connections but got %d", 2, numRecentlyUsed) } if numIdle != 0 { t.Fatalf("expected %d idle connections but got %d", 0, numIdle) } }) t.Run("should release idle connections while honoring the configured headroom", func(t *testing.T) { c := getClientWithMinIdleConnsHeadroomPercentage(t, 50) conn1 := getConn(c) conn2 := getConn(c) conn3 := getConn(c) conn4 := getConn(c) conn1.release() conn2.release() time.Sleep(recentlyUsedThreshold) conn3.release() conn4.release() c.releaseIdleConnections() numRecentlyUsed, numIdle := countFreeConns(c) if numRecentlyUsed != 2 { t.Fatalf("expected %d recently used connections but got %d", 2, numRecentlyUsed) } if numIdle != 1 { t.Fatalf("expected %d idle connections but got %d", 1, numIdle) } }) t.Run("should release all idle connections if headroom is zero", func(t *testing.T) { c := getClientWithMinIdleConnsHeadroomPercentage(t, 0) conn1 := getConn(c) conn2 := getConn(c) conn3 := getConn(c) conn4 := getConn(c) conn1.release() conn2.release() time.Sleep(recentlyUsedThreshold) conn3.release() conn4.release() c.releaseIdleConnections() numRecentlyUsed, numIdle := countFreeConns(c) if numRecentlyUsed != 2 { t.Fatalf("expected %d recently used connections but got %d", 2, numRecentlyUsed) } if numIdle != 0 { t.Fatalf("expected %d idle connections but got %d", 0, numIdle) } }) t.Run("should not release idle connections if headroom is disabled (negative value)", func(t *testing.T) { c := getClientWithMinIdleConnsHeadroomPercentage(t, -1) conn1 := getConn(c) conn2 := getConn(c) conn3 := getConn(c) conn4 := getConn(c) conn1.release() conn2.release() time.Sleep(recentlyUsedThreshold) conn3.release() conn4.release() c.releaseIdleConnections() numRecentlyUsed, numIdle := countFreeConns(c) if numRecentlyUsed != 2 { t.Fatalf("expected %d recently used connections but got %d", 2, numRecentlyUsed) } if numIdle != 2 { t.Fatalf("expected %d idle connections but got %d", 2, numIdle) } }) t.Run("should not release idle connections if headroom is 100%", func(t *testing.T) { c := getClientWithMinIdleConnsHeadroomPercentage(t, 100) conn1 := getConn(c) conn2 := getConn(c) conn3 := getConn(c) conn4 := getConn(c) conn1.release() conn2.release() time.Sleep(recentlyUsedThreshold) conn3.release() conn4.release() c.releaseIdleConnections() numRecentlyUsed, numIdle := countFreeConns(c) if numRecentlyUsed != 2 { t.Fatalf("expected %d recently used connections but got %d", 2, numRecentlyUsed) } if numIdle != 2 { t.Fatalf("expected %d idle connections but got %d", 2, numIdle) } }) t.Run("should allow to set an headroom percentage > 100%", func(t *testing.T) { c := getClientWithMinIdleConnsHeadroomPercentage(t, 200) conn1 := getConn(c) conn2 := getConn(c) conn3 := getConn(c) conn4 := getConn(c) conn1.release() conn2.release() conn3.release() time.Sleep(recentlyUsedThreshold) conn4.release() c.releaseIdleConnections() numRecentlyUsed, numIdle := countFreeConns(c) if numRecentlyUsed != 1 { t.Fatalf("expected %d recently used connections but got %d", 1, numRecentlyUsed) } if numIdle != 2 { t.Fatalf("expected %d idle connections but got %d", 2, numIdle) } }) t.Run("should keep all idle connections open if the computed headroom is greater than the number of available free connections", func(t *testing.T) { c := getClientWithMinIdleConnsHeadroomPercentage(t, 1000) conn1 := getConn(c) conn2 := getConn(c) conn3 := getConn(c) conn4 := getConn(c) conn1.release() conn2.release() conn3.release() time.Sleep(recentlyUsedThreshold) conn4.release() c.releaseIdleConnections() numRecentlyUsed, numIdle := countFreeConns(c) if numRecentlyUsed != 1 { t.Fatalf("expected %d recently used connections but got %d", 1, numRecentlyUsed) } if numIdle != 3 { t.Fatalf("expected %d idle connections but got %d", 3, numIdle) } }) } func TestClient_Close_ShouldBeIdempotent(t *testing.T) { c := New(testServer) // Call Close twice and make sure it doesn't panic the 2nd time. c.Close() c.Close() } func TestClientReconnectsOnTimeout(t *testing.T) { if !setup(t) { return } c := New(testServer) c.Timeout = 100 * time.Second t.Cleanup(c.Close) // should be able to ping if err := c.Ping(); err != nil { t.Fatalf("expected no error but received %s", err.Error()) } // break the connection tcpaddr, err := net.ResolveTCPAddr("tcp", "192.0.2.0:11211") if err != nil { t.Fatalf("expected no error but received %s", err.Error()) } c.selector.(*ServerList).addrs[0] = newStaticAddr(tcpaddr) // ping should fail if err := c.Ping(); err == nil { t.Fatalf("expected an error but received none") } // ping should succeed again after the client reconnects in the background time.Sleep(500 * time.Millisecond) if err := c.Ping(); err != nil { t.Fatalf("expected no error but received %s", err.Error()) } // verify server address was reset if addr := c.selector.(*ServerList).addrs[0].String(); "127.0.0.1:11211" != addr { t.Fatalf("expected address '127.0.0.1:11211' but got '%s'", addr) } } func BenchmarkGetMulti(b *testing.B) { c := New(testServer) defer c.Close() var keys []string for i := 0; i < 100; i++ { key := fmt.Sprintf("bench-%d", i) keys = append(keys, key) err := c.Set(&Item{ Key: key, Value: []byte(strings.Repeat("bench payload", 10)), Flags: 0, Expiration: 30, casid: 0, }) if err != nil { b.Fatal("Could not set item for test server: ", err) } } b.ResetTimer() for i := 0; i < b.N; i++ { _, _ = c.GetMulti(keys) } } func BenchmarkOnItem(b *testing.B) { fakeServer, err := net.Listen("tcp", "localhost:0") if err != nil { b.Fatal("Could not open fake server: ", err) } defer fakeServer.Close() go func() { for { if c, err := fakeServer.Accept(); err == nil { go func() { _, _ = io.Copy(io.Discard, c) }() } else { return } } }() addr := fakeServer.Addr() c := New(addr.String()) b.Cleanup(c.Close) if _, err := c.getConn(addr); err != nil { b.Fatal("failed to initialize connection to fake server") } item := Item{Key: "foo"} dummyFn := func(_ *Client, _ *bufio.ReadWriter, _ *Item) error { return nil } b.ResetTimer() for i := 0; i < b.N; i++ { _ = c.onItem(&item, dummyFn) } } func BenchmarkScanGetResponseLine(b *testing.B) { line := []byte("VALUE foobar1234 0 4096 1234\r\n") var it Item for i := 0; i < b.N; i++ { _, err := scanGetResponseLine(line, &it) if err != nil { b.Fatal(err) } } } func BenchmarkParseGetResponse(b *testing.B) { valueSize := 500 response := strings.NewReader(fmt.Sprintf("VALUE foobar1234 0 %v 1234\r\n%s\r\nEND\r\n", valueSize, strings.Repeat("a", valueSize))) opts := newOptions(WithAllocator(newTestAllocator(valueSize + 2))) c := &Client{} reader := bufio.NewReader(response) addr, err := net.ResolveTCPAddr("tcp", testServer) if err != nil { b.Fatalf("failed to resolve address %q: %q", testServer, err) } cn, err := c.getConn(addr) if err != nil { b.Fatalf("failed to get connection: %q", err) } for i := 0; i < b.N; i++ { err := c.parseGetResponse(reader, cn, opts, func(it *Item) { opts.Alloc.Put(&it.Value) }) if err != nil { b.Fatal(err) } _, err = response.Seek(0, 0) if err != nil { b.Fatal(err) } reader.Reset(response) } } type testAllocator struct { pool sync.Pool maxSize int numGets int numPuts int } func newTestAllocator(maxSize int) *testAllocator { return &testAllocator{ maxSize: maxSize, pool: sync.Pool{ New: func() interface{} { b := make([]byte, maxSize) return &b }, }, } } func (p *testAllocator) Get(sz int) *[]byte { if sz > p.maxSize { panic("unexpected allocation size in test allocator") } p.numGets += 1 bufPtr := p.pool.Get().(*[]byte) return bufPtr } func (p *testAllocator) Put(b *[]byte) { p.numPuts += 1 p.pool.Put(b) } golang-github-grafana-gomemcache-0.0~git20240805.fdaf6a9/memcache/options.go000066400000000000000000000033231465576071400263350ustar00rootroot00000000000000package memcache var nopAllocator = &defaultAllocator{} func newOptions(opts ...Option) *Options { o := &Options{ Alloc: nopAllocator, } for _, opt := range opts { opt(o) } return o } // Options are used to modify the behavior of an individual Get or GetMulti // call made by the Client. They are constructed by applying Option callbacks // passed to a Client method to a default Options instance. type Options struct { Alloc Allocator } // Option is a callback used to modify the Options that a particular Client // method uses. type Option func(opts *Options) // WithAllocator creates a new Option that makes use of a specific memory Allocator // for result values (Item.Value) loaded from memcached. func WithAllocator(alloc Allocator) Option { return func(opts *Options) { opts.Alloc = alloc } } // Allocator allows memory for memcached result values (Item.Value) to be managed by // callers of the Client instead of by the Client itself. For example, this can be // used by callers to implement arena-style memory management. The default implementation // used, when not otherwise overridden, uses `make` and relies on GC for cleanup. type Allocator interface { // Get returns a byte slice with at least sz capacity. Length of the slice is // not guaranteed and so must be asserted by callers (the Client). Get(sz int) *[]byte // Put returns the byte slice to the underlying allocator. The Client will // only call this method during error handling when allocated values are not // returned to the caller as cache results. Put(b *[]byte) } type defaultAllocator struct{} func (d defaultAllocator) Get(sz int) *[]byte { b := make([]byte, sz) return &b } func (d defaultAllocator) Put(_ *[]byte) { // no-op } golang-github-grafana-gomemcache-0.0~git20240805.fdaf6a9/memcache/selector.go000066400000000000000000000064461465576071400264730ustar00rootroot00000000000000/* Copyright 2011 Google Inc. 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. */ package memcache import ( "hash/crc32" "net" "strings" "sync" ) // ServerSelector is the interface that selects a memcache server // as a function of the item's key. // // All ServerSelector implementations must be safe for concurrent use // by multiple goroutines. type ServerSelector interface { // PickServer returns the server address that a given item // should be shared onto. PickServer(key string) (net.Addr, error) Each(func(net.Addr) error) error } // ServerList is a simple ServerSelector. Its zero value is usable. type ServerList struct { mu sync.RWMutex addrs []net.Addr } // staticAddr caches the Network() and String() values from any net.Addr. type staticAddr struct { ntw, str string } func newStaticAddr(a net.Addr) net.Addr { return &staticAddr{ ntw: a.Network(), str: a.String(), } } func (s *staticAddr) Network() string { return s.ntw } func (s *staticAddr) String() string { return s.str } // SetServers changes a ServerList's set of servers at runtime and is // safe for concurrent use by multiple goroutines. // // Each server is given equal weight. A server is given more weight // if it's listed multiple times. // // SetServers returns an error if any of the server names fail to // resolve. No attempt is made to connect to the server. If any error // is returned, no changes are made to the ServerList. func (ss *ServerList) SetServers(servers ...string) error { naddr := make([]net.Addr, len(servers)) for i, server := range servers { if strings.Contains(server, "/") { addr, err := net.ResolveUnixAddr("unix", server) if err != nil { return err } naddr[i] = newStaticAddr(addr) } else { tcpaddr, err := net.ResolveTCPAddr("tcp", server) if err != nil { return err } naddr[i] = newStaticAddr(tcpaddr) } } ss.mu.Lock() defer ss.mu.Unlock() ss.addrs = naddr return nil } // Each iterates over each server calling the given function func (ss *ServerList) Each(f func(net.Addr) error) error { ss.mu.RLock() defer ss.mu.RUnlock() for _, a := range ss.addrs { if err := f(a); nil != err { return err } } return nil } // keyBufPool returns []byte buffers for use by PickServer's call to // crc32.ChecksumIEEE to avoid allocations. (but doesn't avoid the // copies, which at least are bounded in size and small) var keyBufPool = sync.Pool{ New: func() interface{} { b := make([]byte, 256) return &b }, } func (ss *ServerList) PickServer(key string) (net.Addr, error) { ss.mu.RLock() defer ss.mu.RUnlock() if len(ss.addrs) == 0 { return nil, ErrNoServers } if len(ss.addrs) == 1 { return ss.addrs[0], nil } bufp := keyBufPool.Get().(*[]byte) n := copy(*bufp, key) cs := crc32.ChecksumIEEE((*bufp)[:n]) keyBufPool.Put(bufp) return ss.addrs[cs%uint32(len(ss.addrs))], nil } golang-github-grafana-gomemcache-0.0~git20240805.fdaf6a9/memcache/selector_test.go000066400000000000000000000020521465576071400275170ustar00rootroot00000000000000/* Copyright 2014 Google Inc. 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. */ package memcache import "testing" func BenchmarkPickServer(b *testing.B) { // at least two to avoid 0 and 1 special cases: benchPickServer(b, "127.0.0.1:1234", "127.0.0.1:1235") } func BenchmarkPickServer_Single(b *testing.B) { benchPickServer(b, "127.0.0.1:1234") } func benchPickServer(b *testing.B, servers ...string) { b.ReportAllocs() var ss ServerList _ = ss.SetServers(servers...) for i := 0; i < b.N; i++ { if _, err := ss.PickServer("some key"); err != nil { b.Fatal(err) } } }