update vendor
This commit is contained in:
parent
60665244b3
commit
d94a69e883
|
|
@ -73,12 +73,6 @@
|
|||
revision = "925541529c1fa6821df4e44ce2723319eb2be768"
|
||||
version = "v1.0.0"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/google/btree"
|
||||
packages = ["."]
|
||||
revision = "316fb6d3f031ae8f4d457c6c5186b9e3ded70435"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/google/gofuzz"
|
||||
|
|
@ -91,18 +85,6 @@
|
|||
revision = "ee43cbb60db7bd22502942cccbc39059117352ab"
|
||||
version = "v0.1.0"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/gregjones/httpcache"
|
||||
packages = [".","diskcache"]
|
||||
revision = "2bcd89a1743fd4b373f7370ce8ddc14dfbd18229"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/howeyc/gopass"
|
||||
packages = ["."]
|
||||
revision = "bf9dde6d0d2c004a008c27aaee91170c786f6db8"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/imdario/mergo"
|
||||
packages = ["."]
|
||||
|
|
@ -121,12 +103,6 @@
|
|||
revision = "f7279a603edee96fe7764d3de9c6ff8cf9970994"
|
||||
version = "1.0.4"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/juju/ratelimit"
|
||||
packages = ["."]
|
||||
revision = "59fac5042749a5afb9af70e813da1dd5474f0167"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/mailru/easyjson"
|
||||
|
|
@ -145,18 +121,6 @@
|
|||
revision = "c893efa28eb45626cdaa76c9f653b62488858837"
|
||||
version = "v1.2.0"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/petar/GoLLRB"
|
||||
packages = ["llrb"]
|
||||
revision = "53be0d36a84c2a886ca057d34b6aa4468df9ccb4"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/peterbourgon/diskv"
|
||||
packages = ["."]
|
||||
revision = "5f041e8faa004a95c88a202771f4cc3e991971e6"
|
||||
version = "v2.0.1"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/spf13/cobra"
|
||||
packages = ["."]
|
||||
|
|
@ -178,7 +142,7 @@
|
|||
[[projects]]
|
||||
branch = "master"
|
||||
name = "golang.org/x/net"
|
||||
packages = ["html","html/atom","html/charset","http2","http2/hpack","idna","lex/httplex"]
|
||||
packages = ["context","html","html/atom","html/charset","http2","http2/hpack","idna","lex/httplex"]
|
||||
revision = "a337091b0525af65de94df2eb7e98bd9962dcbe2"
|
||||
|
||||
[[projects]]
|
||||
|
|
@ -193,6 +157,12 @@
|
|||
packages = ["collate","collate/build","encoding","encoding/charmap","encoding/htmlindex","encoding/internal","encoding/internal/identifier","encoding/japanese","encoding/korean","encoding/simplifiedchinese","encoding/traditionalchinese","encoding/unicode","internal/colltab","internal/gen","internal/tag","internal/triegen","internal/ucd","internal/utf8internal","language","runes","secure/bidirule","transform","unicode/bidi","unicode/cldr","unicode/norm","unicode/rangetable","width"]
|
||||
revision = "88f656faf3f37f690df1a32515b479415e1a6769"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "golang.org/x/time"
|
||||
packages = ["rate"]
|
||||
revision = "26559e0f760e39c24d730d3224364aef164ee23f"
|
||||
|
||||
[[projects]]
|
||||
name = "gopkg.in/inf.v0"
|
||||
packages = ["."]
|
||||
|
|
@ -209,19 +179,19 @@
|
|||
branch = "master"
|
||||
name = "k8s.io/api"
|
||||
packages = ["admissionregistration/v1alpha1","admissionregistration/v1beta1","apps/v1","apps/v1beta1","apps/v1beta2","authentication/v1","authentication/v1beta1","authorization/v1","authorization/v1beta1","autoscaling/v1","autoscaling/v2beta1","batch/v1","batch/v1beta1","batch/v2alpha1","certificates/v1beta1","core/v1","events/v1beta1","extensions/v1beta1","networking/v1","policy/v1beta1","rbac/v1","rbac/v1alpha1","rbac/v1beta1","scheduling/v1alpha1","settings/v1alpha1","storage/v1","storage/v1alpha1","storage/v1beta1"]
|
||||
revision = "9382f5a87a364c195477134986b578d103c7c24d"
|
||||
revision = "847e24b2c0e587a6a097d187ebd72e1ca24de001"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "k8s.io/apimachinery"
|
||||
packages = ["pkg/api/errors","pkg/api/meta","pkg/api/resource","pkg/apis/meta/v1","pkg/apis/meta/v1/unstructured","pkg/apis/meta/v1beta1","pkg/conversion","pkg/conversion/queryparams","pkg/fields","pkg/labels","pkg/runtime","pkg/runtime/schema","pkg/runtime/serializer","pkg/runtime/serializer/json","pkg/runtime/serializer/protobuf","pkg/runtime/serializer/recognizer","pkg/runtime/serializer/streaming","pkg/runtime/serializer/versioning","pkg/selection","pkg/types","pkg/util/clock","pkg/util/errors","pkg/util/framer","pkg/util/intstr","pkg/util/json","pkg/util/mergepatch","pkg/util/net","pkg/util/runtime","pkg/util/sets","pkg/util/strategicpatch","pkg/util/validation","pkg/util/validation/field","pkg/util/wait","pkg/util/yaml","pkg/version","pkg/watch","third_party/forked/golang/json","third_party/forked/golang/reflect"]
|
||||
revision = "cd2cae2b39fa57e8063fa1f5f13cfe9862db3d41"
|
||||
revision = "895b82eadff27f5a6b19d80628a04645823c1e46"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "k8s.io/client-go"
|
||||
packages = ["discovery","kubernetes/scheme","pkg/version","rest","rest/watch","tools/auth","tools/clientcmd","tools/clientcmd/api","tools/clientcmd/api/latest","tools/clientcmd/api/v1","tools/metrics","transport","util/cert","util/flowcontrol","util/homedir","util/integer"]
|
||||
revision = "87887458218a51f3944b2f4c553eb38173458e97"
|
||||
packages = ["discovery","kubernetes/scheme","pkg/apis/clientauthentication","pkg/apis/clientauthentication/v1alpha1","pkg/version","plugin/pkg/client/auth/exec","rest","rest/watch","tools/auth","tools/clientcmd","tools/clientcmd/api","tools/clientcmd/api/latest","tools/clientcmd/api/v1","tools/metrics","transport","util/cert","util/flowcontrol","util/homedir","util/integer"]
|
||||
revision = "dd92f6b11395f23fbffdd5f403c25ba7ccae1226"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
|
|
@ -238,6 +208,6 @@
|
|||
[solve-meta]
|
||||
analyzer-name = "dep"
|
||||
analyzer-version = 1
|
||||
inputs-digest = "87aa82576ea1d99fe034e82d57350127128b9a6c228f799f9179f500c5bddda0"
|
||||
inputs-digest = "4545b4518629fb2e300022ffa6fa27980cc7e7c188ee36c7de5f31e4915dc572"
|
||||
solver-name = "gps-cdcl"
|
||||
solver-version = 1
|
||||
|
|
|
|||
|
|
@ -1 +0,0 @@
|
|||
language: go
|
||||
|
|
@ -1,202 +0,0 @@
|
|||
|
||||
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.
|
||||
|
|
@ -1,12 +0,0 @@
|
|||
# BTree implementation for Go
|
||||
|
||||

|
||||
|
||||
This package provides an in-memory B-Tree implementation for Go, useful as
|
||||
an ordered, mutable data structure.
|
||||
|
||||
The API is based off of the wonderful
|
||||
http://godoc.org/github.com/petar/GoLLRB/llrb, and is meant to allow btree to
|
||||
act as a drop-in replacement for gollrb trees.
|
||||
|
||||
See http://godoc.org/github.com/google/btree for documentation.
|
||||
|
|
@ -1,821 +0,0 @@
|
|||
// 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 btree implements in-memory B-Trees of arbitrary degree.
|
||||
//
|
||||
// btree implements an in-memory B-Tree for use as an ordered data structure.
|
||||
// It is not meant for persistent storage solutions.
|
||||
//
|
||||
// It has a flatter structure than an equivalent red-black or other binary tree,
|
||||
// which in some cases yields better memory usage and/or performance.
|
||||
// See some discussion on the matter here:
|
||||
// http://google-opensource.blogspot.com/2013/01/c-containers-that-save-memory-and-time.html
|
||||
// Note, though, that this project is in no way related to the C++ B-Tree
|
||||
// implementation written about there.
|
||||
//
|
||||
// Within this tree, each node contains a slice of items and a (possibly nil)
|
||||
// slice of children. For basic numeric values or raw structs, this can cause
|
||||
// efficiency differences when compared to equivalent C++ template code that
|
||||
// stores values in arrays within the node:
|
||||
// * Due to the overhead of storing values as interfaces (each
|
||||
// value needs to be stored as the value itself, then 2 words for the
|
||||
// interface pointing to that value and its type), resulting in higher
|
||||
// memory use.
|
||||
// * Since interfaces can point to values anywhere in memory, values are
|
||||
// most likely not stored in contiguous blocks, resulting in a higher
|
||||
// number of cache misses.
|
||||
// These issues don't tend to matter, though, when working with strings or other
|
||||
// heap-allocated structures, since C++-equivalent structures also must store
|
||||
// pointers and also distribute their values across the heap.
|
||||
//
|
||||
// This implementation is designed to be a drop-in replacement to gollrb.LLRB
|
||||
// trees, (http://github.com/petar/gollrb), an excellent and probably the most
|
||||
// widely used ordered tree implementation in the Go ecosystem currently.
|
||||
// Its functions, therefore, exactly mirror those of
|
||||
// llrb.LLRB where possible. Unlike gollrb, though, we currently don't
|
||||
// support storing multiple equivalent values.
|
||||
package btree
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// Item represents a single object in the tree.
|
||||
type Item interface {
|
||||
// Less tests whether the current item is less than the given argument.
|
||||
//
|
||||
// This must provide a strict weak ordering.
|
||||
// If !a.Less(b) && !b.Less(a), we treat this to mean a == b (i.e. we can only
|
||||
// hold one of either a or b in the tree).
|
||||
Less(than Item) bool
|
||||
}
|
||||
|
||||
const (
|
||||
DefaultFreeListSize = 32
|
||||
)
|
||||
|
||||
var (
|
||||
nilItems = make(items, 16)
|
||||
nilChildren = make(children, 16)
|
||||
)
|
||||
|
||||
// FreeList represents a free list of btree nodes. By default each
|
||||
// BTree has its own FreeList, but multiple BTrees can share the same
|
||||
// FreeList.
|
||||
// Two Btrees using the same freelist are safe for concurrent write access.
|
||||
type FreeList struct {
|
||||
mu sync.Mutex
|
||||
freelist []*node
|
||||
}
|
||||
|
||||
// NewFreeList creates a new free list.
|
||||
// size is the maximum size of the returned free list.
|
||||
func NewFreeList(size int) *FreeList {
|
||||
return &FreeList{freelist: make([]*node, 0, size)}
|
||||
}
|
||||
|
||||
func (f *FreeList) newNode() (n *node) {
|
||||
f.mu.Lock()
|
||||
index := len(f.freelist) - 1
|
||||
if index < 0 {
|
||||
f.mu.Unlock()
|
||||
return new(node)
|
||||
}
|
||||
n = f.freelist[index]
|
||||
f.freelist[index] = nil
|
||||
f.freelist = f.freelist[:index]
|
||||
f.mu.Unlock()
|
||||
return
|
||||
}
|
||||
|
||||
func (f *FreeList) freeNode(n *node) {
|
||||
f.mu.Lock()
|
||||
if len(f.freelist) < cap(f.freelist) {
|
||||
f.freelist = append(f.freelist, n)
|
||||
}
|
||||
f.mu.Unlock()
|
||||
}
|
||||
|
||||
// ItemIterator allows callers of Ascend* to iterate in-order over portions of
|
||||
// the tree. When this function returns false, iteration will stop and the
|
||||
// associated Ascend* function will immediately return.
|
||||
type ItemIterator func(i Item) bool
|
||||
|
||||
// New creates a new B-Tree with the given degree.
|
||||
//
|
||||
// New(2), for example, will create a 2-3-4 tree (each node contains 1-3 items
|
||||
// and 2-4 children).
|
||||
func New(degree int) *BTree {
|
||||
return NewWithFreeList(degree, NewFreeList(DefaultFreeListSize))
|
||||
}
|
||||
|
||||
// NewWithFreeList creates a new B-Tree that uses the given node free list.
|
||||
func NewWithFreeList(degree int, f *FreeList) *BTree {
|
||||
if degree <= 1 {
|
||||
panic("bad degree")
|
||||
}
|
||||
return &BTree{
|
||||
degree: degree,
|
||||
cow: ©OnWriteContext{freelist: f},
|
||||
}
|
||||
}
|
||||
|
||||
// items stores items in a node.
|
||||
type items []Item
|
||||
|
||||
// insertAt inserts a value into the given index, pushing all subsequent values
|
||||
// forward.
|
||||
func (s *items) insertAt(index int, item Item) {
|
||||
*s = append(*s, nil)
|
||||
if index < len(*s) {
|
||||
copy((*s)[index+1:], (*s)[index:])
|
||||
}
|
||||
(*s)[index] = item
|
||||
}
|
||||
|
||||
// removeAt removes a value at a given index, pulling all subsequent values
|
||||
// back.
|
||||
func (s *items) removeAt(index int) Item {
|
||||
item := (*s)[index]
|
||||
copy((*s)[index:], (*s)[index+1:])
|
||||
(*s)[len(*s)-1] = nil
|
||||
*s = (*s)[:len(*s)-1]
|
||||
return item
|
||||
}
|
||||
|
||||
// pop removes and returns the last element in the list.
|
||||
func (s *items) pop() (out Item) {
|
||||
index := len(*s) - 1
|
||||
out = (*s)[index]
|
||||
(*s)[index] = nil
|
||||
*s = (*s)[:index]
|
||||
return
|
||||
}
|
||||
|
||||
// truncate truncates this instance at index so that it contains only the
|
||||
// first index items. index must be less than or equal to length.
|
||||
func (s *items) truncate(index int) {
|
||||
var toClear items
|
||||
*s, toClear = (*s)[:index], (*s)[index:]
|
||||
for len(toClear) > 0 {
|
||||
toClear = toClear[copy(toClear, nilItems):]
|
||||
}
|
||||
}
|
||||
|
||||
// find returns the index where the given item should be inserted into this
|
||||
// list. 'found' is true if the item already exists in the list at the given
|
||||
// index.
|
||||
func (s items) find(item Item) (index int, found bool) {
|
||||
i := sort.Search(len(s), func(i int) bool {
|
||||
return item.Less(s[i])
|
||||
})
|
||||
if i > 0 && !s[i-1].Less(item) {
|
||||
return i - 1, true
|
||||
}
|
||||
return i, false
|
||||
}
|
||||
|
||||
// children stores child nodes in a node.
|
||||
type children []*node
|
||||
|
||||
// insertAt inserts a value into the given index, pushing all subsequent values
|
||||
// forward.
|
||||
func (s *children) insertAt(index int, n *node) {
|
||||
*s = append(*s, nil)
|
||||
if index < len(*s) {
|
||||
copy((*s)[index+1:], (*s)[index:])
|
||||
}
|
||||
(*s)[index] = n
|
||||
}
|
||||
|
||||
// removeAt removes a value at a given index, pulling all subsequent values
|
||||
// back.
|
||||
func (s *children) removeAt(index int) *node {
|
||||
n := (*s)[index]
|
||||
copy((*s)[index:], (*s)[index+1:])
|
||||
(*s)[len(*s)-1] = nil
|
||||
*s = (*s)[:len(*s)-1]
|
||||
return n
|
||||
}
|
||||
|
||||
// pop removes and returns the last element in the list.
|
||||
func (s *children) pop() (out *node) {
|
||||
index := len(*s) - 1
|
||||
out = (*s)[index]
|
||||
(*s)[index] = nil
|
||||
*s = (*s)[:index]
|
||||
return
|
||||
}
|
||||
|
||||
// truncate truncates this instance at index so that it contains only the
|
||||
// first index children. index must be less than or equal to length.
|
||||
func (s *children) truncate(index int) {
|
||||
var toClear children
|
||||
*s, toClear = (*s)[:index], (*s)[index:]
|
||||
for len(toClear) > 0 {
|
||||
toClear = toClear[copy(toClear, nilChildren):]
|
||||
}
|
||||
}
|
||||
|
||||
// node is an internal node in a tree.
|
||||
//
|
||||
// It must at all times maintain the invariant that either
|
||||
// * len(children) == 0, len(items) unconstrained
|
||||
// * len(children) == len(items) + 1
|
||||
type node struct {
|
||||
items items
|
||||
children children
|
||||
cow *copyOnWriteContext
|
||||
}
|
||||
|
||||
func (n *node) mutableFor(cow *copyOnWriteContext) *node {
|
||||
if n.cow == cow {
|
||||
return n
|
||||
}
|
||||
out := cow.newNode()
|
||||
if cap(out.items) >= len(n.items) {
|
||||
out.items = out.items[:len(n.items)]
|
||||
} else {
|
||||
out.items = make(items, len(n.items), cap(n.items))
|
||||
}
|
||||
copy(out.items, n.items)
|
||||
// Copy children
|
||||
if cap(out.children) >= len(n.children) {
|
||||
out.children = out.children[:len(n.children)]
|
||||
} else {
|
||||
out.children = make(children, len(n.children), cap(n.children))
|
||||
}
|
||||
copy(out.children, n.children)
|
||||
return out
|
||||
}
|
||||
|
||||
func (n *node) mutableChild(i int) *node {
|
||||
c := n.children[i].mutableFor(n.cow)
|
||||
n.children[i] = c
|
||||
return c
|
||||
}
|
||||
|
||||
// split splits the given node at the given index. The current node shrinks,
|
||||
// and this function returns the item that existed at that index and a new node
|
||||
// containing all items/children after it.
|
||||
func (n *node) split(i int) (Item, *node) {
|
||||
item := n.items[i]
|
||||
next := n.cow.newNode()
|
||||
next.items = append(next.items, n.items[i+1:]...)
|
||||
n.items.truncate(i)
|
||||
if len(n.children) > 0 {
|
||||
next.children = append(next.children, n.children[i+1:]...)
|
||||
n.children.truncate(i + 1)
|
||||
}
|
||||
return item, next
|
||||
}
|
||||
|
||||
// maybeSplitChild checks if a child should be split, and if so splits it.
|
||||
// Returns whether or not a split occurred.
|
||||
func (n *node) maybeSplitChild(i, maxItems int) bool {
|
||||
if len(n.children[i].items) < maxItems {
|
||||
return false
|
||||
}
|
||||
first := n.mutableChild(i)
|
||||
item, second := first.split(maxItems / 2)
|
||||
n.items.insertAt(i, item)
|
||||
n.children.insertAt(i+1, second)
|
||||
return true
|
||||
}
|
||||
|
||||
// insert inserts an item into the subtree rooted at this node, making sure
|
||||
// no nodes in the subtree exceed maxItems items. Should an equivalent item be
|
||||
// be found/replaced by insert, it will be returned.
|
||||
func (n *node) insert(item Item, maxItems int) Item {
|
||||
i, found := n.items.find(item)
|
||||
if found {
|
||||
out := n.items[i]
|
||||
n.items[i] = item
|
||||
return out
|
||||
}
|
||||
if len(n.children) == 0 {
|
||||
n.items.insertAt(i, item)
|
||||
return nil
|
||||
}
|
||||
if n.maybeSplitChild(i, maxItems) {
|
||||
inTree := n.items[i]
|
||||
switch {
|
||||
case item.Less(inTree):
|
||||
// no change, we want first split node
|
||||
case inTree.Less(item):
|
||||
i++ // we want second split node
|
||||
default:
|
||||
out := n.items[i]
|
||||
n.items[i] = item
|
||||
return out
|
||||
}
|
||||
}
|
||||
return n.mutableChild(i).insert(item, maxItems)
|
||||
}
|
||||
|
||||
// get finds the given key in the subtree and returns it.
|
||||
func (n *node) get(key Item) Item {
|
||||
i, found := n.items.find(key)
|
||||
if found {
|
||||
return n.items[i]
|
||||
} else if len(n.children) > 0 {
|
||||
return n.children[i].get(key)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// min returns the first item in the subtree.
|
||||
func min(n *node) Item {
|
||||
if n == nil {
|
||||
return nil
|
||||
}
|
||||
for len(n.children) > 0 {
|
||||
n = n.children[0]
|
||||
}
|
||||
if len(n.items) == 0 {
|
||||
return nil
|
||||
}
|
||||
return n.items[0]
|
||||
}
|
||||
|
||||
// max returns the last item in the subtree.
|
||||
func max(n *node) Item {
|
||||
if n == nil {
|
||||
return nil
|
||||
}
|
||||
for len(n.children) > 0 {
|
||||
n = n.children[len(n.children)-1]
|
||||
}
|
||||
if len(n.items) == 0 {
|
||||
return nil
|
||||
}
|
||||
return n.items[len(n.items)-1]
|
||||
}
|
||||
|
||||
// toRemove details what item to remove in a node.remove call.
|
||||
type toRemove int
|
||||
|
||||
const (
|
||||
removeItem toRemove = iota // removes the given item
|
||||
removeMin // removes smallest item in the subtree
|
||||
removeMax // removes largest item in the subtree
|
||||
)
|
||||
|
||||
// remove removes an item from the subtree rooted at this node.
|
||||
func (n *node) remove(item Item, minItems int, typ toRemove) Item {
|
||||
var i int
|
||||
var found bool
|
||||
switch typ {
|
||||
case removeMax:
|
||||
if len(n.children) == 0 {
|
||||
return n.items.pop()
|
||||
}
|
||||
i = len(n.items)
|
||||
case removeMin:
|
||||
if len(n.children) == 0 {
|
||||
return n.items.removeAt(0)
|
||||
}
|
||||
i = 0
|
||||
case removeItem:
|
||||
i, found = n.items.find(item)
|
||||
if len(n.children) == 0 {
|
||||
if found {
|
||||
return n.items.removeAt(i)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
default:
|
||||
panic("invalid type")
|
||||
}
|
||||
// If we get to here, we have children.
|
||||
if len(n.children[i].items) <= minItems {
|
||||
return n.growChildAndRemove(i, item, minItems, typ)
|
||||
}
|
||||
child := n.mutableChild(i)
|
||||
// Either we had enough items to begin with, or we've done some
|
||||
// merging/stealing, because we've got enough now and we're ready to return
|
||||
// stuff.
|
||||
if found {
|
||||
// The item exists at index 'i', and the child we've selected can give us a
|
||||
// predecessor, since if we've gotten here it's got > minItems items in it.
|
||||
out := n.items[i]
|
||||
// We use our special-case 'remove' call with typ=maxItem to pull the
|
||||
// predecessor of item i (the rightmost leaf of our immediate left child)
|
||||
// and set it into where we pulled the item from.
|
||||
n.items[i] = child.remove(nil, minItems, removeMax)
|
||||
return out
|
||||
}
|
||||
// Final recursive call. Once we're here, we know that the item isn't in this
|
||||
// node and that the child is big enough to remove from.
|
||||
return child.remove(item, minItems, typ)
|
||||
}
|
||||
|
||||
// growChildAndRemove grows child 'i' to make sure it's possible to remove an
|
||||
// item from it while keeping it at minItems, then calls remove to actually
|
||||
// remove it.
|
||||
//
|
||||
// Most documentation says we have to do two sets of special casing:
|
||||
// 1) item is in this node
|
||||
// 2) item is in child
|
||||
// In both cases, we need to handle the two subcases:
|
||||
// A) node has enough values that it can spare one
|
||||
// B) node doesn't have enough values
|
||||
// For the latter, we have to check:
|
||||
// a) left sibling has node to spare
|
||||
// b) right sibling has node to spare
|
||||
// c) we must merge
|
||||
// To simplify our code here, we handle cases #1 and #2 the same:
|
||||
// If a node doesn't have enough items, we make sure it does (using a,b,c).
|
||||
// We then simply redo our remove call, and the second time (regardless of
|
||||
// whether we're in case 1 or 2), we'll have enough items and can guarantee
|
||||
// that we hit case A.
|
||||
func (n *node) growChildAndRemove(i int, item Item, minItems int, typ toRemove) Item {
|
||||
if i > 0 && len(n.children[i-1].items) > minItems {
|
||||
// Steal from left child
|
||||
child := n.mutableChild(i)
|
||||
stealFrom := n.mutableChild(i - 1)
|
||||
stolenItem := stealFrom.items.pop()
|
||||
child.items.insertAt(0, n.items[i-1])
|
||||
n.items[i-1] = stolenItem
|
||||
if len(stealFrom.children) > 0 {
|
||||
child.children.insertAt(0, stealFrom.children.pop())
|
||||
}
|
||||
} else if i < len(n.items) && len(n.children[i+1].items) > minItems {
|
||||
// steal from right child
|
||||
child := n.mutableChild(i)
|
||||
stealFrom := n.mutableChild(i + 1)
|
||||
stolenItem := stealFrom.items.removeAt(0)
|
||||
child.items = append(child.items, n.items[i])
|
||||
n.items[i] = stolenItem
|
||||
if len(stealFrom.children) > 0 {
|
||||
child.children = append(child.children, stealFrom.children.removeAt(0))
|
||||
}
|
||||
} else {
|
||||
if i >= len(n.items) {
|
||||
i--
|
||||
}
|
||||
child := n.mutableChild(i)
|
||||
// merge with right child
|
||||
mergeItem := n.items.removeAt(i)
|
||||
mergeChild := n.children.removeAt(i + 1)
|
||||
child.items = append(child.items, mergeItem)
|
||||
child.items = append(child.items, mergeChild.items...)
|
||||
child.children = append(child.children, mergeChild.children...)
|
||||
n.cow.freeNode(mergeChild)
|
||||
}
|
||||
return n.remove(item, minItems, typ)
|
||||
}
|
||||
|
||||
type direction int
|
||||
|
||||
const (
|
||||
descend = direction(-1)
|
||||
ascend = direction(+1)
|
||||
)
|
||||
|
||||
// iterate provides a simple method for iterating over elements in the tree.
|
||||
//
|
||||
// When ascending, the 'start' should be less than 'stop' and when descending,
|
||||
// the 'start' should be greater than 'stop'. Setting 'includeStart' to true
|
||||
// will force the iterator to include the first item when it equals 'start',
|
||||
// thus creating a "greaterOrEqual" or "lessThanEqual" rather than just a
|
||||
// "greaterThan" or "lessThan" queries.
|
||||
func (n *node) iterate(dir direction, start, stop Item, includeStart bool, hit bool, iter ItemIterator) (bool, bool) {
|
||||
var ok bool
|
||||
switch dir {
|
||||
case ascend:
|
||||
for i := 0; i < len(n.items); i++ {
|
||||
if start != nil && n.items[i].Less(start) {
|
||||
continue
|
||||
}
|
||||
if len(n.children) > 0 {
|
||||
if hit, ok = n.children[i].iterate(dir, start, stop, includeStart, hit, iter); !ok {
|
||||
return hit, false
|
||||
}
|
||||
}
|
||||
if !includeStart && !hit && start != nil && !start.Less(n.items[i]) {
|
||||
hit = true
|
||||
continue
|
||||
}
|
||||
hit = true
|
||||
if stop != nil && !n.items[i].Less(stop) {
|
||||
return hit, false
|
||||
}
|
||||
if !iter(n.items[i]) {
|
||||
return hit, false
|
||||
}
|
||||
}
|
||||
if len(n.children) > 0 {
|
||||
if hit, ok = n.children[len(n.children)-1].iterate(dir, start, stop, includeStart, hit, iter); !ok {
|
||||
return hit, false
|
||||
}
|
||||
}
|
||||
case descend:
|
||||
for i := len(n.items) - 1; i >= 0; i-- {
|
||||
if start != nil && !n.items[i].Less(start) {
|
||||
if !includeStart || hit || start.Less(n.items[i]) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
if len(n.children) > 0 {
|
||||
if hit, ok = n.children[i+1].iterate(dir, start, stop, includeStart, hit, iter); !ok {
|
||||
return hit, false
|
||||
}
|
||||
}
|
||||
if stop != nil && !stop.Less(n.items[i]) {
|
||||
return hit, false // continue
|
||||
}
|
||||
hit = true
|
||||
if !iter(n.items[i]) {
|
||||
return hit, false
|
||||
}
|
||||
}
|
||||
if len(n.children) > 0 {
|
||||
if hit, ok = n.children[0].iterate(dir, start, stop, includeStart, hit, iter); !ok {
|
||||
return hit, false
|
||||
}
|
||||
}
|
||||
}
|
||||
return hit, true
|
||||
}
|
||||
|
||||
// Used for testing/debugging purposes.
|
||||
func (n *node) print(w io.Writer, level int) {
|
||||
fmt.Fprintf(w, "%sNODE:%v\n", strings.Repeat(" ", level), n.items)
|
||||
for _, c := range n.children {
|
||||
c.print(w, level+1)
|
||||
}
|
||||
}
|
||||
|
||||
// BTree is an implementation of a B-Tree.
|
||||
//
|
||||
// BTree stores Item instances in an ordered structure, allowing easy insertion,
|
||||
// removal, and iteration.
|
||||
//
|
||||
// Write operations are not safe for concurrent mutation by multiple
|
||||
// goroutines, but Read operations are.
|
||||
type BTree struct {
|
||||
degree int
|
||||
length int
|
||||
root *node
|
||||
cow *copyOnWriteContext
|
||||
}
|
||||
|
||||
// copyOnWriteContext pointers determine node ownership... a tree with a write
|
||||
// context equivalent to a node's write context is allowed to modify that node.
|
||||
// A tree whose write context does not match a node's is not allowed to modify
|
||||
// it, and must create a new, writable copy (IE: it's a Clone).
|
||||
//
|
||||
// When doing any write operation, we maintain the invariant that the current
|
||||
// node's context is equal to the context of the tree that requested the write.
|
||||
// We do this by, before we descend into any node, creating a copy with the
|
||||
// correct context if the contexts don't match.
|
||||
//
|
||||
// Since the node we're currently visiting on any write has the requesting
|
||||
// tree's context, that node is modifiable in place. Children of that node may
|
||||
// not share context, but before we descend into them, we'll make a mutable
|
||||
// copy.
|
||||
type copyOnWriteContext struct {
|
||||
freelist *FreeList
|
||||
}
|
||||
|
||||
// Clone clones the btree, lazily. Clone should not be called concurrently,
|
||||
// but the original tree (t) and the new tree (t2) can be used concurrently
|
||||
// once the Clone call completes.
|
||||
//
|
||||
// The internal tree structure of b is marked read-only and shared between t and
|
||||
// t2. Writes to both t and t2 use copy-on-write logic, creating new nodes
|
||||
// whenever one of b's original nodes would have been modified. Read operations
|
||||
// should have no performance degredation. Write operations for both t and t2
|
||||
// will initially experience minor slow-downs caused by additional allocs and
|
||||
// copies due to the aforementioned copy-on-write logic, but should converge to
|
||||
// the original performance characteristics of the original tree.
|
||||
func (t *BTree) Clone() (t2 *BTree) {
|
||||
// Create two entirely new copy-on-write contexts.
|
||||
// This operation effectively creates three trees:
|
||||
// the original, shared nodes (old b.cow)
|
||||
// the new b.cow nodes
|
||||
// the new out.cow nodes
|
||||
cow1, cow2 := *t.cow, *t.cow
|
||||
out := *t
|
||||
t.cow = &cow1
|
||||
out.cow = &cow2
|
||||
return &out
|
||||
}
|
||||
|
||||
// maxItems returns the max number of items to allow per node.
|
||||
func (t *BTree) maxItems() int {
|
||||
return t.degree*2 - 1
|
||||
}
|
||||
|
||||
// minItems returns the min number of items to allow per node (ignored for the
|
||||
// root node).
|
||||
func (t *BTree) minItems() int {
|
||||
return t.degree - 1
|
||||
}
|
||||
|
||||
func (c *copyOnWriteContext) newNode() (n *node) {
|
||||
n = c.freelist.newNode()
|
||||
n.cow = c
|
||||
return
|
||||
}
|
||||
|
||||
func (c *copyOnWriteContext) freeNode(n *node) {
|
||||
if n.cow == c {
|
||||
// clear to allow GC
|
||||
n.items.truncate(0)
|
||||
n.children.truncate(0)
|
||||
n.cow = nil
|
||||
c.freelist.freeNode(n)
|
||||
}
|
||||
}
|
||||
|
||||
// ReplaceOrInsert adds the given item to the tree. If an item in the tree
|
||||
// already equals the given one, it is removed from the tree and returned.
|
||||
// Otherwise, nil is returned.
|
||||
//
|
||||
// nil cannot be added to the tree (will panic).
|
||||
func (t *BTree) ReplaceOrInsert(item Item) Item {
|
||||
if item == nil {
|
||||
panic("nil item being added to BTree")
|
||||
}
|
||||
if t.root == nil {
|
||||
t.root = t.cow.newNode()
|
||||
t.root.items = append(t.root.items, item)
|
||||
t.length++
|
||||
return nil
|
||||
} else {
|
||||
t.root = t.root.mutableFor(t.cow)
|
||||
if len(t.root.items) >= t.maxItems() {
|
||||
item2, second := t.root.split(t.maxItems() / 2)
|
||||
oldroot := t.root
|
||||
t.root = t.cow.newNode()
|
||||
t.root.items = append(t.root.items, item2)
|
||||
t.root.children = append(t.root.children, oldroot, second)
|
||||
}
|
||||
}
|
||||
out := t.root.insert(item, t.maxItems())
|
||||
if out == nil {
|
||||
t.length++
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Delete removes an item equal to the passed in item from the tree, returning
|
||||
// it. If no such item exists, returns nil.
|
||||
func (t *BTree) Delete(item Item) Item {
|
||||
return t.deleteItem(item, removeItem)
|
||||
}
|
||||
|
||||
// DeleteMin removes the smallest item in the tree and returns it.
|
||||
// If no such item exists, returns nil.
|
||||
func (t *BTree) DeleteMin() Item {
|
||||
return t.deleteItem(nil, removeMin)
|
||||
}
|
||||
|
||||
// DeleteMax removes the largest item in the tree and returns it.
|
||||
// If no such item exists, returns nil.
|
||||
func (t *BTree) DeleteMax() Item {
|
||||
return t.deleteItem(nil, removeMax)
|
||||
}
|
||||
|
||||
func (t *BTree) deleteItem(item Item, typ toRemove) Item {
|
||||
if t.root == nil || len(t.root.items) == 0 {
|
||||
return nil
|
||||
}
|
||||
t.root = t.root.mutableFor(t.cow)
|
||||
out := t.root.remove(item, t.minItems(), typ)
|
||||
if len(t.root.items) == 0 && len(t.root.children) > 0 {
|
||||
oldroot := t.root
|
||||
t.root = t.root.children[0]
|
||||
t.cow.freeNode(oldroot)
|
||||
}
|
||||
if out != nil {
|
||||
t.length--
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// AscendRange calls the iterator for every value in the tree within the range
|
||||
// [greaterOrEqual, lessThan), until iterator returns false.
|
||||
func (t *BTree) AscendRange(greaterOrEqual, lessThan Item, iterator ItemIterator) {
|
||||
if t.root == nil {
|
||||
return
|
||||
}
|
||||
t.root.iterate(ascend, greaterOrEqual, lessThan, true, false, iterator)
|
||||
}
|
||||
|
||||
// AscendLessThan calls the iterator for every value in the tree within the range
|
||||
// [first, pivot), until iterator returns false.
|
||||
func (t *BTree) AscendLessThan(pivot Item, iterator ItemIterator) {
|
||||
if t.root == nil {
|
||||
return
|
||||
}
|
||||
t.root.iterate(ascend, nil, pivot, false, false, iterator)
|
||||
}
|
||||
|
||||
// AscendGreaterOrEqual calls the iterator for every value in the tree within
|
||||
// the range [pivot, last], until iterator returns false.
|
||||
func (t *BTree) AscendGreaterOrEqual(pivot Item, iterator ItemIterator) {
|
||||
if t.root == nil {
|
||||
return
|
||||
}
|
||||
t.root.iterate(ascend, pivot, nil, true, false, iterator)
|
||||
}
|
||||
|
||||
// Ascend calls the iterator for every value in the tree within the range
|
||||
// [first, last], until iterator returns false.
|
||||
func (t *BTree) Ascend(iterator ItemIterator) {
|
||||
if t.root == nil {
|
||||
return
|
||||
}
|
||||
t.root.iterate(ascend, nil, nil, false, false, iterator)
|
||||
}
|
||||
|
||||
// DescendRange calls the iterator for every value in the tree within the range
|
||||
// [lessOrEqual, greaterThan), until iterator returns false.
|
||||
func (t *BTree) DescendRange(lessOrEqual, greaterThan Item, iterator ItemIterator) {
|
||||
if t.root == nil {
|
||||
return
|
||||
}
|
||||
t.root.iterate(descend, lessOrEqual, greaterThan, true, false, iterator)
|
||||
}
|
||||
|
||||
// DescendLessOrEqual calls the iterator for every value in the tree within the range
|
||||
// [pivot, first], until iterator returns false.
|
||||
func (t *BTree) DescendLessOrEqual(pivot Item, iterator ItemIterator) {
|
||||
if t.root == nil {
|
||||
return
|
||||
}
|
||||
t.root.iterate(descend, pivot, nil, true, false, iterator)
|
||||
}
|
||||
|
||||
// DescendGreaterThan calls the iterator for every value in the tree within
|
||||
// the range (pivot, last], until iterator returns false.
|
||||
func (t *BTree) DescendGreaterThan(pivot Item, iterator ItemIterator) {
|
||||
if t.root == nil {
|
||||
return
|
||||
}
|
||||
t.root.iterate(descend, nil, pivot, false, false, iterator)
|
||||
}
|
||||
|
||||
// Descend calls the iterator for every value in the tree within the range
|
||||
// [last, first], until iterator returns false.
|
||||
func (t *BTree) Descend(iterator ItemIterator) {
|
||||
if t.root == nil {
|
||||
return
|
||||
}
|
||||
t.root.iterate(descend, nil, nil, false, false, iterator)
|
||||
}
|
||||
|
||||
// Get looks for the key item in the tree, returning it. It returns nil if
|
||||
// unable to find that item.
|
||||
func (t *BTree) Get(key Item) Item {
|
||||
if t.root == nil {
|
||||
return nil
|
||||
}
|
||||
return t.root.get(key)
|
||||
}
|
||||
|
||||
// Min returns the smallest item in the tree, or nil if the tree is empty.
|
||||
func (t *BTree) Min() Item {
|
||||
return min(t.root)
|
||||
}
|
||||
|
||||
// Max returns the largest item in the tree, or nil if the tree is empty.
|
||||
func (t *BTree) Max() Item {
|
||||
return max(t.root)
|
||||
}
|
||||
|
||||
// Has returns true if the given key is in the tree.
|
||||
func (t *BTree) Has(key Item) bool {
|
||||
return t.Get(key) != nil
|
||||
}
|
||||
|
||||
// Len returns the number of items currently in the tree.
|
||||
func (t *BTree) Len() int {
|
||||
return t.length
|
||||
}
|
||||
|
||||
// Int implements the Item interface for integers.
|
||||
type Int int
|
||||
|
||||
// Less returns true if int(a) < int(b).
|
||||
func (a Int) Less(b Item) bool {
|
||||
return a < b.(Int)
|
||||
}
|
||||
|
|
@ -1,76 +0,0 @@
|
|||
// 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.
|
||||
|
||||
// +build ignore
|
||||
|
||||
// This binary compares memory usage between btree and gollrb.
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"runtime"
|
||||
"time"
|
||||
|
||||
"github.com/google/btree"
|
||||
"github.com/petar/GoLLRB/llrb"
|
||||
)
|
||||
|
||||
var (
|
||||
size = flag.Int("size", 1000000, "size of the tree to build")
|
||||
degree = flag.Int("degree", 8, "degree of btree")
|
||||
gollrb = flag.Bool("llrb", false, "use llrb instead of btree")
|
||||
)
|
||||
|
||||
func main() {
|
||||
flag.Parse()
|
||||
vals := rand.Perm(*size)
|
||||
var t, v interface{}
|
||||
v = vals
|
||||
var stats runtime.MemStats
|
||||
for i := 0; i < 10; i++ {
|
||||
runtime.GC()
|
||||
}
|
||||
fmt.Println("-------- BEFORE ----------")
|
||||
runtime.ReadMemStats(&stats)
|
||||
fmt.Printf("%+v\n", stats)
|
||||
start := time.Now()
|
||||
if *gollrb {
|
||||
tr := llrb.New()
|
||||
for _, v := range vals {
|
||||
tr.ReplaceOrInsert(llrb.Int(v))
|
||||
}
|
||||
t = tr // keep it around
|
||||
} else {
|
||||
tr := btree.New(*degree)
|
||||
for _, v := range vals {
|
||||
tr.ReplaceOrInsert(btree.Int(v))
|
||||
}
|
||||
t = tr // keep it around
|
||||
}
|
||||
fmt.Printf("%v inserts in %v\n", *size, time.Since(start))
|
||||
fmt.Println("-------- AFTER ----------")
|
||||
runtime.ReadMemStats(&stats)
|
||||
fmt.Printf("%+v\n", stats)
|
||||
for i := 0; i < 10; i++ {
|
||||
runtime.GC()
|
||||
}
|
||||
fmt.Println("-------- AFTER GC ----------")
|
||||
runtime.ReadMemStats(&stats)
|
||||
fmt.Printf("%+v\n", stats)
|
||||
if t == v {
|
||||
fmt.Println("to make sure vals and tree aren't GC'd")
|
||||
}
|
||||
}
|
||||
|
|
@ -1,689 +0,0 @@
|
|||
// 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 btree
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"reflect"
|
||||
"sort"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func init() {
|
||||
seed := time.Now().Unix()
|
||||
fmt.Println(seed)
|
||||
rand.Seed(seed)
|
||||
}
|
||||
|
||||
// perm returns a random permutation of n Int items in the range [0, n).
|
||||
func perm(n int) (out []Item) {
|
||||
for _, v := range rand.Perm(n) {
|
||||
out = append(out, Int(v))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// rang returns an ordered list of Int items in the range [0, n).
|
||||
func rang(n int) (out []Item) {
|
||||
for i := 0; i < n; i++ {
|
||||
out = append(out, Int(i))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// all extracts all items from a tree in order as a slice.
|
||||
func all(t *BTree) (out []Item) {
|
||||
t.Ascend(func(a Item) bool {
|
||||
out = append(out, a)
|
||||
return true
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// rangerev returns a reversed ordered list of Int items in the range [0, n).
|
||||
func rangrev(n int) (out []Item) {
|
||||
for i := n - 1; i >= 0; i-- {
|
||||
out = append(out, Int(i))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// allrev extracts all items from a tree in reverse order as a slice.
|
||||
func allrev(t *BTree) (out []Item) {
|
||||
t.Descend(func(a Item) bool {
|
||||
out = append(out, a)
|
||||
return true
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
var btreeDegree = flag.Int("degree", 32, "B-Tree degree")
|
||||
|
||||
func TestBTree(t *testing.T) {
|
||||
tr := New(*btreeDegree)
|
||||
const treeSize = 10000
|
||||
for i := 0; i < 10; i++ {
|
||||
if min := tr.Min(); min != nil {
|
||||
t.Fatalf("empty min, got %+v", min)
|
||||
}
|
||||
if max := tr.Max(); max != nil {
|
||||
t.Fatalf("empty max, got %+v", max)
|
||||
}
|
||||
for _, item := range perm(treeSize) {
|
||||
if x := tr.ReplaceOrInsert(item); x != nil {
|
||||
t.Fatal("insert found item", item)
|
||||
}
|
||||
}
|
||||
for _, item := range perm(treeSize) {
|
||||
if x := tr.ReplaceOrInsert(item); x == nil {
|
||||
t.Fatal("insert didn't find item", item)
|
||||
}
|
||||
}
|
||||
if min, want := tr.Min(), Item(Int(0)); min != want {
|
||||
t.Fatalf("min: want %+v, got %+v", want, min)
|
||||
}
|
||||
if max, want := tr.Max(), Item(Int(treeSize-1)); max != want {
|
||||
t.Fatalf("max: want %+v, got %+v", want, max)
|
||||
}
|
||||
got := all(tr)
|
||||
want := rang(treeSize)
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("mismatch:\n got: %v\nwant: %v", got, want)
|
||||
}
|
||||
|
||||
gotrev := allrev(tr)
|
||||
wantrev := rangrev(treeSize)
|
||||
if !reflect.DeepEqual(gotrev, wantrev) {
|
||||
t.Fatalf("mismatch:\n got: %v\nwant: %v", got, want)
|
||||
}
|
||||
|
||||
for _, item := range perm(treeSize) {
|
||||
if x := tr.Delete(item); x == nil {
|
||||
t.Fatalf("didn't find %v", item)
|
||||
}
|
||||
}
|
||||
if got = all(tr); len(got) > 0 {
|
||||
t.Fatalf("some left!: %v", got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func ExampleBTree() {
|
||||
tr := New(*btreeDegree)
|
||||
for i := Int(0); i < 10; i++ {
|
||||
tr.ReplaceOrInsert(i)
|
||||
}
|
||||
fmt.Println("len: ", tr.Len())
|
||||
fmt.Println("get3: ", tr.Get(Int(3)))
|
||||
fmt.Println("get100: ", tr.Get(Int(100)))
|
||||
fmt.Println("del4: ", tr.Delete(Int(4)))
|
||||
fmt.Println("del100: ", tr.Delete(Int(100)))
|
||||
fmt.Println("replace5: ", tr.ReplaceOrInsert(Int(5)))
|
||||
fmt.Println("replace100:", tr.ReplaceOrInsert(Int(100)))
|
||||
fmt.Println("min: ", tr.Min())
|
||||
fmt.Println("delmin: ", tr.DeleteMin())
|
||||
fmt.Println("max: ", tr.Max())
|
||||
fmt.Println("delmax: ", tr.DeleteMax())
|
||||
fmt.Println("len: ", tr.Len())
|
||||
// Output:
|
||||
// len: 10
|
||||
// get3: 3
|
||||
// get100: <nil>
|
||||
// del4: 4
|
||||
// del100: <nil>
|
||||
// replace5: 5
|
||||
// replace100: <nil>
|
||||
// min: 0
|
||||
// delmin: 0
|
||||
// max: 100
|
||||
// delmax: 100
|
||||
// len: 8
|
||||
}
|
||||
|
||||
func TestDeleteMin(t *testing.T) {
|
||||
tr := New(3)
|
||||
for _, v := range perm(100) {
|
||||
tr.ReplaceOrInsert(v)
|
||||
}
|
||||
var got []Item
|
||||
for v := tr.DeleteMin(); v != nil; v = tr.DeleteMin() {
|
||||
got = append(got, v)
|
||||
}
|
||||
if want := rang(100); !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("ascendrange:\n got: %v\nwant: %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteMax(t *testing.T) {
|
||||
tr := New(3)
|
||||
for _, v := range perm(100) {
|
||||
tr.ReplaceOrInsert(v)
|
||||
}
|
||||
var got []Item
|
||||
for v := tr.DeleteMax(); v != nil; v = tr.DeleteMax() {
|
||||
got = append(got, v)
|
||||
}
|
||||
// Reverse our list.
|
||||
for i := 0; i < len(got)/2; i++ {
|
||||
got[i], got[len(got)-i-1] = got[len(got)-i-1], got[i]
|
||||
}
|
||||
if want := rang(100); !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("ascendrange:\n got: %v\nwant: %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAscendRange(t *testing.T) {
|
||||
tr := New(2)
|
||||
for _, v := range perm(100) {
|
||||
tr.ReplaceOrInsert(v)
|
||||
}
|
||||
var got []Item
|
||||
tr.AscendRange(Int(40), Int(60), func(a Item) bool {
|
||||
got = append(got, a)
|
||||
return true
|
||||
})
|
||||
if want := rang(100)[40:60]; !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("ascendrange:\n got: %v\nwant: %v", got, want)
|
||||
}
|
||||
got = got[:0]
|
||||
tr.AscendRange(Int(40), Int(60), func(a Item) bool {
|
||||
if a.(Int) > 50 {
|
||||
return false
|
||||
}
|
||||
got = append(got, a)
|
||||
return true
|
||||
})
|
||||
if want := rang(100)[40:51]; !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("ascendrange:\n got: %v\nwant: %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDescendRange(t *testing.T) {
|
||||
tr := New(2)
|
||||
for _, v := range perm(100) {
|
||||
tr.ReplaceOrInsert(v)
|
||||
}
|
||||
var got []Item
|
||||
tr.DescendRange(Int(60), Int(40), func(a Item) bool {
|
||||
got = append(got, a)
|
||||
return true
|
||||
})
|
||||
if want := rangrev(100)[39:59]; !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("descendrange:\n got: %v\nwant: %v", got, want)
|
||||
}
|
||||
got = got[:0]
|
||||
tr.DescendRange(Int(60), Int(40), func(a Item) bool {
|
||||
if a.(Int) < 50 {
|
||||
return false
|
||||
}
|
||||
got = append(got, a)
|
||||
return true
|
||||
})
|
||||
if want := rangrev(100)[39:50]; !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("descendrange:\n got: %v\nwant: %v", got, want)
|
||||
}
|
||||
}
|
||||
func TestAscendLessThan(t *testing.T) {
|
||||
tr := New(*btreeDegree)
|
||||
for _, v := range perm(100) {
|
||||
tr.ReplaceOrInsert(v)
|
||||
}
|
||||
var got []Item
|
||||
tr.AscendLessThan(Int(60), func(a Item) bool {
|
||||
got = append(got, a)
|
||||
return true
|
||||
})
|
||||
if want := rang(100)[:60]; !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("ascendrange:\n got: %v\nwant: %v", got, want)
|
||||
}
|
||||
got = got[:0]
|
||||
tr.AscendLessThan(Int(60), func(a Item) bool {
|
||||
if a.(Int) > 50 {
|
||||
return false
|
||||
}
|
||||
got = append(got, a)
|
||||
return true
|
||||
})
|
||||
if want := rang(100)[:51]; !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("ascendrange:\n got: %v\nwant: %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDescendLessOrEqual(t *testing.T) {
|
||||
tr := New(*btreeDegree)
|
||||
for _, v := range perm(100) {
|
||||
tr.ReplaceOrInsert(v)
|
||||
}
|
||||
var got []Item
|
||||
tr.DescendLessOrEqual(Int(40), func(a Item) bool {
|
||||
got = append(got, a)
|
||||
return true
|
||||
})
|
||||
if want := rangrev(100)[59:]; !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("descendlessorequal:\n got: %v\nwant: %v", got, want)
|
||||
}
|
||||
got = got[:0]
|
||||
tr.DescendLessOrEqual(Int(60), func(a Item) bool {
|
||||
if a.(Int) < 50 {
|
||||
return false
|
||||
}
|
||||
got = append(got, a)
|
||||
return true
|
||||
})
|
||||
if want := rangrev(100)[39:50]; !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("descendlessorequal:\n got: %v\nwant: %v", got, want)
|
||||
}
|
||||
}
|
||||
func TestAscendGreaterOrEqual(t *testing.T) {
|
||||
tr := New(*btreeDegree)
|
||||
for _, v := range perm(100) {
|
||||
tr.ReplaceOrInsert(v)
|
||||
}
|
||||
var got []Item
|
||||
tr.AscendGreaterOrEqual(Int(40), func(a Item) bool {
|
||||
got = append(got, a)
|
||||
return true
|
||||
})
|
||||
if want := rang(100)[40:]; !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("ascendrange:\n got: %v\nwant: %v", got, want)
|
||||
}
|
||||
got = got[:0]
|
||||
tr.AscendGreaterOrEqual(Int(40), func(a Item) bool {
|
||||
if a.(Int) > 50 {
|
||||
return false
|
||||
}
|
||||
got = append(got, a)
|
||||
return true
|
||||
})
|
||||
if want := rang(100)[40:51]; !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("ascendrange:\n got: %v\nwant: %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDescendGreaterThan(t *testing.T) {
|
||||
tr := New(*btreeDegree)
|
||||
for _, v := range perm(100) {
|
||||
tr.ReplaceOrInsert(v)
|
||||
}
|
||||
var got []Item
|
||||
tr.DescendGreaterThan(Int(40), func(a Item) bool {
|
||||
got = append(got, a)
|
||||
return true
|
||||
})
|
||||
if want := rangrev(100)[:59]; !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("descendgreaterthan:\n got: %v\nwant: %v", got, want)
|
||||
}
|
||||
got = got[:0]
|
||||
tr.DescendGreaterThan(Int(40), func(a Item) bool {
|
||||
if a.(Int) < 50 {
|
||||
return false
|
||||
}
|
||||
got = append(got, a)
|
||||
return true
|
||||
})
|
||||
if want := rangrev(100)[:50]; !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("descendgreaterthan:\n got: %v\nwant: %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
const benchmarkTreeSize = 10000
|
||||
|
||||
func BenchmarkInsert(b *testing.B) {
|
||||
b.StopTimer()
|
||||
insertP := perm(benchmarkTreeSize)
|
||||
b.StartTimer()
|
||||
i := 0
|
||||
for i < b.N {
|
||||
tr := New(*btreeDegree)
|
||||
for _, item := range insertP {
|
||||
tr.ReplaceOrInsert(item)
|
||||
i++
|
||||
if i >= b.N {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkDeleteInsert(b *testing.B) {
|
||||
b.StopTimer()
|
||||
insertP := perm(benchmarkTreeSize)
|
||||
tr := New(*btreeDegree)
|
||||
for _, item := range insertP {
|
||||
tr.ReplaceOrInsert(item)
|
||||
}
|
||||
b.StartTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
tr.Delete(insertP[i%benchmarkTreeSize])
|
||||
tr.ReplaceOrInsert(insertP[i%benchmarkTreeSize])
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkDeleteInsertCloneOnce(b *testing.B) {
|
||||
b.StopTimer()
|
||||
insertP := perm(benchmarkTreeSize)
|
||||
tr := New(*btreeDegree)
|
||||
for _, item := range insertP {
|
||||
tr.ReplaceOrInsert(item)
|
||||
}
|
||||
tr = tr.Clone()
|
||||
b.StartTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
tr.Delete(insertP[i%benchmarkTreeSize])
|
||||
tr.ReplaceOrInsert(insertP[i%benchmarkTreeSize])
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkDeleteInsertCloneEachTime(b *testing.B) {
|
||||
b.StopTimer()
|
||||
insertP := perm(benchmarkTreeSize)
|
||||
tr := New(*btreeDegree)
|
||||
for _, item := range insertP {
|
||||
tr.ReplaceOrInsert(item)
|
||||
}
|
||||
b.StartTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
tr = tr.Clone()
|
||||
tr.Delete(insertP[i%benchmarkTreeSize])
|
||||
tr.ReplaceOrInsert(insertP[i%benchmarkTreeSize])
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkDelete(b *testing.B) {
|
||||
b.StopTimer()
|
||||
insertP := perm(benchmarkTreeSize)
|
||||
removeP := perm(benchmarkTreeSize)
|
||||
b.StartTimer()
|
||||
i := 0
|
||||
for i < b.N {
|
||||
b.StopTimer()
|
||||
tr := New(*btreeDegree)
|
||||
for _, v := range insertP {
|
||||
tr.ReplaceOrInsert(v)
|
||||
}
|
||||
b.StartTimer()
|
||||
for _, item := range removeP {
|
||||
tr.Delete(item)
|
||||
i++
|
||||
if i >= b.N {
|
||||
return
|
||||
}
|
||||
}
|
||||
if tr.Len() > 0 {
|
||||
panic(tr.Len())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkGet(b *testing.B) {
|
||||
b.StopTimer()
|
||||
insertP := perm(benchmarkTreeSize)
|
||||
removeP := perm(benchmarkTreeSize)
|
||||
b.StartTimer()
|
||||
i := 0
|
||||
for i < b.N {
|
||||
b.StopTimer()
|
||||
tr := New(*btreeDegree)
|
||||
for _, v := range insertP {
|
||||
tr.ReplaceOrInsert(v)
|
||||
}
|
||||
b.StartTimer()
|
||||
for _, item := range removeP {
|
||||
tr.Get(item)
|
||||
i++
|
||||
if i >= b.N {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkGetCloneEachTime(b *testing.B) {
|
||||
b.StopTimer()
|
||||
insertP := perm(benchmarkTreeSize)
|
||||
removeP := perm(benchmarkTreeSize)
|
||||
b.StartTimer()
|
||||
i := 0
|
||||
for i < b.N {
|
||||
b.StopTimer()
|
||||
tr := New(*btreeDegree)
|
||||
for _, v := range insertP {
|
||||
tr.ReplaceOrInsert(v)
|
||||
}
|
||||
b.StartTimer()
|
||||
for _, item := range removeP {
|
||||
tr = tr.Clone()
|
||||
tr.Get(item)
|
||||
i++
|
||||
if i >= b.N {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type byInts []Item
|
||||
|
||||
func (a byInts) Len() int {
|
||||
return len(a)
|
||||
}
|
||||
|
||||
func (a byInts) Less(i, j int) bool {
|
||||
return a[i].(Int) < a[j].(Int)
|
||||
}
|
||||
|
||||
func (a byInts) Swap(i, j int) {
|
||||
a[i], a[j] = a[j], a[i]
|
||||
}
|
||||
|
||||
func BenchmarkAscend(b *testing.B) {
|
||||
arr := perm(benchmarkTreeSize)
|
||||
tr := New(*btreeDegree)
|
||||
for _, v := range arr {
|
||||
tr.ReplaceOrInsert(v)
|
||||
}
|
||||
sort.Sort(byInts(arr))
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
j := 0
|
||||
tr.Ascend(func(item Item) bool {
|
||||
if item.(Int) != arr[j].(Int) {
|
||||
b.Fatalf("mismatch: expected: %v, got %v", arr[j].(Int), item.(Int))
|
||||
}
|
||||
j++
|
||||
return true
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkDescend(b *testing.B) {
|
||||
arr := perm(benchmarkTreeSize)
|
||||
tr := New(*btreeDegree)
|
||||
for _, v := range arr {
|
||||
tr.ReplaceOrInsert(v)
|
||||
}
|
||||
sort.Sort(byInts(arr))
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
j := len(arr) - 1
|
||||
tr.Descend(func(item Item) bool {
|
||||
if item.(Int) != arr[j].(Int) {
|
||||
b.Fatalf("mismatch: expected: %v, got %v", arr[j].(Int), item.(Int))
|
||||
}
|
||||
j--
|
||||
return true
|
||||
})
|
||||
}
|
||||
}
|
||||
func BenchmarkAscendRange(b *testing.B) {
|
||||
arr := perm(benchmarkTreeSize)
|
||||
tr := New(*btreeDegree)
|
||||
for _, v := range arr {
|
||||
tr.ReplaceOrInsert(v)
|
||||
}
|
||||
sort.Sort(byInts(arr))
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
j := 100
|
||||
tr.AscendRange(Int(100), arr[len(arr)-100], func(item Item) bool {
|
||||
if item.(Int) != arr[j].(Int) {
|
||||
b.Fatalf("mismatch: expected: %v, got %v", arr[j].(Int), item.(Int))
|
||||
}
|
||||
j++
|
||||
return true
|
||||
})
|
||||
if j != len(arr)-100 {
|
||||
b.Fatalf("expected: %v, got %v", len(arr)-100, j)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkDescendRange(b *testing.B) {
|
||||
arr := perm(benchmarkTreeSize)
|
||||
tr := New(*btreeDegree)
|
||||
for _, v := range arr {
|
||||
tr.ReplaceOrInsert(v)
|
||||
}
|
||||
sort.Sort(byInts(arr))
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
j := len(arr) - 100
|
||||
tr.DescendRange(arr[len(arr)-100], Int(100), func(item Item) bool {
|
||||
if item.(Int) != arr[j].(Int) {
|
||||
b.Fatalf("mismatch: expected: %v, got %v", arr[j].(Int), item.(Int))
|
||||
}
|
||||
j--
|
||||
return true
|
||||
})
|
||||
if j != 100 {
|
||||
b.Fatalf("expected: %v, got %v", len(arr)-100, j)
|
||||
}
|
||||
}
|
||||
}
|
||||
func BenchmarkAscendGreaterOrEqual(b *testing.B) {
|
||||
arr := perm(benchmarkTreeSize)
|
||||
tr := New(*btreeDegree)
|
||||
for _, v := range arr {
|
||||
tr.ReplaceOrInsert(v)
|
||||
}
|
||||
sort.Sort(byInts(arr))
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
j := 100
|
||||
k := 0
|
||||
tr.AscendGreaterOrEqual(Int(100), func(item Item) bool {
|
||||
if item.(Int) != arr[j].(Int) {
|
||||
b.Fatalf("mismatch: expected: %v, got %v", arr[j].(Int), item.(Int))
|
||||
}
|
||||
j++
|
||||
k++
|
||||
return true
|
||||
})
|
||||
if j != len(arr) {
|
||||
b.Fatalf("expected: %v, got %v", len(arr), j)
|
||||
}
|
||||
if k != len(arr)-100 {
|
||||
b.Fatalf("expected: %v, got %v", len(arr)-100, k)
|
||||
}
|
||||
}
|
||||
}
|
||||
func BenchmarkDescendLessOrEqual(b *testing.B) {
|
||||
arr := perm(benchmarkTreeSize)
|
||||
tr := New(*btreeDegree)
|
||||
for _, v := range arr {
|
||||
tr.ReplaceOrInsert(v)
|
||||
}
|
||||
sort.Sort(byInts(arr))
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
j := len(arr) - 100
|
||||
k := len(arr)
|
||||
tr.DescendLessOrEqual(arr[len(arr)-100], func(item Item) bool {
|
||||
if item.(Int) != arr[j].(Int) {
|
||||
b.Fatalf("mismatch: expected: %v, got %v", arr[j].(Int), item.(Int))
|
||||
}
|
||||
j--
|
||||
k--
|
||||
return true
|
||||
})
|
||||
if j != -1 {
|
||||
b.Fatalf("expected: %v, got %v", -1, j)
|
||||
}
|
||||
if k != 99 {
|
||||
b.Fatalf("expected: %v, got %v", 99, k)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const cloneTestSize = 10000
|
||||
|
||||
func cloneTest(t *testing.T, b *BTree, start int, p []Item, wg *sync.WaitGroup, trees *[]*BTree) {
|
||||
t.Logf("Starting new clone at %v", start)
|
||||
*trees = append(*trees, b)
|
||||
for i := start; i < cloneTestSize; i++ {
|
||||
b.ReplaceOrInsert(p[i])
|
||||
if i%(cloneTestSize/5) == 0 {
|
||||
wg.Add(1)
|
||||
go cloneTest(t, b.Clone(), i+1, p, wg, trees)
|
||||
}
|
||||
}
|
||||
wg.Done()
|
||||
}
|
||||
|
||||
func TestCloneConcurrentOperations(t *testing.T) {
|
||||
b := New(*btreeDegree)
|
||||
trees := []*BTree{}
|
||||
p := perm(cloneTestSize)
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(1)
|
||||
go cloneTest(t, b, 0, p, &wg, &trees)
|
||||
wg.Wait()
|
||||
want := rang(cloneTestSize)
|
||||
t.Logf("Starting equality checks on %d trees", len(trees))
|
||||
for i, tree := range trees {
|
||||
if !reflect.DeepEqual(want, all(tree)) {
|
||||
t.Errorf("tree %v mismatch", i)
|
||||
}
|
||||
}
|
||||
t.Log("Removing half from first half")
|
||||
toRemove := rang(cloneTestSize)[cloneTestSize/2:]
|
||||
for i := 0; i < len(trees)/2; i++ {
|
||||
tree := trees[i]
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
for _, item := range toRemove {
|
||||
tree.Delete(item)
|
||||
}
|
||||
wg.Done()
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
t.Log("Checking all values again")
|
||||
for i, tree := range trees {
|
||||
var wantpart []Item
|
||||
if i < len(trees)/2 {
|
||||
wantpart = want[:cloneTestSize/2]
|
||||
} else {
|
||||
wantpart = want
|
||||
}
|
||||
if got := all(tree); !reflect.DeepEqual(wantpart, got) {
|
||||
t.Errorf("tree %v mismatch, want %v got %v", i, len(want), len(got))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,19 +0,0 @@
|
|||
sudo: false
|
||||
language: go
|
||||
go:
|
||||
- 1.6.x
|
||||
- 1.7.x
|
||||
- 1.8.x
|
||||
- 1.9.x
|
||||
- master
|
||||
matrix:
|
||||
allow_failures:
|
||||
- go: master
|
||||
fast_finish: true
|
||||
install:
|
||||
- # Do nothing. This is needed to prevent default install action "go get -t -v ./..." from happening here (we want it to happen inside script step).
|
||||
script:
|
||||
- go get -t -v ./...
|
||||
- diff -u <(echo -n) <(gofmt -d .)
|
||||
- go tool vet .
|
||||
- go test -v -race ./...
|
||||
|
|
@ -1,7 +0,0 @@
|
|||
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.
|
||||
|
|
@ -1,25 +0,0 @@
|
|||
httpcache
|
||||
=========
|
||||
|
||||
[](https://travis-ci.org/gregjones/httpcache) [](https://godoc.org/github.com/gregjones/httpcache)
|
||||
|
||||
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).
|
||||
|
||||
Cache Backends
|
||||
--------------
|
||||
|
||||
- The built-in 'memory' cache stores responses in an in-memory map.
|
||||
- [`github.com/gregjones/httpcache/diskcache`](https://github.com/gregjones/httpcache/tree/master/diskcache) provides a filesystem-backed cache using the [diskv](https://github.com/peterbourgon/diskv) library.
|
||||
- [`github.com/gregjones/httpcache/memcache`](https://github.com/gregjones/httpcache/tree/master/memcache) provides memcache implementations, for both App Engine and 'normal' memcache servers.
|
||||
- [`sourcegraph.com/sourcegraph/s3cache`](https://sourcegraph.com/github.com/sourcegraph/s3cache) uses Amazon S3 for storage.
|
||||
- [`github.com/gregjones/httpcache/leveldbcache`](https://github.com/gregjones/httpcache/tree/master/leveldbcache) provides a filesystem-backed cache using [leveldb](https://github.com/syndtr/goleveldb/leveldb).
|
||||
- [`github.com/die-net/lrucache`](https://github.com/die-net/lrucache) provides an in-memory cache that will evict least-recently used entries.
|
||||
- [`github.com/die-net/lrucache/twotier`](https://github.com/die-net/lrucache/tree/master/twotier) allows caches to be combined, for example to use lrucache above with a persistent disk-cache.
|
||||
- [`github.com/birkelund/boltdbcache`](https://github.com/birkelund/boltdbcache) provides a BoltDB implementation (based on the [bbolt](https://github.com/coreos/bbolt) fork).
|
||||
|
||||
License
|
||||
-------
|
||||
|
||||
- [MIT License](LICENSE.txt)
|
||||
|
|
@ -1,61 +0,0 @@
|
|||
// Package diskcache provides an implementation of httpcache.Cache that uses the diskv package
|
||||
// to supplement an in-memory map with persistent storage
|
||||
//
|
||||
package diskcache
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/md5"
|
||||
"encoding/hex"
|
||||
"github.com/peterbourgon/diskv"
|
||||
"io"
|
||||
)
|
||||
|
||||
// Cache is an implementation of httpcache.Cache that supplements the in-memory map with persistent storage
|
||||
type Cache struct {
|
||||
d *diskv.Diskv
|
||||
}
|
||||
|
||||
// Get returns the response corresponding to key if present
|
||||
func (c *Cache) Get(key string) (resp []byte, ok bool) {
|
||||
key = keyToFilename(key)
|
||||
resp, err := c.d.Read(key)
|
||||
if err != nil {
|
||||
return []byte{}, false
|
||||
}
|
||||
return resp, true
|
||||
}
|
||||
|
||||
// Set saves a response to the cache as key
|
||||
func (c *Cache) Set(key string, resp []byte) {
|
||||
key = keyToFilename(key)
|
||||
c.d.WriteStream(key, bytes.NewReader(resp), true)
|
||||
}
|
||||
|
||||
// Delete removes the response with key from the cache
|
||||
func (c *Cache) Delete(key string) {
|
||||
key = keyToFilename(key)
|
||||
c.d.Erase(key)
|
||||
}
|
||||
|
||||
func keyToFilename(key string) string {
|
||||
h := md5.New()
|
||||
io.WriteString(h, key)
|
||||
return hex.EncodeToString(h.Sum(nil))
|
||||
}
|
||||
|
||||
// New returns a new Cache that will store files in basePath
|
||||
func New(basePath string) *Cache {
|
||||
return &Cache{
|
||||
d: diskv.New(diskv.Options{
|
||||
BasePath: basePath,
|
||||
CacheSizeMax: 100 * 1024 * 1024, // 100MB
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
// NewWithDiskv returns a new Cache using the provided Diskv as underlying
|
||||
// storage.
|
||||
func NewWithDiskv(d *diskv.Diskv) *Cache {
|
||||
return &Cache{d}
|
||||
}
|
||||
|
|
@ -1,42 +0,0 @@
|
|||
package diskcache
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDiskCache(t *testing.T) {
|
||||
tempDir, err := ioutil.TempDir("", "httpcache")
|
||||
if err != nil {
|
||||
t.Fatalf("TempDir: %v", err)
|
||||
}
|
||||
defer os.RemoveAll(tempDir)
|
||||
|
||||
cache := New(tempDir)
|
||||
|
||||
key := "testKey"
|
||||
_, ok := cache.Get(key)
|
||||
if ok {
|
||||
t.Fatal("retrieved key before adding it")
|
||||
}
|
||||
|
||||
val := []byte("some bytes")
|
||||
cache.Set(key, val)
|
||||
|
||||
retVal, ok := cache.Get(key)
|
||||
if !ok {
|
||||
t.Fatal("could not retrieve an element we just added")
|
||||
}
|
||||
if !bytes.Equal(retVal, val) {
|
||||
t.Fatal("retrieved a different value than what we put in")
|
||||
}
|
||||
|
||||
cache.Delete(key)
|
||||
|
||||
_, ok = cache.Get(key)
|
||||
if ok {
|
||||
t.Fatal("deleted key still present")
|
||||
}
|
||||
}
|
||||
|
|
@ -1,551 +0,0 @@
|
|||
// 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": struct{}{},
|
||||
"Keep-Alive": struct{}{},
|
||||
"Proxy-Authenticate": struct{}{},
|
||||
"Proxy-Authorization": struct{}{},
|
||||
"Te": struct{}{},
|
||||
"Trailers": struct{}{},
|
||||
"Transfer-Encoding": struct{}{},
|
||||
"Upgrade": struct{}{},
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -1,51 +0,0 @@
|
|||
// Package leveldbcache provides an implementation of httpcache.Cache that
|
||||
// uses github.com/syndtr/goleveldb/leveldb
|
||||
package leveldbcache
|
||||
|
||||
import (
|
||||
"github.com/syndtr/goleveldb/leveldb"
|
||||
)
|
||||
|
||||
// Cache is an implementation of httpcache.Cache with leveldb storage
|
||||
type Cache struct {
|
||||
db *leveldb.DB
|
||||
}
|
||||
|
||||
// Get returns the response corresponding to key if present
|
||||
func (c *Cache) Get(key string) (resp []byte, ok bool) {
|
||||
var err error
|
||||
resp, err = c.db.Get([]byte(key), nil)
|
||||
if err != nil {
|
||||
return []byte{}, false
|
||||
}
|
||||
return resp, true
|
||||
}
|
||||
|
||||
// Set saves a response to the cache as key
|
||||
func (c *Cache) Set(key string, resp []byte) {
|
||||
c.db.Put([]byte(key), resp, nil)
|
||||
}
|
||||
|
||||
// Delete removes the response with key from the cache
|
||||
func (c *Cache) Delete(key string) {
|
||||
c.db.Delete([]byte(key), nil)
|
||||
}
|
||||
|
||||
// New returns a new Cache that will store leveldb in path
|
||||
func New(path string) (*Cache, error) {
|
||||
cache := &Cache{}
|
||||
|
||||
var err error
|
||||
cache.db, err = leveldb.OpenFile(path, nil)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return cache, nil
|
||||
}
|
||||
|
||||
// NewWithDB returns a new Cache using the provided leveldb as underlying
|
||||
// storage.
|
||||
func NewWithDB(db *leveldb.DB) *Cache {
|
||||
return &Cache{db}
|
||||
}
|
||||
|
|
@ -1,46 +0,0 @@
|
|||
package leveldbcache
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDiskCache(t *testing.T) {
|
||||
tempDir, err := ioutil.TempDir("", "httpcache")
|
||||
if err != nil {
|
||||
t.Fatalf("TempDir: %v", err)
|
||||
}
|
||||
defer os.RemoveAll(tempDir)
|
||||
|
||||
cache, err := New(filepath.Join(tempDir, "db"))
|
||||
if err != nil {
|
||||
t.Fatalf("New leveldb,: %v", err)
|
||||
}
|
||||
|
||||
key := "testKey"
|
||||
_, ok := cache.Get(key)
|
||||
if ok {
|
||||
t.Fatal("retrieved key before adding it")
|
||||
}
|
||||
|
||||
val := []byte("some bytes")
|
||||
cache.Set(key, val)
|
||||
|
||||
retVal, ok := cache.Get(key)
|
||||
if !ok {
|
||||
t.Fatal("could not retrieve an element we just added")
|
||||
}
|
||||
if !bytes.Equal(retVal, val) {
|
||||
t.Fatal("retrieved a different value than what we put in")
|
||||
}
|
||||
|
||||
cache.Delete(key)
|
||||
|
||||
_, ok = cache.Get(key)
|
||||
if ok {
|
||||
t.Fatal("deleted key still present")
|
||||
}
|
||||
}
|
||||
|
|
@ -1,61 +0,0 @@
|
|||
// +build appengine
|
||||
|
||||
// Package memcache provides an implementation of httpcache.Cache that uses App
|
||||
// Engine's memcache package to store cached responses.
|
||||
//
|
||||
// When not built for Google App Engine, this package will provide an
|
||||
// implementation that connects to a specified memcached server. See the
|
||||
// memcache.go file in this package for details.
|
||||
package memcache
|
||||
|
||||
import (
|
||||
"appengine"
|
||||
"appengine/memcache"
|
||||
)
|
||||
|
||||
// Cache is an implementation of httpcache.Cache that caches responses in App
|
||||
// Engine's memcache.
|
||||
type Cache struct {
|
||||
appengine.Context
|
||||
}
|
||||
|
||||
// cacheKey modifies an httpcache key for use in memcache. Specifically, it
|
||||
// prefixes keys to avoid collision with other data stored in memcache.
|
||||
func cacheKey(key string) string {
|
||||
return "httpcache:" + key
|
||||
}
|
||||
|
||||
// Get returns the response corresponding to key if present.
|
||||
func (c *Cache) Get(key string) (resp []byte, ok bool) {
|
||||
item, err := memcache.Get(c.Context, cacheKey(key))
|
||||
if err != nil {
|
||||
if err != memcache.ErrCacheMiss {
|
||||
c.Context.Errorf("error getting cached response: %v", err)
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
return item.Value, true
|
||||
}
|
||||
|
||||
// Set saves a response to the cache as key.
|
||||
func (c *Cache) Set(key string, resp []byte) {
|
||||
item := &memcache.Item{
|
||||
Key: cacheKey(key),
|
||||
Value: resp,
|
||||
}
|
||||
if err := memcache.Set(c.Context, item); err != nil {
|
||||
c.Context.Errorf("error caching response: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Delete removes the response with key from the cache.
|
||||
func (c *Cache) Delete(key string) {
|
||||
if err := memcache.Delete(c.Context, cacheKey(key)); err != nil {
|
||||
c.Context.Errorf("error deleting cached response: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// New returns a new Cache for the given context.
|
||||
func New(ctx appengine.Context) *Cache {
|
||||
return &Cache{ctx}
|
||||
}
|
||||
|
|
@ -1,44 +0,0 @@
|
|||
// +build appengine
|
||||
|
||||
package memcache
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
|
||||
"appengine/aetest"
|
||||
)
|
||||
|
||||
func TestAppEngine(t *testing.T) {
|
||||
ctx, err := aetest.NewContext(nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer ctx.Close()
|
||||
|
||||
cache := New(ctx)
|
||||
|
||||
key := "testKey"
|
||||
_, ok := cache.Get(key)
|
||||
if ok {
|
||||
t.Fatal("retrieved key before adding it")
|
||||
}
|
||||
|
||||
val := []byte("some bytes")
|
||||
cache.Set(key, val)
|
||||
|
||||
retVal, ok := cache.Get(key)
|
||||
if !ok {
|
||||
t.Fatal("could not retrieve an element we just added")
|
||||
}
|
||||
if !bytes.Equal(retVal, val) {
|
||||
t.Fatal("retrieved a different value than what we put in")
|
||||
}
|
||||
|
||||
cache.Delete(key)
|
||||
|
||||
_, ok = cache.Get(key)
|
||||
if ok {
|
||||
t.Fatal("deleted key still present")
|
||||
}
|
||||
}
|
||||
|
|
@ -1,60 +0,0 @@
|
|||
// +build !appengine
|
||||
|
||||
// Package memcache provides an implementation of httpcache.Cache that uses
|
||||
// gomemcache to store cached responses.
|
||||
//
|
||||
// When built for Google App Engine, this package will provide an
|
||||
// implementation that uses App Engine's memcache service. See the
|
||||
// appengine.go file in this package for details.
|
||||
package memcache
|
||||
|
||||
import (
|
||||
"github.com/bradfitz/gomemcache/memcache"
|
||||
)
|
||||
|
||||
// Cache is an implementation of httpcache.Cache that caches responses in a
|
||||
// memcache server.
|
||||
type Cache struct {
|
||||
*memcache.Client
|
||||
}
|
||||
|
||||
// cacheKey modifies an httpcache key for use in memcache. Specifically, it
|
||||
// prefixes keys to avoid collision with other data stored in memcache.
|
||||
func cacheKey(key string) string {
|
||||
return "httpcache:" + key
|
||||
}
|
||||
|
||||
// Get returns the response corresponding to key if present.
|
||||
func (c *Cache) Get(key string) (resp []byte, ok bool) {
|
||||
item, err := c.Client.Get(cacheKey(key))
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
return item.Value, true
|
||||
}
|
||||
|
||||
// Set saves a response to the cache as key.
|
||||
func (c *Cache) Set(key string, resp []byte) {
|
||||
item := &memcache.Item{
|
||||
Key: cacheKey(key),
|
||||
Value: resp,
|
||||
}
|
||||
c.Client.Set(item)
|
||||
}
|
||||
|
||||
// Delete removes the response with key from the cache.
|
||||
func (c *Cache) Delete(key string) {
|
||||
c.Client.Delete(cacheKey(key))
|
||||
}
|
||||
|
||||
// New returns a new Cache using the provided memcache server(s) with equal
|
||||
// weight. If a server is listed multiple times, it gets a proportional amount
|
||||
// of weight.
|
||||
func New(server ...string) *Cache {
|
||||
return NewWithClient(memcache.New(server...))
|
||||
}
|
||||
|
||||
// NewWithClient returns a new Cache with the given memcache client.
|
||||
func NewWithClient(client *memcache.Client) *Cache {
|
||||
return &Cache{client}
|
||||
}
|
||||
|
|
@ -1,47 +0,0 @@
|
|||
// +build !appengine
|
||||
|
||||
package memcache
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"net"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const testServer = "localhost:11211"
|
||||
|
||||
func TestMemCache(t *testing.T) {
|
||||
conn, err := net.Dial("tcp", testServer)
|
||||
if err != nil {
|
||||
// TODO: rather than skip the test, fall back to a faked memcached server
|
||||
t.Skipf("skipping test; no server running at %s", testServer)
|
||||
}
|
||||
conn.Write([]byte("flush_all\r\n")) // flush memcache
|
||||
conn.Close()
|
||||
|
||||
cache := New(testServer)
|
||||
|
||||
key := "testKey"
|
||||
_, ok := cache.Get(key)
|
||||
if ok {
|
||||
t.Fatal("retrieved key before adding it")
|
||||
}
|
||||
|
||||
val := []byte("some bytes")
|
||||
cache.Set(key, val)
|
||||
|
||||
retVal, ok := cache.Get(key)
|
||||
if !ok {
|
||||
t.Fatal("could not retrieve an element we just added")
|
||||
}
|
||||
if !bytes.Equal(retVal, val) {
|
||||
t.Fatal("retrieved a different value than what we put in")
|
||||
}
|
||||
|
||||
cache.Delete(key)
|
||||
|
||||
_, ok = cache.Get(key)
|
||||
if ok {
|
||||
t.Fatal("deleted key still present")
|
||||
}
|
||||
}
|
||||
|
|
@ -1,43 +0,0 @@
|
|||
// Package redis provides a redis interface for http caching.
|
||||
package redis
|
||||
|
||||
import (
|
||||
"github.com/garyburd/redigo/redis"
|
||||
"github.com/gregjones/httpcache"
|
||||
)
|
||||
|
||||
// cache is an implementation of httpcache.Cache that caches responses in a
|
||||
// redis server.
|
||||
type cache struct {
|
||||
redis.Conn
|
||||
}
|
||||
|
||||
// cacheKey modifies an httpcache key for use in redis. Specifically, it
|
||||
// prefixes keys to avoid collision with other data stored in redis.
|
||||
func cacheKey(key string) string {
|
||||
return "rediscache:" + key
|
||||
}
|
||||
|
||||
// Get returns the response corresponding to key if present.
|
||||
func (c cache) Get(key string) (resp []byte, ok bool) {
|
||||
item, err := redis.Bytes(c.Do("GET", cacheKey(key)))
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
return item, true
|
||||
}
|
||||
|
||||
// Set saves a response to the cache as key.
|
||||
func (c cache) Set(key string, resp []byte) {
|
||||
c.Do("SET", cacheKey(key), resp)
|
||||
}
|
||||
|
||||
// Delete removes the response with key from the cache.
|
||||
func (c cache) Delete(key string) {
|
||||
c.Do("DEL", cacheKey(key))
|
||||
}
|
||||
|
||||
// NewWithClient returns a new Cache with the given redis connection.
|
||||
func NewWithClient(client redis.Conn) httpcache.Cache {
|
||||
return cache{client}
|
||||
}
|
||||
|
|
@ -1,43 +0,0 @@
|
|||
package redis
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
|
||||
"github.com/garyburd/redigo/redis"
|
||||
)
|
||||
|
||||
func TestRedisCache(t *testing.T) {
|
||||
conn, err := redis.Dial("tcp", "localhost:6379")
|
||||
if err != nil {
|
||||
// TODO: rather than skip the test, fall back to a faked redis server
|
||||
t.Skipf("skipping test; no server running at localhost:6379")
|
||||
}
|
||||
conn.Do("FLUSHALL")
|
||||
|
||||
cache := NewWithClient(conn)
|
||||
|
||||
key := "testKey"
|
||||
_, ok := cache.Get(key)
|
||||
if ok {
|
||||
t.Fatal("retrieved key before adding it")
|
||||
}
|
||||
|
||||
val := []byte("some bytes")
|
||||
cache.Set(key, val)
|
||||
|
||||
retVal, ok := cache.Get(key)
|
||||
if !ok {
|
||||
t.Fatal("could not retrieve an element we just added")
|
||||
}
|
||||
if !bytes.Equal(retVal, val) {
|
||||
t.Fatal("retrieved a different value than what we put in")
|
||||
}
|
||||
|
||||
cache.Delete(key)
|
||||
|
||||
_, ok = cache.Get(key)
|
||||
if ok {
|
||||
t.Fatal("deleted key still present")
|
||||
}
|
||||
}
|
||||
|
|
@ -1,11 +0,0 @@
|
|||
language: go
|
||||
|
||||
os:
|
||||
- linux
|
||||
- osx
|
||||
|
||||
go:
|
||||
- 1.3
|
||||
- 1.4
|
||||
- 1.5
|
||||
- tip
|
||||
|
|
@ -1,15 +0,0 @@
|
|||
ISC License
|
||||
|
||||
Copyright (c) 2012 Chris Howey
|
||||
|
||||
Permission to use, copy, modify, and distribute this software for any
|
||||
purpose with or without fee is hereby granted, provided that the above
|
||||
copyright notice and this permission notice appear in all copies.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
|
|
@ -1,384 +0,0 @@
|
|||
Unless otherwise noted, all files in this distribution are released
|
||||
under the Common Development and Distribution License (CDDL).
|
||||
Exceptions are noted within the associated source files.
|
||||
|
||||
--------------------------------------------------------------------
|
||||
|
||||
|
||||
COMMON DEVELOPMENT AND DISTRIBUTION LICENSE Version 1.0
|
||||
|
||||
1. Definitions.
|
||||
|
||||
1.1. "Contributor" means each individual or entity that creates
|
||||
or contributes to the creation of Modifications.
|
||||
|
||||
1.2. "Contributor Version" means the combination of the Original
|
||||
Software, prior Modifications used by a Contributor (if any),
|
||||
and the Modifications made by that particular Contributor.
|
||||
|
||||
1.3. "Covered Software" means (a) the Original Software, or (b)
|
||||
Modifications, or (c) the combination of files containing
|
||||
Original Software with files containing Modifications, in
|
||||
each case including portions thereof.
|
||||
|
||||
1.4. "Executable" means the Covered Software in any form other
|
||||
than Source Code.
|
||||
|
||||
1.5. "Initial Developer" means the individual or entity that first
|
||||
makes Original Software available under this License.
|
||||
|
||||
1.6. "Larger Work" means a work which combines Covered Software or
|
||||
portions thereof with code not governed by the terms of this
|
||||
License.
|
||||
|
||||
1.7. "License" means this document.
|
||||
|
||||
1.8. "Licensable" means having the right to grant, to the maximum
|
||||
extent possible, whether at the time of the initial grant or
|
||||
subsequently acquired, any and all of the rights conveyed
|
||||
herein.
|
||||
|
||||
1.9. "Modifications" means the Source Code and Executable form of
|
||||
any of the following:
|
||||
|
||||
A. Any file that results from an addition to, deletion from or
|
||||
modification of the contents of a file containing Original
|
||||
Software or previous Modifications;
|
||||
|
||||
B. Any new file that contains any part of the Original
|
||||
Software or previous Modifications; or
|
||||
|
||||
C. Any new file that is contributed or otherwise made
|
||||
available under the terms of this License.
|
||||
|
||||
1.10. "Original Software" means the Source Code and Executable
|
||||
form of computer software code that is originally released
|
||||
under this License.
|
||||
|
||||
1.11. "Patent Claims" means any patent claim(s), now owned or
|
||||
hereafter acquired, including without limitation, method,
|
||||
process, and apparatus claims, in any patent Licensable by
|
||||
grantor.
|
||||
|
||||
1.12. "Source Code" means (a) the common form of computer software
|
||||
code in which modifications are made and (b) associated
|
||||
documentation included in or with such code.
|
||||
|
||||
1.13. "You" (or "Your") means an individual or a legal entity
|
||||
exercising rights under, and complying with all of the terms
|
||||
of, this License. For legal entities, "You" includes any
|
||||
entity which controls, is controlled by, or is under common
|
||||
control with You. For purposes of this definition,
|
||||
"control" means (a) the power, direct or indirect, to cause
|
||||
the direction or management of such entity, whether by
|
||||
contract or otherwise, or (b) ownership of more than fifty
|
||||
percent (50%) of the outstanding shares or beneficial
|
||||
ownership of such entity.
|
||||
|
||||
2. License Grants.
|
||||
|
||||
2.1. The Initial Developer Grant.
|
||||
|
||||
Conditioned upon Your compliance with Section 3.1 below and
|
||||
subject to third party intellectual property claims, the Initial
|
||||
Developer hereby grants You a world-wide, royalty-free,
|
||||
non-exclusive license:
|
||||
|
||||
(a) under intellectual property rights (other than patent or
|
||||
trademark) Licensable by Initial Developer, to use,
|
||||
reproduce, modify, display, perform, sublicense and
|
||||
distribute the Original Software (or portions thereof),
|
||||
with or without Modifications, and/or as part of a Larger
|
||||
Work; and
|
||||
|
||||
(b) under Patent Claims infringed by the making, using or
|
||||
selling of Original Software, to make, have made, use,
|
||||
practice, sell, and offer for sale, and/or otherwise
|
||||
dispose of the Original Software (or portions thereof).
|
||||
|
||||
(c) The licenses granted in Sections 2.1(a) and (b) are
|
||||
effective on the date Initial Developer first distributes
|
||||
or otherwise makes the Original Software available to a
|
||||
third party under the terms of this License.
|
||||
|
||||
(d) Notwithstanding Section 2.1(b) above, no patent license is
|
||||
granted: (1) for code that You delete from the Original
|
||||
Software, or (2) for infringements caused by: (i) the
|
||||
modification of the Original Software, or (ii) the
|
||||
combination of the Original Software with other software
|
||||
or devices.
|
||||
|
||||
2.2. Contributor Grant.
|
||||
|
||||
Conditioned upon Your compliance with Section 3.1 below and
|
||||
subject to third party intellectual property claims, each
|
||||
Contributor hereby grants You a world-wide, royalty-free,
|
||||
non-exclusive license:
|
||||
|
||||
(a) under intellectual property rights (other than patent or
|
||||
trademark) Licensable by Contributor to use, reproduce,
|
||||
modify, display, perform, sublicense and distribute the
|
||||
Modifications created by such Contributor (or portions
|
||||
thereof), either on an unmodified basis, with other
|
||||
Modifications, as Covered Software and/or as part of a
|
||||
Larger Work; and
|
||||
|
||||
(b) under Patent Claims infringed by the making, using, or
|
||||
selling of Modifications made by that Contributor either
|
||||
alone and/or in combination with its Contributor Version
|
||||
(or portions of such combination), to make, use, sell,
|
||||
offer for sale, have made, and/or otherwise dispose of:
|
||||
(1) Modifications made by that Contributor (or portions
|
||||
thereof); and (2) the combination of Modifications made by
|
||||
that Contributor with its Contributor Version (or portions
|
||||
of such combination).
|
||||
|
||||
(c) The licenses granted in Sections 2.2(a) and 2.2(b) are
|
||||
effective on the date Contributor first distributes or
|
||||
otherwise makes the Modifications available to a third
|
||||
party.
|
||||
|
||||
(d) Notwithstanding Section 2.2(b) above, no patent license is
|
||||
granted: (1) for any code that Contributor has deleted
|
||||
from the Contributor Version; (2) for infringements caused
|
||||
by: (i) third party modifications of Contributor Version,
|
||||
or (ii) the combination of Modifications made by that
|
||||
Contributor with other software (except as part of the
|
||||
Contributor Version) or other devices; or (3) under Patent
|
||||
Claims infringed by Covered Software in the absence of
|
||||
Modifications made by that Contributor.
|
||||
|
||||
3. Distribution Obligations.
|
||||
|
||||
3.1. Availability of Source Code.
|
||||
|
||||
Any Covered Software that You distribute or otherwise make
|
||||
available in Executable form must also be made available in Source
|
||||
Code form and that Source Code form must be distributed only under
|
||||
the terms of this License. You must include a copy of this
|
||||
License with every copy of the Source Code form of the Covered
|
||||
Software You distribute or otherwise make available. You must
|
||||
inform recipients of any such Covered Software in Executable form
|
||||
as to how they can obtain such Covered Software in Source Code
|
||||
form in a reasonable manner on or through a medium customarily
|
||||
used for software exchange.
|
||||
|
||||
3.2. Modifications.
|
||||
|
||||
The Modifications that You create or to which You contribute are
|
||||
governed by the terms of this License. You represent that You
|
||||
believe Your Modifications are Your original creation(s) and/or
|
||||
You have sufficient rights to grant the rights conveyed by this
|
||||
License.
|
||||
|
||||
3.3. Required Notices.
|
||||
|
||||
You must include a notice in each of Your Modifications that
|
||||
identifies You as the Contributor of the Modification. You may
|
||||
not remove or alter any copyright, patent or trademark notices
|
||||
contained within the Covered Software, or any notices of licensing
|
||||
or any descriptive text giving attribution to any Contributor or
|
||||
the Initial Developer.
|
||||
|
||||
3.4. Application of Additional Terms.
|
||||
|
||||
You may not offer or impose any terms on any Covered Software in
|
||||
Source Code form that alters or restricts the applicable version
|
||||
of this License or the recipients' rights hereunder. You may
|
||||
choose to offer, and to charge a fee for, warranty, support,
|
||||
indemnity or liability obligations to one or more recipients of
|
||||
Covered Software. However, you may do so only on Your own behalf,
|
||||
and not on behalf of the Initial Developer or any Contributor.
|
||||
You must make it absolutely clear that any such warranty, support,
|
||||
indemnity or liability obligation is offered by You alone, and You
|
||||
hereby agree to indemnify the Initial Developer and every
|
||||
Contributor for any liability incurred by the Initial Developer or
|
||||
such Contributor as a result of warranty, support, indemnity or
|
||||
liability terms You offer.
|
||||
|
||||
3.5. Distribution of Executable Versions.
|
||||
|
||||
You may distribute the Executable form of the Covered Software
|
||||
under the terms of this License or under the terms of a license of
|
||||
Your choice, which may contain terms different from this License,
|
||||
provided that You are in compliance with the terms of this License
|
||||
and that the license for the Executable form does not attempt to
|
||||
limit or alter the recipient's rights in the Source Code form from
|
||||
the rights set forth in this License. If You distribute the
|
||||
Covered Software in Executable form under a different license, You
|
||||
must make it absolutely clear that any terms which differ from
|
||||
this License are offered by You alone, not by the Initial
|
||||
Developer or Contributor. You hereby agree to indemnify the
|
||||
Initial Developer and every Contributor for any liability incurred
|
||||
by the Initial Developer or such Contributor as a result of any
|
||||
such terms You offer.
|
||||
|
||||
3.6. Larger Works.
|
||||
|
||||
You may create a Larger Work by combining Covered Software with
|
||||
other code not governed by the terms of this License and
|
||||
distribute the Larger Work as a single product. In such a case,
|
||||
You must make sure the requirements of this License are fulfilled
|
||||
for the Covered Software.
|
||||
|
||||
4. Versions of the License.
|
||||
|
||||
4.1. New Versions.
|
||||
|
||||
Sun Microsystems, Inc. is the initial license steward and may
|
||||
publish revised and/or new versions of this License from time to
|
||||
time. Each version will be given a distinguishing version number.
|
||||
Except as provided in Section 4.3, no one other than the license
|
||||
steward has the right to modify this License.
|
||||
|
||||
4.2. Effect of New Versions.
|
||||
|
||||
You may always continue to use, distribute or otherwise make the
|
||||
Covered Software available under the terms of the version of the
|
||||
License under which You originally received the Covered Software.
|
||||
If the Initial Developer includes a notice in the Original
|
||||
Software prohibiting it from being distributed or otherwise made
|
||||
available under any subsequent version of the License, You must
|
||||
distribute and make the Covered Software available under the terms
|
||||
of the version of the License under which You originally received
|
||||
the Covered Software. Otherwise, You may also choose to use,
|
||||
distribute or otherwise make the Covered Software available under
|
||||
the terms of any subsequent version of the License published by
|
||||
the license steward.
|
||||
|
||||
4.3. Modified Versions.
|
||||
|
||||
When You are an Initial Developer and You want to create a new
|
||||
license for Your Original Software, You may create and use a
|
||||
modified version of this License if You: (a) rename the license
|
||||
and remove any references to the name of the license steward
|
||||
(except to note that the license differs from this License); and
|
||||
(b) otherwise make it clear that the license contains terms which
|
||||
differ from this License.
|
||||
|
||||
5. DISCLAIMER OF WARRANTY.
|
||||
|
||||
COVERED SOFTWARE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS"
|
||||
BASIS, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED,
|
||||
INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE COVERED
|
||||
SOFTWARE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR
|
||||
PURPOSE OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND
|
||||
PERFORMANCE OF THE COVERED SOFTWARE IS WITH YOU. SHOULD ANY
|
||||
COVERED SOFTWARE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE
|
||||
INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY
|
||||
NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF
|
||||
WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF
|
||||
ANY COVERED SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS
|
||||
DISCLAIMER.
|
||||
|
||||
6. TERMINATION.
|
||||
|
||||
6.1. This License and the rights granted hereunder will terminate
|
||||
automatically if You fail to comply with terms herein and fail to
|
||||
cure such breach within 30 days of becoming aware of the breach.
|
||||
Provisions which, by their nature, must remain in effect beyond
|
||||
the termination of this License shall survive.
|
||||
|
||||
6.2. If You assert a patent infringement claim (excluding
|
||||
declaratory judgment actions) against Initial Developer or a
|
||||
Contributor (the Initial Developer or Contributor against whom You
|
||||
assert such claim is referred to as "Participant") alleging that
|
||||
the Participant Software (meaning the Contributor Version where
|
||||
the Participant is a Contributor or the Original Software where
|
||||
the Participant is the Initial Developer) directly or indirectly
|
||||
infringes any patent, then any and all rights granted directly or
|
||||
indirectly to You by such Participant, the Initial Developer (if
|
||||
the Initial Developer is not the Participant) and all Contributors
|
||||
under Sections 2.1 and/or 2.2 of this License shall, upon 60 days
|
||||
notice from Participant terminate prospectively and automatically
|
||||
at the expiration of such 60 day notice period, unless if within
|
||||
such 60 day period You withdraw Your claim with respect to the
|
||||
Participant Software against such Participant either unilaterally
|
||||
or pursuant to a written agreement with Participant.
|
||||
|
||||
6.3. In the event of termination under Sections 6.1 or 6.2 above,
|
||||
all end user licenses that have been validly granted by You or any
|
||||
distributor hereunder prior to termination (excluding licenses
|
||||
granted to You by any distributor) shall survive termination.
|
||||
|
||||
7. LIMITATION OF LIABILITY.
|
||||
|
||||
UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT
|
||||
(INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE
|
||||
INITIAL DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF
|
||||
COVERED SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE
|
||||
LIABLE TO ANY PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR
|
||||
CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT
|
||||
LIMITATION, DAMAGES FOR LOST PROFITS, LOSS OF GOODWILL, WORK
|
||||
STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER
|
||||
COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN
|
||||
INFORMED OF THE POSSIBILITY OF SUCH DAMAGES. THIS LIMITATION OF
|
||||
LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL
|
||||
INJURY RESULTING FROM SUCH PARTY'S NEGLIGENCE TO THE EXTENT
|
||||
APPLICABLE LAW PROHIBITS SUCH LIMITATION. SOME JURISDICTIONS DO
|
||||
NOT ALLOW THE EXCLUSION OR LIMITATION OF INCIDENTAL OR
|
||||
CONSEQUENTIAL DAMAGES, SO THIS EXCLUSION AND LIMITATION MAY NOT
|
||||
APPLY TO YOU.
|
||||
|
||||
8. U.S. GOVERNMENT END USERS.
|
||||
|
||||
The Covered Software is a "commercial item," as that term is
|
||||
defined in 48 C.F.R. 2.101 (Oct. 1995), consisting of "commercial
|
||||
computer software" (as that term is defined at 48
|
||||
C.F.R. 252.227-7014(a)(1)) and "commercial computer software
|
||||
documentation" as such terms are used in 48 C.F.R. 12.212
|
||||
(Sept. 1995). Consistent with 48 C.F.R. 12.212 and 48
|
||||
C.F.R. 227.7202-1 through 227.7202-4 (June 1995), all
|
||||
U.S. Government End Users acquire Covered Software with only those
|
||||
rights set forth herein. This U.S. Government Rights clause is in
|
||||
lieu of, and supersedes, any other FAR, DFAR, or other clause or
|
||||
provision that addresses Government rights in computer software
|
||||
under this License.
|
||||
|
||||
9. MISCELLANEOUS.
|
||||
|
||||
This License represents the complete agreement concerning subject
|
||||
matter hereof. If any provision of this License is held to be
|
||||
unenforceable, such provision shall be reformed only to the extent
|
||||
necessary to make it enforceable. This License shall be governed
|
||||
by the law of the jurisdiction specified in a notice contained
|
||||
within the Original Software (except to the extent applicable law,
|
||||
if any, provides otherwise), excluding such jurisdiction's
|
||||
conflict-of-law provisions. Any litigation relating to this
|
||||
License shall be subject to the jurisdiction of the courts located
|
||||
in the jurisdiction and venue specified in a notice contained
|
||||
within the Original Software, with the losing party responsible
|
||||
for costs, including, without limitation, court costs and
|
||||
reasonable attorneys' fees and expenses. The application of the
|
||||
United Nations Convention on Contracts for the International Sale
|
||||
of Goods is expressly excluded. Any law or regulation which
|
||||
provides that the language of a contract shall be construed
|
||||
against the drafter shall not apply to this License. You agree
|
||||
that You alone are responsible for compliance with the United
|
||||
States export administration regulations (and the export control
|
||||
laws and regulation of any other countries) when You use,
|
||||
distribute or otherwise make available any Covered Software.
|
||||
|
||||
10. RESPONSIBILITY FOR CLAIMS.
|
||||
|
||||
As between Initial Developer and the Contributors, each party is
|
||||
responsible for claims and damages arising, directly or
|
||||
indirectly, out of its utilization of rights under this License
|
||||
and You agree to work with Initial Developer and Contributors to
|
||||
distribute such responsibility on an equitable basis. Nothing
|
||||
herein is intended or shall be deemed to constitute any admission
|
||||
of liability.
|
||||
|
||||
--------------------------------------------------------------------
|
||||
|
||||
NOTICE PURSUANT TO SECTION 9 OF THE COMMON DEVELOPMENT AND
|
||||
DISTRIBUTION LICENSE (CDDL)
|
||||
|
||||
For Covered Software in this distribution, this License shall
|
||||
be governed by the laws of the State of California (excluding
|
||||
conflict-of-law provisions).
|
||||
|
||||
Any litigation relating to this License shall be subject to the
|
||||
jurisdiction of the Federal Courts of the Northern District of
|
||||
California and the state courts of the State of California, with
|
||||
venue lying in Santa Clara County, California.
|
||||
|
|
@ -1,27 +0,0 @@
|
|||
# getpasswd in Go [](https://godoc.org/github.com/howeyc/gopass) [](http://travis-ci.org/howeyc/gopass)
|
||||
|
||||
Retrieve password from user terminal or piped input without echo.
|
||||
|
||||
Verified on BSD, Linux, and Windows.
|
||||
|
||||
Example:
|
||||
```go
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
import "github.com/howeyc/gopass"
|
||||
|
||||
func main() {
|
||||
fmt.Printf("Password: ")
|
||||
|
||||
// Silent. For printing *'s use gopass.GetPasswdMasked()
|
||||
pass, err := gopass.GetPasswd()
|
||||
if err != nil {
|
||||
// Handle gopass.ErrInterrupted or getch() read error
|
||||
}
|
||||
|
||||
// Do something with pass
|
||||
}
|
||||
```
|
||||
|
||||
Caution: Multi-byte characters not supported!
|
||||
|
|
@ -1,110 +0,0 @@
|
|||
package gopass
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
|
||||
type FdReader interface {
|
||||
io.Reader
|
||||
Fd() uintptr
|
||||
}
|
||||
|
||||
var defaultGetCh = func(r io.Reader) (byte, error) {
|
||||
buf := make([]byte, 1)
|
||||
if n, err := r.Read(buf); n == 0 || err != nil {
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return 0, io.EOF
|
||||
}
|
||||
return buf[0], nil
|
||||
}
|
||||
|
||||
var (
|
||||
maxLength = 512
|
||||
ErrInterrupted = errors.New("interrupted")
|
||||
ErrMaxLengthExceeded = fmt.Errorf("maximum byte limit (%v) exceeded", maxLength)
|
||||
|
||||
// Provide variable so that tests can provide a mock implementation.
|
||||
getch = defaultGetCh
|
||||
)
|
||||
|
||||
// getPasswd returns the input read from terminal.
|
||||
// If prompt is not empty, it will be output as a prompt to the user
|
||||
// If masked is true, typing will be matched by asterisks on the screen.
|
||||
// Otherwise, typing will echo nothing.
|
||||
func getPasswd(prompt string, masked bool, r FdReader, w io.Writer) ([]byte, error) {
|
||||
var err error
|
||||
var pass, bs, mask []byte
|
||||
if masked {
|
||||
bs = []byte("\b \b")
|
||||
mask = []byte("*")
|
||||
}
|
||||
|
||||
if isTerminal(r.Fd()) {
|
||||
if oldState, err := makeRaw(r.Fd()); err != nil {
|
||||
return pass, err
|
||||
} else {
|
||||
defer func() {
|
||||
restore(r.Fd(), oldState)
|
||||
fmt.Fprintln(w)
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
if prompt != "" {
|
||||
fmt.Fprint(w, prompt)
|
||||
}
|
||||
|
||||
// Track total bytes read, not just bytes in the password. This ensures any
|
||||
// errors that might flood the console with nil or -1 bytes infinitely are
|
||||
// capped.
|
||||
var counter int
|
||||
for counter = 0; counter <= maxLength; counter++ {
|
||||
if v, e := getch(r); e != nil {
|
||||
err = e
|
||||
break
|
||||
} else if v == 127 || v == 8 {
|
||||
if l := len(pass); l > 0 {
|
||||
pass = pass[:l-1]
|
||||
fmt.Fprint(w, string(bs))
|
||||
}
|
||||
} else if v == 13 || v == 10 {
|
||||
break
|
||||
} else if v == 3 {
|
||||
err = ErrInterrupted
|
||||
break
|
||||
} else if v != 0 {
|
||||
pass = append(pass, v)
|
||||
fmt.Fprint(w, string(mask))
|
||||
}
|
||||
}
|
||||
|
||||
if counter > maxLength {
|
||||
err = ErrMaxLengthExceeded
|
||||
}
|
||||
|
||||
return pass, err
|
||||
}
|
||||
|
||||
// GetPasswd returns the password read from the terminal without echoing input.
|
||||
// The returned byte array does not include end-of-line characters.
|
||||
func GetPasswd() ([]byte, error) {
|
||||
return getPasswd("", false, os.Stdin, os.Stdout)
|
||||
}
|
||||
|
||||
// GetPasswdMasked returns the password read from the terminal, echoing asterisks.
|
||||
// The returned byte array does not include end-of-line characters.
|
||||
func GetPasswdMasked() ([]byte, error) {
|
||||
return getPasswd("", true, os.Stdin, os.Stdout)
|
||||
}
|
||||
|
||||
// GetPasswdPrompt prompts the user and returns the password read from the terminal.
|
||||
// If mask is true, then asterisks are echoed.
|
||||
// The returned byte array does not include end-of-line characters.
|
||||
func GetPasswdPrompt(prompt string, mask bool, r FdReader, w io.Writer) ([]byte, error) {
|
||||
return getPasswd(prompt, mask, r, w)
|
||||
}
|
||||
|
|
@ -1,225 +0,0 @@
|
|||
package gopass
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestGetPasswd tests the password creation and output based on a byte buffer
|
||||
// as input to mock the underlying getch() methods.
|
||||
func TestGetPasswd(t *testing.T) {
|
||||
type testData struct {
|
||||
input []byte
|
||||
|
||||
// Due to how backspaces are written, it is easier to manually write
|
||||
// each expected output for the masked cases.
|
||||
masked string
|
||||
password string
|
||||
byesLeft int
|
||||
reason string
|
||||
}
|
||||
|
||||
ds := []testData{
|
||||
testData{[]byte("abc\n"), "***", "abc", 0, "Password parsing should stop at \\n"},
|
||||
testData{[]byte("abc\r"), "***", "abc", 0, "Password parsing should stop at \\r"},
|
||||
testData{[]byte("a\nbc\n"), "*", "a", 3, "Password parsing should stop at \\n"},
|
||||
testData{[]byte("*!]|\n"), "****", "*!]|", 0, "Special characters shouldn't affect the password."},
|
||||
|
||||
testData{[]byte("abc\r\n"), "***", "abc", 1,
|
||||
"Password parsing should stop at \\r; Windows LINE_MODE should be unset so \\r is not converted to \\r\\n."},
|
||||
|
||||
testData{[]byte{'a', 'b', 'c', 8, '\n'}, "***\b \b", "ab", 0, "Backspace byte should remove the last read byte."},
|
||||
testData{[]byte{'a', 'b', 127, 'c', '\n'}, "**\b \b*", "ac", 0, "Delete byte should remove the last read byte."},
|
||||
testData{[]byte{'a', 'b', 127, 'c', 8, 127, '\n'}, "**\b \b*\b \b\b \b", "", 0, "Successive deletes continue to delete."},
|
||||
testData{[]byte{8, 8, 8, '\n'}, "", "", 0, "Deletes before characters are noops."},
|
||||
testData{[]byte{8, 8, 8, 'a', 'b', 'c', '\n'}, "***", "abc", 0, "Deletes before characters are noops."},
|
||||
|
||||
testData{[]byte{'a', 'b', 0, 'c', '\n'}, "***", "abc", 0,
|
||||
"Nil byte should be ignored due; may get unintended nil bytes from syscalls on Windows."},
|
||||
}
|
||||
|
||||
// Redirecting output for tests as they print to os.Stdout but we want to
|
||||
// capture and test the output.
|
||||
for _, masked := range []bool{true, false} {
|
||||
for _, d := range ds {
|
||||
pipeBytesToStdin(d.input)
|
||||
|
||||
r, w, err := os.Pipe()
|
||||
if err != nil {
|
||||
t.Fatal(err.Error())
|
||||
}
|
||||
|
||||
result, err := getPasswd("", masked, os.Stdin, w)
|
||||
if err != nil {
|
||||
t.Errorf("Error getting password: %s", err.Error())
|
||||
}
|
||||
leftOnBuffer := flushStdin()
|
||||
|
||||
// Test output (masked and unmasked). Delete/backspace actually
|
||||
// deletes, overwrites and deletes again. As a result, we need to
|
||||
// remove those from the pipe afterwards to mimic the console's
|
||||
// interpretation of those bytes.
|
||||
w.Close()
|
||||
output, err := ioutil.ReadAll(r)
|
||||
if err != nil {
|
||||
t.Fatal(err.Error())
|
||||
}
|
||||
var expectedOutput []byte
|
||||
if masked {
|
||||
expectedOutput = []byte(d.masked)
|
||||
} else {
|
||||
expectedOutput = []byte("")
|
||||
}
|
||||
if bytes.Compare(expectedOutput, output) != 0 {
|
||||
t.Errorf("Expected output to equal %v (%q) but got %v (%q) instead when masked=%v. %s", expectedOutput, string(expectedOutput), output, string(output), masked, d.reason)
|
||||
}
|
||||
|
||||
if string(result) != d.password {
|
||||
t.Errorf("Expected %q but got %q instead when masked=%v. %s", d.password, result, masked, d.reason)
|
||||
}
|
||||
|
||||
if leftOnBuffer != d.byesLeft {
|
||||
t.Errorf("Expected %v bytes left on buffer but instead got %v when masked=%v. %s", d.byesLeft, leftOnBuffer, masked, d.reason)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestPipe ensures we get our expected pipe behavior.
|
||||
func TestPipe(t *testing.T) {
|
||||
type testData struct {
|
||||
input string
|
||||
password string
|
||||
expError error
|
||||
}
|
||||
ds := []testData{
|
||||
testData{"abc", "abc", io.EOF},
|
||||
testData{"abc\n", "abc", nil},
|
||||
testData{"abc\r", "abc", nil},
|
||||
testData{"abc\r\n", "abc", nil},
|
||||
}
|
||||
|
||||
for _, d := range ds {
|
||||
_, err := pipeToStdin(d.input)
|
||||
if err != nil {
|
||||
t.Log("Error writing input to stdin:", err)
|
||||
t.FailNow()
|
||||
}
|
||||
pass, err := GetPasswd()
|
||||
if string(pass) != d.password {
|
||||
t.Errorf("Expected %q but got %q instead.", d.password, string(pass))
|
||||
}
|
||||
if err != d.expError {
|
||||
t.Errorf("Expected %v but got %q instead.", d.expError, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// flushStdin reads from stdin for .5 seconds to ensure no bytes are left on
|
||||
// the buffer. Returns the number of bytes read.
|
||||
func flushStdin() int {
|
||||
ch := make(chan byte)
|
||||
go func(ch chan byte) {
|
||||
reader := bufio.NewReader(os.Stdin)
|
||||
for {
|
||||
b, err := reader.ReadByte()
|
||||
if err != nil { // Maybe log non io.EOF errors, if you want
|
||||
close(ch)
|
||||
return
|
||||
}
|
||||
ch <- b
|
||||
}
|
||||
close(ch)
|
||||
}(ch)
|
||||
|
||||
numBytes := 0
|
||||
for {
|
||||
select {
|
||||
case _, ok := <-ch:
|
||||
if !ok {
|
||||
return numBytes
|
||||
}
|
||||
numBytes++
|
||||
case <-time.After(500 * time.Millisecond):
|
||||
return numBytes
|
||||
}
|
||||
}
|
||||
return numBytes
|
||||
}
|
||||
|
||||
// pipeToStdin pipes the given string onto os.Stdin by replacing it with an
|
||||
// os.Pipe. The write end of the pipe is closed so that EOF is read after the
|
||||
// final byte.
|
||||
func pipeToStdin(s string) (int, error) {
|
||||
pipeReader, pipeWriter, err := os.Pipe()
|
||||
if err != nil {
|
||||
fmt.Println("Error getting os pipes:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
os.Stdin = pipeReader
|
||||
w, err := pipeWriter.WriteString(s)
|
||||
pipeWriter.Close()
|
||||
return w, err
|
||||
}
|
||||
|
||||
func pipeBytesToStdin(b []byte) (int, error) {
|
||||
return pipeToStdin(string(b))
|
||||
}
|
||||
|
||||
// TestGetPasswd_Err tests errors are properly handled from getch()
|
||||
func TestGetPasswd_Err(t *testing.T) {
|
||||
var inBuffer *bytes.Buffer
|
||||
getch = func(io.Reader) (byte, error) {
|
||||
b, err := inBuffer.ReadByte()
|
||||
if err != nil {
|
||||
return 13, err
|
||||
}
|
||||
if b == 'z' {
|
||||
return 'z', fmt.Errorf("Forced error; byte returned should not be considered accurate.")
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
defer func() { getch = defaultGetCh }()
|
||||
|
||||
for input, expectedPassword := range map[string]string{"abc": "abc", "abzc": "ab"} {
|
||||
inBuffer = bytes.NewBufferString(input)
|
||||
p, err := GetPasswdMasked()
|
||||
if string(p) != expectedPassword {
|
||||
t.Errorf("Expected %q but got %q instead.", expectedPassword, p)
|
||||
}
|
||||
if err == nil {
|
||||
t.Errorf("Expected error to be returned.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMaxPasswordLength(t *testing.T) {
|
||||
type testData struct {
|
||||
input []byte
|
||||
expectedErr error
|
||||
|
||||
// Helper field to output in case of failure; rather than hundreds of
|
||||
// bytes.
|
||||
inputDesc string
|
||||
}
|
||||
|
||||
ds := []testData{
|
||||
testData{append(bytes.Repeat([]byte{'a'}, maxLength), '\n'), nil, fmt.Sprintf("%v 'a' bytes followed by a newline", maxLength)},
|
||||
testData{append(bytes.Repeat([]byte{'a'}, maxLength+1), '\n'), ErrMaxLengthExceeded, fmt.Sprintf("%v 'a' bytes followed by a newline", maxLength+1)},
|
||||
testData{append(bytes.Repeat([]byte{0x00}, maxLength+1), '\n'), ErrMaxLengthExceeded, fmt.Sprintf("%v 0x00 bytes followed by a newline", maxLength+1)},
|
||||
}
|
||||
|
||||
for _, d := range ds {
|
||||
pipeBytesToStdin(d.input)
|
||||
_, err := GetPasswd()
|
||||
if err != d.expectedErr {
|
||||
t.Errorf("Expected error to be %v; isntead got %v from %v", d.expectedErr, err, d.inputDesc)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,25 +0,0 @@
|
|||
// +build !solaris
|
||||
|
||||
package gopass
|
||||
|
||||
import "golang.org/x/crypto/ssh/terminal"
|
||||
|
||||
type terminalState struct {
|
||||
state *terminal.State
|
||||
}
|
||||
|
||||
func isTerminal(fd uintptr) bool {
|
||||
return terminal.IsTerminal(int(fd))
|
||||
}
|
||||
|
||||
func makeRaw(fd uintptr) (*terminalState, error) {
|
||||
state, err := terminal.MakeRaw(int(fd))
|
||||
|
||||
return &terminalState{
|
||||
state: state,
|
||||
}, err
|
||||
}
|
||||
|
||||
func restore(fd uintptr, oldState *terminalState) error {
|
||||
return terminal.Restore(int(fd), oldState.state)
|
||||
}
|
||||
|
|
@ -1,69 +0,0 @@
|
|||
/*
|
||||
* CDDL HEADER START
|
||||
*
|
||||
* The contents of this file are subject to the terms of the
|
||||
* Common Development and Distribution License, Version 1.0 only
|
||||
* (the "License"). You may not use this file except in compliance
|
||||
* with the License.
|
||||
*
|
||||
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
|
||||
* or http://www.opensolaris.org/os/licensing.
|
||||
* See the License for the specific language governing permissions
|
||||
* and limitations under the License.
|
||||
*
|
||||
* When distributing Covered Code, include this CDDL HEADER in each
|
||||
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
|
||||
* If applicable, add the following below this CDDL HEADER, with the
|
||||
* fields enclosed by brackets "[]" replaced with your own identifying
|
||||
* information: Portions Copyright [yyyy] [name of copyright owner]
|
||||
*
|
||||
* CDDL HEADER END
|
||||
*/
|
||||
// Below is derived from Solaris source, so CDDL license is included.
|
||||
|
||||
package gopass
|
||||
|
||||
import (
|
||||
"syscall"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
type terminalState struct {
|
||||
state *unix.Termios
|
||||
}
|
||||
|
||||
// isTerminal returns true if there is a terminal attached to the given
|
||||
// file descriptor.
|
||||
// Source: http://src.illumos.org/source/xref/illumos-gate/usr/src/lib/libbc/libc/gen/common/isatty.c
|
||||
func isTerminal(fd uintptr) bool {
|
||||
var termio unix.Termio
|
||||
err := unix.IoctlSetTermio(int(fd), unix.TCGETA, &termio)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// makeRaw puts the terminal connected to the given file descriptor into raw
|
||||
// mode and returns the previous state of the terminal so that it can be
|
||||
// restored.
|
||||
// Source: http://src.illumos.org/source/xref/illumos-gate/usr/src/lib/libast/common/uwin/getpass.c
|
||||
func makeRaw(fd uintptr) (*terminalState, error) {
|
||||
oldTermiosPtr, err := unix.IoctlGetTermios(int(fd), unix.TCGETS)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
oldTermios := *oldTermiosPtr
|
||||
|
||||
newTermios := oldTermios
|
||||
newTermios.Lflag &^= syscall.ECHO | syscall.ECHOE | syscall.ECHOK | syscall.ECHONL
|
||||
if err := unix.IoctlSetTermios(int(fd), unix.TCSETS, &newTermios); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &terminalState{
|
||||
state: oldTermiosPtr,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func restore(fd uintptr, oldState *terminalState) error {
|
||||
return unix.IoctlSetTermios(int(fd), unix.TCSETS, oldState.state)
|
||||
}
|
||||
|
|
@ -1,191 +0,0 @@
|
|||
All files in this repository are licensed as follows. If you contribute
|
||||
to this repository, it is assumed that you license your contribution
|
||||
under the same license unless you state otherwise.
|
||||
|
||||
All files Copyright (C) 2015 Canonical Ltd. unless otherwise specified in the file.
|
||||
|
||||
This software is licensed under the LGPLv3, included below.
|
||||
|
||||
As a special exception to the GNU Lesser General Public License version 3
|
||||
("LGPL3"), the copyright holders of this Library give you permission to
|
||||
convey to a third party a Combined Work that links statically or dynamically
|
||||
to this Library without providing any Minimal Corresponding Source or
|
||||
Minimal Application Code as set out in 4d or providing the installation
|
||||
information set out in section 4e, provided that you comply with the other
|
||||
provisions of LGPL3 and provided that you meet, for the Application the
|
||||
terms and conditions of the license(s) which apply to the Application.
|
||||
|
||||
Except as stated in this special exception, the provisions of LGPL3 will
|
||||
continue to comply in full to this Library. If you modify this Library, you
|
||||
may apply this exception to your version of this Library, but you are not
|
||||
obliged to do so. If you do not wish to do so, delete this exception
|
||||
statement from your version. This exception does not (and cannot) modify any
|
||||
license terms which apply to the Application, with which you must still
|
||||
comply.
|
||||
|
||||
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
|
||||
This version of the GNU Lesser General Public License incorporates
|
||||
the terms and conditions of version 3 of the GNU General Public
|
||||
License, supplemented by the additional permissions listed below.
|
||||
|
||||
0. Additional Definitions.
|
||||
|
||||
As used herein, "this License" refers to version 3 of the GNU Lesser
|
||||
General Public License, and the "GNU GPL" refers to version 3 of the GNU
|
||||
General Public License.
|
||||
|
||||
"The Library" refers to a covered work governed by this License,
|
||||
other than an Application or a Combined Work as defined below.
|
||||
|
||||
An "Application" is any work that makes use of an interface provided
|
||||
by the Library, but which is not otherwise based on the Library.
|
||||
Defining a subclass of a class defined by the Library is deemed a mode
|
||||
of using an interface provided by the Library.
|
||||
|
||||
A "Combined Work" is a work produced by combining or linking an
|
||||
Application with the Library. The particular version of the Library
|
||||
with which the Combined Work was made is also called the "Linked
|
||||
Version".
|
||||
|
||||
The "Minimal Corresponding Source" for a Combined Work means the
|
||||
Corresponding Source for the Combined Work, excluding any source code
|
||||
for portions of the Combined Work that, considered in isolation, are
|
||||
based on the Application, and not on the Linked Version.
|
||||
|
||||
The "Corresponding Application Code" for a Combined Work means the
|
||||
object code and/or source code for the Application, including any data
|
||||
and utility programs needed for reproducing the Combined Work from the
|
||||
Application, but excluding the System Libraries of the Combined Work.
|
||||
|
||||
1. Exception to Section 3 of the GNU GPL.
|
||||
|
||||
You may convey a covered work under sections 3 and 4 of this License
|
||||
without being bound by section 3 of the GNU GPL.
|
||||
|
||||
2. Conveying Modified Versions.
|
||||
|
||||
If you modify a copy of the Library, and, in your modifications, a
|
||||
facility refers to a function or data to be supplied by an Application
|
||||
that uses the facility (other than as an argument passed when the
|
||||
facility is invoked), then you may convey a copy of the modified
|
||||
version:
|
||||
|
||||
a) under this License, provided that you make a good faith effort to
|
||||
ensure that, in the event an Application does not supply the
|
||||
function or data, the facility still operates, and performs
|
||||
whatever part of its purpose remains meaningful, or
|
||||
|
||||
b) under the GNU GPL, with none of the additional permissions of
|
||||
this License applicable to that copy.
|
||||
|
||||
3. Object Code Incorporating Material from Library Header Files.
|
||||
|
||||
The object code form of an Application may incorporate material from
|
||||
a header file that is part of the Library. You may convey such object
|
||||
code under terms of your choice, provided that, if the incorporated
|
||||
material is not limited to numerical parameters, data structure
|
||||
layouts and accessors, or small macros, inline functions and templates
|
||||
(ten or fewer lines in length), you do both of the following:
|
||||
|
||||
a) Give prominent notice with each copy of the object code that the
|
||||
Library is used in it and that the Library and its use are
|
||||
covered by this License.
|
||||
|
||||
b) Accompany the object code with a copy of the GNU GPL and this license
|
||||
document.
|
||||
|
||||
4. Combined Works.
|
||||
|
||||
You may convey a Combined Work under terms of your choice that,
|
||||
taken together, effectively do not restrict modification of the
|
||||
portions of the Library contained in the Combined Work and reverse
|
||||
engineering for debugging such modifications, if you also do each of
|
||||
the following:
|
||||
|
||||
a) Give prominent notice with each copy of the Combined Work that
|
||||
the Library is used in it and that the Library and its use are
|
||||
covered by this License.
|
||||
|
||||
b) Accompany the Combined Work with a copy of the GNU GPL and this license
|
||||
document.
|
||||
|
||||
c) For a Combined Work that displays copyright notices during
|
||||
execution, include the copyright notice for the Library among
|
||||
these notices, as well as a reference directing the user to the
|
||||
copies of the GNU GPL and this license document.
|
||||
|
||||
d) Do one of the following:
|
||||
|
||||
0) Convey the Minimal Corresponding Source under the terms of this
|
||||
License, and the Corresponding Application Code in a form
|
||||
suitable for, and under terms that permit, the user to
|
||||
recombine or relink the Application with a modified version of
|
||||
the Linked Version to produce a modified Combined Work, in the
|
||||
manner specified by section 6 of the GNU GPL for conveying
|
||||
Corresponding Source.
|
||||
|
||||
1) Use a suitable shared library mechanism for linking with the
|
||||
Library. A suitable mechanism is one that (a) uses at run time
|
||||
a copy of the Library already present on the user's computer
|
||||
system, and (b) will operate properly with a modified version
|
||||
of the Library that is interface-compatible with the Linked
|
||||
Version.
|
||||
|
||||
e) Provide Installation Information, but only if you would otherwise
|
||||
be required to provide such information under section 6 of the
|
||||
GNU GPL, and only to the extent that such information is
|
||||
necessary to install and execute a modified version of the
|
||||
Combined Work produced by recombining or relinking the
|
||||
Application with a modified version of the Linked Version. (If
|
||||
you use option 4d0, the Installation Information must accompany
|
||||
the Minimal Corresponding Source and Corresponding Application
|
||||
Code. If you use option 4d1, you must provide the Installation
|
||||
Information in the manner specified by section 6 of the GNU GPL
|
||||
for conveying Corresponding Source.)
|
||||
|
||||
5. Combined Libraries.
|
||||
|
||||
You may place library facilities that are a work based on the
|
||||
Library side by side in a single library together with other library
|
||||
facilities that are not Applications and are not covered by this
|
||||
License, and convey such a combined library under terms of your
|
||||
choice, if you do both of the following:
|
||||
|
||||
a) Accompany the combined library with a copy of the same work based
|
||||
on the Library, uncombined with any other library facilities,
|
||||
conveyed under the terms of this License.
|
||||
|
||||
b) Give prominent notice with the combined library that part of it
|
||||
is a work based on the Library, and explaining where to find the
|
||||
accompanying uncombined form of the same work.
|
||||
|
||||
6. Revised Versions of the GNU Lesser General Public License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions
|
||||
of the GNU Lesser General Public License from time to time. Such new
|
||||
versions will be similar in spirit to the present version, but may
|
||||
differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Library as you received it specifies that a certain numbered version
|
||||
of the GNU Lesser General Public License "or any later version"
|
||||
applies to it, you have the option of following the terms and
|
||||
conditions either of that published version or of any later version
|
||||
published by the Free Software Foundation. If the Library as you
|
||||
received it does not specify a version number of the GNU Lesser
|
||||
General Public License, you may choose any version of the GNU Lesser
|
||||
General Public License ever published by the Free Software Foundation.
|
||||
|
||||
If the Library as you received it specifies that a proxy can decide
|
||||
whether future versions of the GNU Lesser General Public License shall
|
||||
apply, that proxy's public statement of acceptance of any version is
|
||||
permanent authorization for you to choose that version for the
|
||||
Library.
|
||||
|
|
@ -1,117 +0,0 @@
|
|||
# ratelimit
|
||||
--
|
||||
import "github.com/juju/ratelimit"
|
||||
|
||||
The ratelimit package provides an efficient token bucket implementation. See
|
||||
http://en.wikipedia.org/wiki/Token_bucket.
|
||||
|
||||
## Usage
|
||||
|
||||
#### func Reader
|
||||
|
||||
```go
|
||||
func Reader(r io.Reader, bucket *Bucket) io.Reader
|
||||
```
|
||||
Reader returns a reader that is rate limited by the given token bucket. Each
|
||||
token in the bucket represents one byte.
|
||||
|
||||
#### func Writer
|
||||
|
||||
```go
|
||||
func Writer(w io.Writer, bucket *Bucket) io.Writer
|
||||
```
|
||||
Writer returns a writer that is rate limited by the given token bucket. Each
|
||||
token in the bucket represents one byte.
|
||||
|
||||
#### type Bucket
|
||||
|
||||
```go
|
||||
type Bucket struct {
|
||||
}
|
||||
```
|
||||
|
||||
Bucket represents a token bucket that fills at a predetermined rate. Methods on
|
||||
Bucket may be called concurrently.
|
||||
|
||||
#### func NewBucket
|
||||
|
||||
```go
|
||||
func NewBucket(fillInterval time.Duration, capacity int64) *Bucket
|
||||
```
|
||||
NewBucket returns a new token bucket that fills at the rate of one token every
|
||||
fillInterval, up to the given maximum capacity. Both arguments must be positive.
|
||||
The bucket is initially full.
|
||||
|
||||
#### func NewBucketWithQuantum
|
||||
|
||||
```go
|
||||
func NewBucketWithQuantum(fillInterval time.Duration, capacity, quantum int64) *Bucket
|
||||
```
|
||||
NewBucketWithQuantum is similar to NewBucket, but allows the specification of
|
||||
the quantum size - quantum tokens are added every fillInterval.
|
||||
|
||||
#### func NewBucketWithRate
|
||||
|
||||
```go
|
||||
func NewBucketWithRate(rate float64, capacity int64) *Bucket
|
||||
```
|
||||
NewBucketWithRate returns a token bucket that fills the bucket at the rate of
|
||||
rate tokens per second up to the given maximum capacity. Because of limited
|
||||
clock resolution, at high rates, the actual rate may be up to 1% different from
|
||||
the specified rate.
|
||||
|
||||
#### func (*Bucket) Rate
|
||||
|
||||
```go
|
||||
func (tb *Bucket) Rate() float64
|
||||
```
|
||||
Rate returns the fill rate of the bucket, in tokens per second.
|
||||
|
||||
#### func (*Bucket) Take
|
||||
|
||||
```go
|
||||
func (tb *Bucket) Take(count int64) time.Duration
|
||||
```
|
||||
Take takes count tokens from the bucket without blocking. It returns the time
|
||||
that the caller should wait until the tokens are actually available.
|
||||
|
||||
Note that if the request is irrevocable - there is no way to return tokens to
|
||||
the bucket once this method commits us to taking them.
|
||||
|
||||
#### func (*Bucket) TakeAvailable
|
||||
|
||||
```go
|
||||
func (tb *Bucket) TakeAvailable(count int64) int64
|
||||
```
|
||||
TakeAvailable takes up to count immediately available tokens from the bucket. It
|
||||
returns the number of tokens removed, or zero if there are no available tokens.
|
||||
It does not block.
|
||||
|
||||
#### func (*Bucket) TakeMaxDuration
|
||||
|
||||
```go
|
||||
func (tb *Bucket) TakeMaxDuration(count int64, maxWait time.Duration) (time.Duration, bool)
|
||||
```
|
||||
TakeMaxDuration is like Take, except that it will only take tokens from the
|
||||
bucket if the wait time for the tokens is no greater than maxWait.
|
||||
|
||||
If it would take longer than maxWait for the tokens to become available, it does
|
||||
nothing and reports false, otherwise it returns the time that the caller should
|
||||
wait until the tokens are actually available, and reports true.
|
||||
|
||||
#### func (*Bucket) Wait
|
||||
|
||||
```go
|
||||
func (tb *Bucket) Wait(count int64)
|
||||
```
|
||||
Wait takes count tokens from the bucket, waiting until they are available.
|
||||
|
||||
#### func (*Bucket) WaitMaxDuration
|
||||
|
||||
```go
|
||||
func (tb *Bucket) WaitMaxDuration(count int64, maxWait time.Duration) bool
|
||||
```
|
||||
WaitMaxDuration is like Wait except that it will only take tokens from the
|
||||
bucket if it needs to wait for no greater than maxWait. It reports whether any
|
||||
tokens have been removed from the bucket If no tokens have been removed, it
|
||||
returns immediately.
|
||||
|
|
@ -1,344 +0,0 @@
|
|||
// Copyright 2014 Canonical Ltd.
|
||||
// Licensed under the LGPLv3 with static-linking exception.
|
||||
// See LICENCE file for details.
|
||||
|
||||
// Package ratelimit provides an efficient token bucket implementation
|
||||
// that can be used to limit the rate of arbitrary things.
|
||||
// See http://en.wikipedia.org/wiki/Token_bucket.
|
||||
package ratelimit
|
||||
|
||||
import (
|
||||
"math"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// The algorithm that this implementation uses does computational work
|
||||
// only when tokens are removed from the bucket, and that work completes
|
||||
// in short, bounded-constant time (Bucket.Wait benchmarks at 175ns on
|
||||
// my laptop).
|
||||
//
|
||||
// Time is measured in equal measured ticks, a given interval
|
||||
// (fillInterval) apart. On each tick a number of tokens (quantum) are
|
||||
// added to the bucket.
|
||||
//
|
||||
// When any of the methods are called the bucket updates the number of
|
||||
// tokens that are in the bucket, and it records the current tick
|
||||
// number too. Note that it doesn't record the current time - by
|
||||
// keeping things in units of whole ticks, it's easy to dish out tokens
|
||||
// at exactly the right intervals as measured from the start time.
|
||||
//
|
||||
// This allows us to calculate the number of tokens that will be
|
||||
// available at some time in the future with a few simple arithmetic
|
||||
// operations.
|
||||
//
|
||||
// The main reason for being able to transfer multiple tokens on each tick
|
||||
// is so that we can represent rates greater than 1e9 (the resolution of the Go
|
||||
// time package) tokens per second, but it's also useful because
|
||||
// it means we can easily represent situations like "a person gets
|
||||
// five tokens an hour, replenished on the hour".
|
||||
|
||||
// Bucket represents a token bucket that fills at a predetermined rate.
|
||||
// Methods on Bucket may be called concurrently.
|
||||
type Bucket struct {
|
||||
clock Clock
|
||||
|
||||
// startTime holds the moment when the bucket was
|
||||
// first created and ticks began.
|
||||
startTime time.Time
|
||||
|
||||
// capacity holds the overall capacity of the bucket.
|
||||
capacity int64
|
||||
|
||||
// quantum holds how many tokens are added on
|
||||
// each tick.
|
||||
quantum int64
|
||||
|
||||
// fillInterval holds the interval between each tick.
|
||||
fillInterval time.Duration
|
||||
|
||||
// mu guards the fields below it.
|
||||
mu sync.Mutex
|
||||
|
||||
// availableTokens holds the number of available
|
||||
// tokens as of the associated latestTick.
|
||||
// It will be negative when there are consumers
|
||||
// waiting for tokens.
|
||||
availableTokens int64
|
||||
|
||||
// latestTick holds the latest tick for which
|
||||
// we know the number of tokens in the bucket.
|
||||
latestTick int64
|
||||
}
|
||||
|
||||
// NewBucket returns a new token bucket that fills at the
|
||||
// rate of one token every fillInterval, up to the given
|
||||
// maximum capacity. Both arguments must be
|
||||
// positive. The bucket is initially full.
|
||||
func NewBucket(fillInterval time.Duration, capacity int64) *Bucket {
|
||||
return NewBucketWithClock(fillInterval, capacity, nil)
|
||||
}
|
||||
|
||||
// NewBucketWithClock is identical to NewBucket but injects a testable clock
|
||||
// interface.
|
||||
func NewBucketWithClock(fillInterval time.Duration, capacity int64, clock Clock) *Bucket {
|
||||
return NewBucketWithQuantumAndClock(fillInterval, capacity, 1, clock)
|
||||
}
|
||||
|
||||
// rateMargin specifes the allowed variance of actual
|
||||
// rate from specified rate. 1% seems reasonable.
|
||||
const rateMargin = 0.01
|
||||
|
||||
// NewBucketWithRate returns a token bucket that fills the bucket
|
||||
// at the rate of rate tokens per second up to the given
|
||||
// maximum capacity. Because of limited clock resolution,
|
||||
// at high rates, the actual rate may be up to 1% different from the
|
||||
// specified rate.
|
||||
func NewBucketWithRate(rate float64, capacity int64) *Bucket {
|
||||
return NewBucketWithRateAndClock(rate, capacity, nil)
|
||||
}
|
||||
|
||||
// NewBucketWithRateAndClock is identical to NewBucketWithRate but injects a
|
||||
// testable clock interface.
|
||||
func NewBucketWithRateAndClock(rate float64, capacity int64, clock Clock) *Bucket {
|
||||
// Use the same bucket each time through the loop
|
||||
// to save allocations.
|
||||
tb := NewBucketWithQuantumAndClock(1, capacity, 1, clock)
|
||||
for quantum := int64(1); quantum < 1<<50; quantum = nextQuantum(quantum) {
|
||||
fillInterval := time.Duration(1e9 * float64(quantum) / rate)
|
||||
if fillInterval <= 0 {
|
||||
continue
|
||||
}
|
||||
tb.fillInterval = fillInterval
|
||||
tb.quantum = quantum
|
||||
if diff := math.Abs(tb.Rate() - rate); diff/rate <= rateMargin {
|
||||
return tb
|
||||
}
|
||||
}
|
||||
panic("cannot find suitable quantum for " + strconv.FormatFloat(rate, 'g', -1, 64))
|
||||
}
|
||||
|
||||
// nextQuantum returns the next quantum to try after q.
|
||||
// We grow the quantum exponentially, but slowly, so we
|
||||
// get a good fit in the lower numbers.
|
||||
func nextQuantum(q int64) int64 {
|
||||
q1 := q * 11 / 10
|
||||
if q1 == q {
|
||||
q1++
|
||||
}
|
||||
return q1
|
||||
}
|
||||
|
||||
// NewBucketWithQuantum is similar to NewBucket, but allows
|
||||
// the specification of the quantum size - quantum tokens
|
||||
// are added every fillInterval.
|
||||
func NewBucketWithQuantum(fillInterval time.Duration, capacity, quantum int64) *Bucket {
|
||||
return NewBucketWithQuantumAndClock(fillInterval, capacity, quantum, nil)
|
||||
}
|
||||
|
||||
// NewBucketWithQuantumAndClock is like NewBucketWithQuantum, but
|
||||
// also has a clock argument that allows clients to fake the passing
|
||||
// of time. If clock is nil, the system clock will be used.
|
||||
func NewBucketWithQuantumAndClock(fillInterval time.Duration, capacity, quantum int64, clock Clock) *Bucket {
|
||||
if clock == nil {
|
||||
clock = realClock{}
|
||||
}
|
||||
if fillInterval <= 0 {
|
||||
panic("token bucket fill interval is not > 0")
|
||||
}
|
||||
if capacity <= 0 {
|
||||
panic("token bucket capacity is not > 0")
|
||||
}
|
||||
if quantum <= 0 {
|
||||
panic("token bucket quantum is not > 0")
|
||||
}
|
||||
return &Bucket{
|
||||
clock: clock,
|
||||
startTime: clock.Now(),
|
||||
latestTick: 0,
|
||||
fillInterval: fillInterval,
|
||||
capacity: capacity,
|
||||
quantum: quantum,
|
||||
availableTokens: capacity,
|
||||
}
|
||||
}
|
||||
|
||||
// Wait takes count tokens from the bucket, waiting until they are
|
||||
// available.
|
||||
func (tb *Bucket) Wait(count int64) {
|
||||
if d := tb.Take(count); d > 0 {
|
||||
tb.clock.Sleep(d)
|
||||
}
|
||||
}
|
||||
|
||||
// WaitMaxDuration is like Wait except that it will
|
||||
// only take tokens from the bucket if it needs to wait
|
||||
// for no greater than maxWait. It reports whether
|
||||
// any tokens have been removed from the bucket
|
||||
// If no tokens have been removed, it returns immediately.
|
||||
func (tb *Bucket) WaitMaxDuration(count int64, maxWait time.Duration) bool {
|
||||
d, ok := tb.TakeMaxDuration(count, maxWait)
|
||||
if d > 0 {
|
||||
tb.clock.Sleep(d)
|
||||
}
|
||||
return ok
|
||||
}
|
||||
|
||||
const infinityDuration time.Duration = 0x7fffffffffffffff
|
||||
|
||||
// Take takes count tokens from the bucket without blocking. It returns
|
||||
// the time that the caller should wait until the tokens are actually
|
||||
// available.
|
||||
//
|
||||
// Note that if the request is irrevocable - there is no way to return
|
||||
// tokens to the bucket once this method commits us to taking them.
|
||||
func (tb *Bucket) Take(count int64) time.Duration {
|
||||
tb.mu.Lock()
|
||||
defer tb.mu.Unlock()
|
||||
d, _ := tb.take(tb.clock.Now(), count, infinityDuration)
|
||||
return d
|
||||
}
|
||||
|
||||
// TakeMaxDuration is like Take, except that
|
||||
// it will only take tokens from the bucket if the wait
|
||||
// time for the tokens is no greater than maxWait.
|
||||
//
|
||||
// If it would take longer than maxWait for the tokens
|
||||
// to become available, it does nothing and reports false,
|
||||
// otherwise it returns the time that the caller should
|
||||
// wait until the tokens are actually available, and reports
|
||||
// true.
|
||||
func (tb *Bucket) TakeMaxDuration(count int64, maxWait time.Duration) (time.Duration, bool) {
|
||||
tb.mu.Lock()
|
||||
defer tb.mu.Unlock()
|
||||
return tb.take(tb.clock.Now(), count, maxWait)
|
||||
}
|
||||
|
||||
// TakeAvailable takes up to count immediately available tokens from the
|
||||
// bucket. It returns the number of tokens removed, or zero if there are
|
||||
// no available tokens. It does not block.
|
||||
func (tb *Bucket) TakeAvailable(count int64) int64 {
|
||||
tb.mu.Lock()
|
||||
defer tb.mu.Unlock()
|
||||
return tb.takeAvailable(tb.clock.Now(), count)
|
||||
}
|
||||
|
||||
// takeAvailable is the internal version of TakeAvailable - it takes the
|
||||
// current time as an argument to enable easy testing.
|
||||
func (tb *Bucket) takeAvailable(now time.Time, count int64) int64 {
|
||||
if count <= 0 {
|
||||
return 0
|
||||
}
|
||||
tb.adjustavailableTokens(tb.currentTick(now))
|
||||
if tb.availableTokens <= 0 {
|
||||
return 0
|
||||
}
|
||||
if count > tb.availableTokens {
|
||||
count = tb.availableTokens
|
||||
}
|
||||
tb.availableTokens -= count
|
||||
return count
|
||||
}
|
||||
|
||||
// Available returns the number of available tokens. It will be negative
|
||||
// when there are consumers waiting for tokens. Note that if this
|
||||
// returns greater than zero, it does not guarantee that calls that take
|
||||
// tokens from the buffer will succeed, as the number of available
|
||||
// tokens could have changed in the meantime. This method is intended
|
||||
// primarily for metrics reporting and debugging.
|
||||
func (tb *Bucket) Available() int64 {
|
||||
return tb.available(tb.clock.Now())
|
||||
}
|
||||
|
||||
// available is the internal version of available - it takes the current time as
|
||||
// an argument to enable easy testing.
|
||||
func (tb *Bucket) available(now time.Time) int64 {
|
||||
tb.mu.Lock()
|
||||
defer tb.mu.Unlock()
|
||||
tb.adjustavailableTokens(tb.currentTick(now))
|
||||
return tb.availableTokens
|
||||
}
|
||||
|
||||
// Capacity returns the capacity that the bucket was created with.
|
||||
func (tb *Bucket) Capacity() int64 {
|
||||
return tb.capacity
|
||||
}
|
||||
|
||||
// Rate returns the fill rate of the bucket, in tokens per second.
|
||||
func (tb *Bucket) Rate() float64 {
|
||||
return 1e9 * float64(tb.quantum) / float64(tb.fillInterval)
|
||||
}
|
||||
|
||||
// take is the internal version of Take - it takes the current time as
|
||||
// an argument to enable easy testing.
|
||||
func (tb *Bucket) take(now time.Time, count int64, maxWait time.Duration) (time.Duration, bool) {
|
||||
if count <= 0 {
|
||||
return 0, true
|
||||
}
|
||||
|
||||
tick := tb.currentTick(now)
|
||||
tb.adjustavailableTokens(tick)
|
||||
avail := tb.availableTokens - count
|
||||
if avail >= 0 {
|
||||
tb.availableTokens = avail
|
||||
return 0, true
|
||||
}
|
||||
// Round up the missing tokens to the nearest multiple
|
||||
// of quantum - the tokens won't be available until
|
||||
// that tick.
|
||||
|
||||
// endTick holds the tick when all the requested tokens will
|
||||
// become available.
|
||||
endTick := tick + (-avail+tb.quantum-1)/tb.quantum
|
||||
endTime := tb.startTime.Add(time.Duration(endTick) * tb.fillInterval)
|
||||
waitTime := endTime.Sub(now)
|
||||
if waitTime > maxWait {
|
||||
return 0, false
|
||||
}
|
||||
tb.availableTokens = avail
|
||||
return waitTime, true
|
||||
}
|
||||
|
||||
// currentTick returns the current time tick, measured
|
||||
// from tb.startTime.
|
||||
func (tb *Bucket) currentTick(now time.Time) int64 {
|
||||
return int64(now.Sub(tb.startTime) / tb.fillInterval)
|
||||
}
|
||||
|
||||
// adjustavailableTokens adjusts the current number of tokens
|
||||
// available in the bucket at the given time, which must
|
||||
// be in the future (positive) with respect to tb.latestTick.
|
||||
func (tb *Bucket) adjustavailableTokens(tick int64) {
|
||||
if tb.availableTokens >= tb.capacity {
|
||||
return
|
||||
}
|
||||
tb.availableTokens += (tick - tb.latestTick) * tb.quantum
|
||||
if tb.availableTokens > tb.capacity {
|
||||
tb.availableTokens = tb.capacity
|
||||
}
|
||||
tb.latestTick = tick
|
||||
return
|
||||
}
|
||||
|
||||
// Clock represents the passage of time in a way that
|
||||
// can be faked out for tests.
|
||||
type Clock interface {
|
||||
// Now returns the current time.
|
||||
Now() time.Time
|
||||
// Sleep sleeps for at least the given duration.
|
||||
Sleep(d time.Duration)
|
||||
}
|
||||
|
||||
// realClock implements Clock in terms of standard time functions.
|
||||
type realClock struct{}
|
||||
|
||||
// Now implements Clock.Now by calling time.Now.
|
||||
func (realClock) Now() time.Time {
|
||||
return time.Now()
|
||||
}
|
||||
|
||||
// Now implements Clock.Sleep by calling time.Sleep.
|
||||
func (realClock) Sleep(d time.Duration) {
|
||||
time.Sleep(d)
|
||||
}
|
||||
|
|
@ -1,396 +0,0 @@
|
|||
// Copyright 2014 Canonical Ltd.
|
||||
// Licensed under the LGPLv3 with static-linking exception.
|
||||
// See LICENCE file for details.
|
||||
|
||||
package ratelimit
|
||||
|
||||
import (
|
||||
"math"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
gc "gopkg.in/check.v1"
|
||||
)
|
||||
|
||||
func TestPackage(t *testing.T) {
|
||||
gc.TestingT(t)
|
||||
}
|
||||
|
||||
type rateLimitSuite struct{}
|
||||
|
||||
var _ = gc.Suite(rateLimitSuite{})
|
||||
|
||||
type takeReq struct {
|
||||
time time.Duration
|
||||
count int64
|
||||
expectWait time.Duration
|
||||
}
|
||||
|
||||
var takeTests = []struct {
|
||||
about string
|
||||
fillInterval time.Duration
|
||||
capacity int64
|
||||
reqs []takeReq
|
||||
}{{
|
||||
about: "serial requests",
|
||||
fillInterval: 250 * time.Millisecond,
|
||||
capacity: 10,
|
||||
reqs: []takeReq{{
|
||||
time: 0,
|
||||
count: 0,
|
||||
expectWait: 0,
|
||||
}, {
|
||||
time: 0,
|
||||
count: 10,
|
||||
expectWait: 0,
|
||||
}, {
|
||||
time: 0,
|
||||
count: 1,
|
||||
expectWait: 250 * time.Millisecond,
|
||||
}, {
|
||||
time: 250 * time.Millisecond,
|
||||
count: 1,
|
||||
expectWait: 250 * time.Millisecond,
|
||||
}},
|
||||
}, {
|
||||
about: "concurrent requests",
|
||||
fillInterval: 250 * time.Millisecond,
|
||||
capacity: 10,
|
||||
reqs: []takeReq{{
|
||||
time: 0,
|
||||
count: 10,
|
||||
expectWait: 0,
|
||||
}, {
|
||||
time: 0,
|
||||
count: 2,
|
||||
expectWait: 500 * time.Millisecond,
|
||||
}, {
|
||||
time: 0,
|
||||
count: 2,
|
||||
expectWait: 1000 * time.Millisecond,
|
||||
}, {
|
||||
time: 0,
|
||||
count: 1,
|
||||
expectWait: 1250 * time.Millisecond,
|
||||
}},
|
||||
}, {
|
||||
about: "more than capacity",
|
||||
fillInterval: 1 * time.Millisecond,
|
||||
capacity: 10,
|
||||
reqs: []takeReq{{
|
||||
time: 0,
|
||||
count: 10,
|
||||
expectWait: 0,
|
||||
}, {
|
||||
time: 20 * time.Millisecond,
|
||||
count: 15,
|
||||
expectWait: 5 * time.Millisecond,
|
||||
}},
|
||||
}, {
|
||||
about: "sub-quantum time",
|
||||
fillInterval: 10 * time.Millisecond,
|
||||
capacity: 10,
|
||||
reqs: []takeReq{{
|
||||
time: 0,
|
||||
count: 10,
|
||||
expectWait: 0,
|
||||
}, {
|
||||
time: 7 * time.Millisecond,
|
||||
count: 1,
|
||||
expectWait: 3 * time.Millisecond,
|
||||
}, {
|
||||
time: 8 * time.Millisecond,
|
||||
count: 1,
|
||||
expectWait: 12 * time.Millisecond,
|
||||
}},
|
||||
}, {
|
||||
about: "within capacity",
|
||||
fillInterval: 10 * time.Millisecond,
|
||||
capacity: 5,
|
||||
reqs: []takeReq{{
|
||||
time: 0,
|
||||
count: 5,
|
||||
expectWait: 0,
|
||||
}, {
|
||||
time: 60 * time.Millisecond,
|
||||
count: 5,
|
||||
expectWait: 0,
|
||||
}, {
|
||||
time: 60 * time.Millisecond,
|
||||
count: 1,
|
||||
expectWait: 10 * time.Millisecond,
|
||||
}, {
|
||||
time: 80 * time.Millisecond,
|
||||
count: 2,
|
||||
expectWait: 10 * time.Millisecond,
|
||||
}},
|
||||
}}
|
||||
|
||||
var availTests = []struct {
|
||||
about string
|
||||
capacity int64
|
||||
fillInterval time.Duration
|
||||
take int64
|
||||
sleep time.Duration
|
||||
|
||||
expectCountAfterTake int64
|
||||
expectCountAfterSleep int64
|
||||
}{{
|
||||
about: "should fill tokens after interval",
|
||||
capacity: 5,
|
||||
fillInterval: time.Second,
|
||||
take: 5,
|
||||
sleep: time.Second,
|
||||
expectCountAfterTake: 0,
|
||||
expectCountAfterSleep: 1,
|
||||
}, {
|
||||
about: "should fill tokens plus existing count",
|
||||
capacity: 2,
|
||||
fillInterval: time.Second,
|
||||
take: 1,
|
||||
sleep: time.Second,
|
||||
expectCountAfterTake: 1,
|
||||
expectCountAfterSleep: 2,
|
||||
}, {
|
||||
about: "shouldn't fill before interval",
|
||||
capacity: 2,
|
||||
fillInterval: 2 * time.Second,
|
||||
take: 1,
|
||||
sleep: time.Second,
|
||||
expectCountAfterTake: 1,
|
||||
expectCountAfterSleep: 1,
|
||||
}, {
|
||||
about: "should fill only once after 1*interval before 2*interval",
|
||||
capacity: 2,
|
||||
fillInterval: 2 * time.Second,
|
||||
take: 1,
|
||||
sleep: 3 * time.Second,
|
||||
expectCountAfterTake: 1,
|
||||
expectCountAfterSleep: 2,
|
||||
}}
|
||||
|
||||
func (rateLimitSuite) TestTake(c *gc.C) {
|
||||
for i, test := range takeTests {
|
||||
tb := NewBucket(test.fillInterval, test.capacity)
|
||||
for j, req := range test.reqs {
|
||||
d, ok := tb.take(tb.startTime.Add(req.time), req.count, infinityDuration)
|
||||
c.Assert(ok, gc.Equals, true)
|
||||
if d != req.expectWait {
|
||||
c.Fatalf("test %d.%d, %s, got %v want %v", i, j, test.about, d, req.expectWait)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (rateLimitSuite) TestTakeMaxDuration(c *gc.C) {
|
||||
for i, test := range takeTests {
|
||||
tb := NewBucket(test.fillInterval, test.capacity)
|
||||
for j, req := range test.reqs {
|
||||
if req.expectWait > 0 {
|
||||
d, ok := tb.take(tb.startTime.Add(req.time), req.count, req.expectWait-1)
|
||||
c.Assert(ok, gc.Equals, false)
|
||||
c.Assert(d, gc.Equals, time.Duration(0))
|
||||
}
|
||||
d, ok := tb.take(tb.startTime.Add(req.time), req.count, req.expectWait)
|
||||
c.Assert(ok, gc.Equals, true)
|
||||
if d != req.expectWait {
|
||||
c.Fatalf("test %d.%d, %s, got %v want %v", i, j, test.about, d, req.expectWait)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type takeAvailableReq struct {
|
||||
time time.Duration
|
||||
count int64
|
||||
expect int64
|
||||
}
|
||||
|
||||
var takeAvailableTests = []struct {
|
||||
about string
|
||||
fillInterval time.Duration
|
||||
capacity int64
|
||||
reqs []takeAvailableReq
|
||||
}{{
|
||||
about: "serial requests",
|
||||
fillInterval: 250 * time.Millisecond,
|
||||
capacity: 10,
|
||||
reqs: []takeAvailableReq{{
|
||||
time: 0,
|
||||
count: 0,
|
||||
expect: 0,
|
||||
}, {
|
||||
time: 0,
|
||||
count: 10,
|
||||
expect: 10,
|
||||
}, {
|
||||
time: 0,
|
||||
count: 1,
|
||||
expect: 0,
|
||||
}, {
|
||||
time: 250 * time.Millisecond,
|
||||
count: 1,
|
||||
expect: 1,
|
||||
}},
|
||||
}, {
|
||||
about: "concurrent requests",
|
||||
fillInterval: 250 * time.Millisecond,
|
||||
capacity: 10,
|
||||
reqs: []takeAvailableReq{{
|
||||
time: 0,
|
||||
count: 5,
|
||||
expect: 5,
|
||||
}, {
|
||||
time: 0,
|
||||
count: 2,
|
||||
expect: 2,
|
||||
}, {
|
||||
time: 0,
|
||||
count: 5,
|
||||
expect: 3,
|
||||
}, {
|
||||
time: 0,
|
||||
count: 1,
|
||||
expect: 0,
|
||||
}},
|
||||
}, {
|
||||
about: "more than capacity",
|
||||
fillInterval: 1 * time.Millisecond,
|
||||
capacity: 10,
|
||||
reqs: []takeAvailableReq{{
|
||||
time: 0,
|
||||
count: 10,
|
||||
expect: 10,
|
||||
}, {
|
||||
time: 20 * time.Millisecond,
|
||||
count: 15,
|
||||
expect: 10,
|
||||
}},
|
||||
}, {
|
||||
about: "within capacity",
|
||||
fillInterval: 10 * time.Millisecond,
|
||||
capacity: 5,
|
||||
reqs: []takeAvailableReq{{
|
||||
time: 0,
|
||||
count: 5,
|
||||
expect: 5,
|
||||
}, {
|
||||
time: 60 * time.Millisecond,
|
||||
count: 5,
|
||||
expect: 5,
|
||||
}, {
|
||||
time: 70 * time.Millisecond,
|
||||
count: 1,
|
||||
expect: 1,
|
||||
}},
|
||||
}}
|
||||
|
||||
func (rateLimitSuite) TestTakeAvailable(c *gc.C) {
|
||||
for i, test := range takeAvailableTests {
|
||||
tb := NewBucket(test.fillInterval, test.capacity)
|
||||
for j, req := range test.reqs {
|
||||
d := tb.takeAvailable(tb.startTime.Add(req.time), req.count)
|
||||
if d != req.expect {
|
||||
c.Fatalf("test %d.%d, %s, got %v want %v", i, j, test.about, d, req.expect)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (rateLimitSuite) TestPanics(c *gc.C) {
|
||||
c.Assert(func() { NewBucket(0, 1) }, gc.PanicMatches, "token bucket fill interval is not > 0")
|
||||
c.Assert(func() { NewBucket(-2, 1) }, gc.PanicMatches, "token bucket fill interval is not > 0")
|
||||
c.Assert(func() { NewBucket(1, 0) }, gc.PanicMatches, "token bucket capacity is not > 0")
|
||||
c.Assert(func() { NewBucket(1, -2) }, gc.PanicMatches, "token bucket capacity is not > 0")
|
||||
}
|
||||
|
||||
func isCloseTo(x, y, tolerance float64) bool {
|
||||
return math.Abs(x-y)/y < tolerance
|
||||
}
|
||||
|
||||
func (rateLimitSuite) TestRate(c *gc.C) {
|
||||
tb := NewBucket(1, 1)
|
||||
if !isCloseTo(tb.Rate(), 1e9, 0.00001) {
|
||||
c.Fatalf("got %v want 1e9", tb.Rate())
|
||||
}
|
||||
tb = NewBucket(2*time.Second, 1)
|
||||
if !isCloseTo(tb.Rate(), 0.5, 0.00001) {
|
||||
c.Fatalf("got %v want 0.5", tb.Rate())
|
||||
}
|
||||
tb = NewBucketWithQuantum(100*time.Millisecond, 1, 5)
|
||||
if !isCloseTo(tb.Rate(), 50, 0.00001) {
|
||||
c.Fatalf("got %v want 50", tb.Rate())
|
||||
}
|
||||
}
|
||||
|
||||
func checkRate(c *gc.C, rate float64) {
|
||||
tb := NewBucketWithRate(rate, 1<<62)
|
||||
if !isCloseTo(tb.Rate(), rate, rateMargin) {
|
||||
c.Fatalf("got %g want %v", tb.Rate(), rate)
|
||||
}
|
||||
d, ok := tb.take(tb.startTime, 1<<62, infinityDuration)
|
||||
c.Assert(ok, gc.Equals, true)
|
||||
c.Assert(d, gc.Equals, time.Duration(0))
|
||||
|
||||
// Check that the actual rate is as expected by
|
||||
// asking for a not-quite multiple of the bucket's
|
||||
// quantum and checking that the wait time
|
||||
// correct.
|
||||
d, ok = tb.take(tb.startTime, tb.quantum*2-tb.quantum/2, infinityDuration)
|
||||
c.Assert(ok, gc.Equals, true)
|
||||
expectTime := 1e9 * float64(tb.quantum) * 2 / rate
|
||||
if !isCloseTo(float64(d), expectTime, rateMargin) {
|
||||
c.Fatalf("rate %g: got %g want %v", rate, float64(d), expectTime)
|
||||
}
|
||||
}
|
||||
|
||||
func (rateLimitSuite) NewBucketWithRate(c *gc.C) {
|
||||
for rate := float64(1); rate < 1e6; rate += 7 {
|
||||
checkRate(c, rate)
|
||||
}
|
||||
for _, rate := range []float64{
|
||||
1024 * 1024 * 1024,
|
||||
1e-5,
|
||||
0.9e-5,
|
||||
0.5,
|
||||
0.9,
|
||||
0.9e8,
|
||||
3e12,
|
||||
4e18,
|
||||
float64(1<<63 - 1),
|
||||
} {
|
||||
checkRate(c, rate)
|
||||
checkRate(c, rate/3)
|
||||
checkRate(c, rate*1.3)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAvailable(t *testing.T) {
|
||||
for i, tt := range availTests {
|
||||
tb := NewBucket(tt.fillInterval, tt.capacity)
|
||||
if c := tb.takeAvailable(tb.startTime, tt.take); c != tt.take {
|
||||
t.Fatalf("#%d: %s, take = %d, want = %d", i, tt.about, c, tt.take)
|
||||
}
|
||||
if c := tb.available(tb.startTime); c != tt.expectCountAfterTake {
|
||||
t.Fatalf("#%d: %s, after take, available = %d, want = %d", i, tt.about, c, tt.expectCountAfterTake)
|
||||
}
|
||||
if c := tb.available(tb.startTime.Add(tt.sleep)); c != tt.expectCountAfterSleep {
|
||||
t.Fatalf("#%d: %s, after some time it should fill in new tokens, available = %d, want = %d",
|
||||
i, tt.about, c, tt.expectCountAfterSleep)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func BenchmarkWait(b *testing.B) {
|
||||
tb := NewBucket(1, 16*1024)
|
||||
for i := b.N - 1; i >= 0; i-- {
|
||||
tb.Wait(1)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkNewBucket(b *testing.B) {
|
||||
for i := b.N - 1; i >= 0; i-- {
|
||||
NewBucketWithRate(4e18, 1<<62)
|
||||
}
|
||||
}
|
||||
|
|
@ -1,51 +0,0 @@
|
|||
// Copyright 2014 Canonical Ltd.
|
||||
// Licensed under the LGPLv3 with static-linking exception.
|
||||
// See LICENCE file for details.
|
||||
|
||||
package ratelimit
|
||||
|
||||
import "io"
|
||||
|
||||
type reader struct {
|
||||
r io.Reader
|
||||
bucket *Bucket
|
||||
}
|
||||
|
||||
// Reader returns a reader that is rate limited by
|
||||
// the given token bucket. Each token in the bucket
|
||||
// represents one byte.
|
||||
func Reader(r io.Reader, bucket *Bucket) io.Reader {
|
||||
return &reader{
|
||||
r: r,
|
||||
bucket: bucket,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *reader) Read(buf []byte) (int, error) {
|
||||
n, err := r.r.Read(buf)
|
||||
if n <= 0 {
|
||||
return n, err
|
||||
}
|
||||
r.bucket.Wait(int64(n))
|
||||
return n, err
|
||||
}
|
||||
|
||||
type writer struct {
|
||||
w io.Writer
|
||||
bucket *Bucket
|
||||
}
|
||||
|
||||
// Writer returns a reader that is rate limited by
|
||||
// the given token bucket. Each token in the bucket
|
||||
// represents one byte.
|
||||
func Writer(w io.Writer, bucket *Bucket) io.Writer {
|
||||
return &writer{
|
||||
w: w,
|
||||
bucket: bucket,
|
||||
}
|
||||
}
|
||||
|
||||
func (w *writer) Write(buf []byte) (int, error) {
|
||||
w.bucket.Wait(int64(len(buf)))
|
||||
return w.w.Write(buf)
|
||||
}
|
||||
|
|
@ -1,23 +0,0 @@
|
|||
syntax:glob
|
||||
*.[568ao]
|
||||
*.ao
|
||||
*.so
|
||||
*.pyc
|
||||
*.swp
|
||||
*.swo
|
||||
._*
|
||||
.nfs.*
|
||||
[568a].out
|
||||
*~
|
||||
*.orig
|
||||
*.pb.go
|
||||
core
|
||||
_obj
|
||||
_test
|
||||
src/pkg/Make.deps
|
||||
_testmain.go
|
||||
|
||||
syntax:regexp
|
||||
^pkg/
|
||||
^src/cmd/(.*)/6?\1$
|
||||
^.*/core.[0-9]*$
|
||||
|
|
@ -1,4 +0,0 @@
|
|||
Petar Maymounkov <petar@5ttt.org>
|
||||
Vadim Vygonets <vadik@vygo.net>
|
||||
Ian Smith <iansmith@acm.org>
|
||||
Martin Bruse
|
||||
|
|
@ -1,27 +0,0 @@
|
|||
Copyright (c) 2010, Petar Maymounkov
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification,
|
||||
are permitted provided that the following conditions are met:
|
||||
|
||||
(*) Redistributions of source code must retain the above copyright notice, this list
|
||||
of conditions and the following disclaimer.
|
||||
|
||||
(*) Redistributions in binary form must reproduce the above copyright notice, this
|
||||
list of conditions and the following disclaimer in the documentation and/or
|
||||
other materials provided with the distribution.
|
||||
|
||||
(*) Neither the name of Petar Maymounkov nor the names of its contributors may be
|
||||
used to endorse or promote products derived from this software without specific
|
||||
prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
||||
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
|
@ -1,66 +0,0 @@
|
|||
# GoLLRB
|
||||
|
||||
GoLLRB is a Left-Leaning Red-Black (LLRB) implementation of 2-3 balanced binary
|
||||
search trees in Go Language.
|
||||
|
||||
## Overview
|
||||
|
||||
As of this writing and to the best of the author's knowledge,
|
||||
Go still does not have a balanced binary search tree (BBST) data structure.
|
||||
These data structures are quite useful in a variety of cases. A BBST maintains
|
||||
elements in sorted order under dynamic updates (inserts and deletes) and can
|
||||
support various order-specific queries. Furthermore, in practice one often
|
||||
implements other common data structures like Priority Queues, using BBST's.
|
||||
|
||||
2-3 trees (a type of BBST's), as well as the runtime-similar 2-3-4 trees, are
|
||||
the de facto standard BBST algoritms found in implementations of Python, Java,
|
||||
and other libraries. The LLRB method of implementing 2-3 trees is a recent
|
||||
improvement over the traditional implementation. The LLRB approach was
|
||||
discovered relatively recently (in 2008) by Robert Sedgewick of Princeton
|
||||
University.
|
||||
|
||||
GoLLRB is a Go implementation of LLRB 2-3 trees.
|
||||
|
||||
## Maturity
|
||||
|
||||
GoLLRB has been used in some pretty heavy-weight machine learning tasks over many gigabytes of data.
|
||||
I consider it to be in stable, perhaps even production, shape. There are no known bugs.
|
||||
|
||||
## Installation
|
||||
|
||||
With a healthy Go Language installed, simply run `go get github.com/petar/GoLLRB/llrb`
|
||||
|
||||
## Example
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/petar/GoLLRB/llrb"
|
||||
)
|
||||
|
||||
func lessInt(a, b interface{}) bool { return a.(int) < b.(int) }
|
||||
|
||||
func main() {
|
||||
tree := llrb.New(lessInt)
|
||||
tree.ReplaceOrInsert(1)
|
||||
tree.ReplaceOrInsert(2)
|
||||
tree.ReplaceOrInsert(3)
|
||||
tree.ReplaceOrInsert(4)
|
||||
tree.DeleteMin()
|
||||
tree.Delete(4)
|
||||
c := tree.IterAscend()
|
||||
for {
|
||||
u := <-c
|
||||
if u == nil {
|
||||
break
|
||||
}
|
||||
fmt.Printf("%d\n", int(u.(int)))
|
||||
}
|
||||
}
|
||||
|
||||
## About
|
||||
|
||||
GoLLRB was written by [Petar Maymounkov](http://pdos.csail.mit.edu/~petar/).
|
||||
|
||||
Follow me on [Twitter @maymounkov](http://www.twitter.com/maymounkov)!
|
||||
File diff suppressed because one or more lines are too long
|
|
@ -1,475 +0,0 @@
|
|||
public class RedBlackBST<Key extends Comparable<Key>, Value>
|
||||
{
|
||||
private static final int BST = 0;
|
||||
private static final int TD234 = 1;
|
||||
private static final int BU23 = 2;
|
||||
private static final boolean RED = true;
|
||||
private static final boolean BLACK = false;
|
||||
|
||||
private Node root; // root of the BST
|
||||
private int k; // ordinal for drawing
|
||||
private final int species; // species kind of tree for insert
|
||||
private int heightBLACK; // black height of tree
|
||||
|
||||
RedBlackBST(int species)
|
||||
{ this.species = species; }
|
||||
|
||||
private class Node
|
||||
{
|
||||
Key key; // key
|
||||
Value value; // associated data
|
||||
Node left, right; // left and right subtrees
|
||||
boolean color; // color of parent link
|
||||
private int N; // number of nodes in tree rooted here
|
||||
private int height; // height of tree rooted here
|
||||
private double xc, yc; // for drawing
|
||||
|
||||
Node(Key key, Value value)
|
||||
{
|
||||
this.key = key;
|
||||
this.value = value;
|
||||
this.color = RED;
|
||||
this.N = 1;
|
||||
this.height = 1;
|
||||
}
|
||||
}
|
||||
|
||||
public int size()
|
||||
{ return size(root); }
|
||||
|
||||
private int size(Node x)
|
||||
{
|
||||
if (x == null) return 0;
|
||||
else return x.N;
|
||||
}
|
||||
|
||||
public int rootRank()
|
||||
{
|
||||
if (root == null) return 0;
|
||||
else return size(root.left);
|
||||
}
|
||||
|
||||
public int height()
|
||||
{ return height(root); }
|
||||
|
||||
public int heightB()
|
||||
{ return heightBLACK; }
|
||||
|
||||
private int height(Node x)
|
||||
{
|
||||
if (x == null) return 0;
|
||||
else return x.height;
|
||||
}
|
||||
|
||||
public boolean contains(Key key)
|
||||
{ return (get(key) != null); }
|
||||
|
||||
public Value get(Key key)
|
||||
{ return get(root, key); }
|
||||
|
||||
private Value get(Node x, Key key)
|
||||
{
|
||||
if (x == null) return null;
|
||||
if (eq (key, x.key)) return x.value;
|
||||
if (less(key, x.key)) return get(x.left, key);
|
||||
else return get(x.right, key);
|
||||
}
|
||||
|
||||
public Key min()
|
||||
{
|
||||
if (root == null) return null;
|
||||
else return min(root);
|
||||
}
|
||||
|
||||
private Key min(Node x)
|
||||
{
|
||||
if (x.left == null) return x.key;
|
||||
else return min(x.left);
|
||||
}
|
||||
|
||||
public Key max()
|
||||
{
|
||||
if (root == null) return null;
|
||||
else return max(root);
|
||||
}
|
||||
|
||||
private Key max(Node x)
|
||||
{
|
||||
if (x.right == null) return x.key;
|
||||
else return max(x.right);
|
||||
}
|
||||
|
||||
public void put(Key key, Value value)
|
||||
{
|
||||
root = insert(root, key, value);
|
||||
if (isRed(root)) heightBLACK++;
|
||||
root.color = BLACK;
|
||||
}
|
||||
|
||||
private Node insert(Node h, Key key, Value value)
|
||||
{
|
||||
if (h == null)
|
||||
return new Node(key, value);
|
||||
|
||||
if (species == TD234)
|
||||
if (isRed(h.left) && isRed(h.right))
|
||||
colorFlip(h);
|
||||
|
||||
if (eq(key, h.key))
|
||||
h.value = value;
|
||||
else if (less(key, h.key))
|
||||
h.left = insert(h.left, key, value);
|
||||
else
|
||||
h.right = insert(h.right, key, value);
|
||||
|
||||
if (species == BST) return setN(h);
|
||||
|
||||
if (isRed(h.right))
|
||||
h = rotateLeft(h);
|
||||
|
||||
if (isRed(h.left) && isRed(h.left.left))
|
||||
h = rotateRight(h);
|
||||
|
||||
if (species == BU23)
|
||||
if (isRed(h.left) && isRed(h.right))
|
||||
colorFlip(h);
|
||||
|
||||
return setN(h);
|
||||
}
|
||||
|
||||
public void deleteMin()
|
||||
{
|
||||
root = deleteMin(root);
|
||||
root.color = BLACK;
|
||||
}
|
||||
|
||||
private Node deleteMin(Node h)
|
||||
{
|
||||
if (h.left == null)
|
||||
return null;
|
||||
|
||||
if (!isRed(h.left) && !isRed(h.left.left))
|
||||
h = moveRedLeft(h);
|
||||
|
||||
h.left = deleteMin(h.left);
|
||||
|
||||
return fixUp(h);
|
||||
}
|
||||
|
||||
public void deleteMax()
|
||||
{
|
||||
root = deleteMax(root);
|
||||
root.color = BLACK;
|
||||
}
|
||||
|
||||
private Node deleteMax(Node h)
|
||||
{
|
||||
// if (h.right == null)
|
||||
// {
|
||||
// if (h.left != null)
|
||||
// h.left.color = BLACK;
|
||||
// return h.left;
|
||||
// }
|
||||
|
||||
if (isRed(h.left))
|
||||
h = rotateRight(h);
|
||||
|
||||
if (h.right == null)
|
||||
return null;
|
||||
|
||||
if (!isRed(h.right) && !isRed(h.right.left))
|
||||
h = moveRedRight(h);
|
||||
|
||||
h.right = deleteMax(h.right);
|
||||
|
||||
return fixUp(h);
|
||||
}
|
||||
|
||||
public void delete(Key key)
|
||||
{
|
||||
root = delete(root, key);
|
||||
root.color = BLACK;
|
||||
}
|
||||
|
||||
private Node delete(Node h, Key key)
|
||||
{
|
||||
if (less(key, h.key))
|
||||
{
|
||||
if (!isRed(h.left) && !isRed(h.left.left))
|
||||
h = moveRedLeft(h);
|
||||
h.left = delete(h.left, key);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (isRed(h.left))
|
||||
h = rotateRight(h);
|
||||
if (eq(key, h.key) && (h.right == null))
|
||||
return null;
|
||||
if (!isRed(h.right) && !isRed(h.right.left))
|
||||
h = moveRedRight(h);
|
||||
if (eq(key, h.key))
|
||||
{
|
||||
h.value = get(h.right, min(h.right));
|
||||
h.key = min(h.right);
|
||||
h.right = deleteMin(h.right);
|
||||
}
|
||||
else h.right = delete(h.right, key);
|
||||
}
|
||||
|
||||
return fixUp(h);
|
||||
}
|
||||
|
||||
// Helper methods
|
||||
|
||||
private boolean less(Key a, Key b) { return a.compareTo(b) < 0; }
|
||||
private boolean eq (Key a, Key b) { return a.compareTo(b) == 0; }
|
||||
|
||||
private boolean isRed(Node x)
|
||||
{
|
||||
if (x == null) return false;
|
||||
return (x.color == RED);
|
||||
}
|
||||
|
||||
private void colorFlip(Node h)
|
||||
{
|
||||
h.color = !h.color;
|
||||
h.left.color = !h.left.color;
|
||||
h.right.color = !h.right.color;
|
||||
}
|
||||
|
||||
private Node rotateLeft(Node h)
|
||||
{ // Make a right-leaning 3-node lean to the left.
|
||||
Node x = h.right;
|
||||
h.right = x.left;
|
||||
x.left = setN(h);
|
||||
x.color = x.left.color;
|
||||
x.left.color = RED;
|
||||
return setN(x);
|
||||
}
|
||||
|
||||
private Node rotateRight(Node h)
|
||||
{ // Make a left-leaning 3-node lean to the right.
|
||||
Node x = h.left;
|
||||
h.left = x.right;
|
||||
x.right = setN(h);
|
||||
x.color = x.right.color;
|
||||
x.right.color = RED;
|
||||
return setN(x);
|
||||
}
|
||||
|
||||
private Node moveRedLeft(Node h)
|
||||
{ // Assuming that h is red and both h.left and h.left.left
|
||||
// are black, make h.left or one of its children red.
|
||||
colorFlip(h);
|
||||
if (isRed(h.right.left))
|
||||
{
|
||||
h.right = rotateRight(h.right);
|
||||
h = rotateLeft(h);
|
||||
colorFlip(h);
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
private Node moveRedRight(Node h)
|
||||
{ // Assuming that h is red and both h.right and h.right.left
|
||||
// are black, make h.right or one of its children red.
|
||||
colorFlip(h);
|
||||
if (isRed(h.left.left))
|
||||
{
|
||||
h = rotateRight(h);
|
||||
colorFlip(h);
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
private Node fixUp(Node h)
|
||||
{
|
||||
if (isRed(h.right))
|
||||
h = rotateLeft(h);
|
||||
|
||||
if (isRed(h.left) && isRed(h.left.left))
|
||||
h = rotateRight(h);
|
||||
|
||||
if (isRed(h.left) && isRed(h.right))
|
||||
colorFlip(h);
|
||||
|
||||
return setN(h);
|
||||
}
|
||||
|
||||
private Node setN(Node h)
|
||||
{
|
||||
h.N = size(h.left) + size(h.right) + 1;
|
||||
if (height(h.left) > height(h.right)) h.height = height(h.left) + 1;
|
||||
else h.height = height(h.right) + 1;
|
||||
return h;
|
||||
}
|
||||
|
||||
public String toString()
|
||||
{
|
||||
if (root == null) return "";
|
||||
else return heightB() + " " + toString(root);
|
||||
}
|
||||
|
||||
public String toString(Node x)
|
||||
{
|
||||
String s = "(";
|
||||
if (x.left == null) s += "("; else s += toString(x.left);
|
||||
if (isRed(x)) s += "*";
|
||||
if (x.right == null) s += ")"; else s += toString(x.right);
|
||||
return s + ")";
|
||||
}
|
||||
|
||||
// Methods for tree drawing
|
||||
|
||||
public void draw(double y, double lineWidth, double nodeSize)
|
||||
{
|
||||
k = 0;
|
||||
setcoords(root, y);
|
||||
StdDraw.setPenColor(StdDraw.BLACK);
|
||||
StdDraw.setPenRadius(lineWidth);
|
||||
drawlines(root);
|
||||
StdDraw.setPenColor(StdDraw.WHITE);
|
||||
drawnodes(root, nodeSize);
|
||||
}
|
||||
|
||||
public void setcoords(Node x, double d)
|
||||
{
|
||||
if (x == null) return;
|
||||
setcoords(x.left, d-.04);
|
||||
x.xc = (0.5 + k++)/size(); x.yc = d - .04;
|
||||
setcoords(x.right, d-.04);
|
||||
}
|
||||
|
||||
public void drawlines(Node x)
|
||||
{
|
||||
if (x == null) return;
|
||||
drawlines(x.left);
|
||||
if (x.left != null)
|
||||
{
|
||||
if (x.left.color == RED) StdDraw.setPenColor(StdDraw.RED);
|
||||
else StdDraw.setPenColor(StdDraw.BLACK);
|
||||
StdDraw.line(x.xc, x.yc, x.left.xc, x.left.yc);
|
||||
}
|
||||
if (x.right != null)
|
||||
{
|
||||
if (x.right.color == RED) StdDraw.setPenColor(StdDraw.RED);
|
||||
else StdDraw.setPenColor(StdDraw.BLACK);
|
||||
StdDraw.line(x.xc, x.yc, x.right.xc, x.right.yc);
|
||||
}
|
||||
drawlines(x.right);
|
||||
}
|
||||
|
||||
public void drawnodes(Node x, double nodeSize)
|
||||
{
|
||||
if (x == null) return;
|
||||
drawnodes(x.left, nodeSize);
|
||||
StdDraw.filledCircle(x.xc, x.yc, nodeSize);
|
||||
drawnodes(x.right, nodeSize);
|
||||
}
|
||||
|
||||
public void mark(Key key)
|
||||
{
|
||||
StdDraw.setPenColor(StdDraw.BLACK);
|
||||
marknodes(key, root);
|
||||
}
|
||||
|
||||
public void marknodes(Key key, Node x)
|
||||
{
|
||||
if (x == null) return;
|
||||
marknodes(key, x.left);
|
||||
if (eq(key, x.key))
|
||||
StdDraw.filledCircle(x.xc, x.yc, .004);
|
||||
marknodes(key, x.right);
|
||||
}
|
||||
|
||||
public int ipl()
|
||||
{ return ipl(root); }
|
||||
|
||||
public int ipl(Node x)
|
||||
{
|
||||
if (x == null) return 0;
|
||||
return size(x) - 1 + ipl(x.left) + ipl(x.right);
|
||||
}
|
||||
|
||||
public int sizeRed()
|
||||
{ return sizeRed(root); }
|
||||
|
||||
public int sizeRed(Node x)
|
||||
{
|
||||
if (x == null) return 0;
|
||||
if (isRed(x)) return 1 + sizeRed(x.left) + sizeRed(x.right);
|
||||
else return sizeRed(x.left) + sizeRed(x.right);
|
||||
}
|
||||
|
||||
// Integrity checks
|
||||
|
||||
public boolean check()
|
||||
{ // Is this tree a red-black tree?
|
||||
return isBST() && is234() && isBalanced();
|
||||
}
|
||||
|
||||
private boolean isBST()
|
||||
{ // Is this tree a BST?
|
||||
return isBST(root, min(), max());
|
||||
}
|
||||
|
||||
private boolean isBST(Node x, Key min, Key max)
|
||||
{ // Are all the values in the BST rooted at x between min and max,
|
||||
// and does the same property hold for both subtrees?
|
||||
if (x == null) return true;
|
||||
if (less(x.key, min) || less(max, x.key)) return false;
|
||||
return isBST(x.left, min, x.key) && isBST(x.right, x.key, max);
|
||||
}
|
||||
|
||||
private boolean is234() { return is234(root); }
|
||||
private boolean is234(Node x)
|
||||
{ // Does the tree have no red right links, and at most two (left)
|
||||
// red links in a row on any path?
|
||||
if (x == null) return true;
|
||||
if (isRed(x.right)) return false;
|
||||
if (isRed(x))
|
||||
if (isRed(x.left))
|
||||
if (isRed(x.left.left)) return false;
|
||||
return is234(x.left) && is234(x.right);
|
||||
}
|
||||
|
||||
private boolean isBalanced()
|
||||
{ // Do all paths from root to leaf have same number of black edges?
|
||||
int black = 0; // number of black links on path from root to min
|
||||
Node x = root;
|
||||
while (x != null)
|
||||
{
|
||||
if (!isRed(x)) black++;
|
||||
x = x.left;
|
||||
}
|
||||
return isBalanced(root, black);
|
||||
}
|
||||
|
||||
private boolean isBalanced(Node x, int black)
|
||||
{ // Does every path from the root to a leaf have the given number
|
||||
// of black links?
|
||||
if (x == null && black == 0) return true;
|
||||
else if (x == null && black != 0) return false;
|
||||
if (!isRed(x)) black--;
|
||||
return isBalanced(x.left, black) && isBalanced(x.right, black);
|
||||
}
|
||||
|
||||
|
||||
public static void main(String[] args)
|
||||
{
|
||||
StdDraw.setPenRadius(.0025);
|
||||
int species = Integer.parseInt(args[0]);
|
||||
RedBlackBST<Integer, Integer> st;
|
||||
st = new RedBlackBST<Integer, Integer>(species);
|
||||
int[] a = { 3, 1, 4, 2, 5, 9, 6, 8, 7 };
|
||||
for (int i = 0; i < a.length; i++)
|
||||
st.put(a[i], i);
|
||||
StdOut.println(st);
|
||||
StdDraw.clear(StdDraw.LIGHT_GRAY);
|
||||
st.draw(.95, .0025, .008);
|
||||
StdOut.println(st.min() + " " + st.max() + " " + st.check());
|
||||
StdOut.println(st.ipl());
|
||||
StdOut.println(st.heightB());
|
||||
}
|
||||
|
||||
}
|
||||
Binary file not shown.
|
|
@ -1,26 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/petar/GoLLRB/llrb"
|
||||
)
|
||||
|
||||
func lessInt(a, b interface{}) bool { return a.(int) < b.(int) }
|
||||
|
||||
func main() {
|
||||
tree := llrb.New(lessInt)
|
||||
tree.ReplaceOrInsert(1)
|
||||
tree.ReplaceOrInsert(2)
|
||||
tree.ReplaceOrInsert(3)
|
||||
tree.ReplaceOrInsert(4)
|
||||
tree.DeleteMin()
|
||||
tree.Delete(4)
|
||||
c := tree.IterAscend()
|
||||
for {
|
||||
u := <-c
|
||||
if u == nil {
|
||||
break
|
||||
}
|
||||
fmt.Printf("%d\n", int(u.(int)))
|
||||
}
|
||||
}
|
||||
|
|
@ -1,39 +0,0 @@
|
|||
// Copyright 2010 Petar Maymounkov. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package llrb
|
||||
|
||||
import "math"
|
||||
|
||||
// avgVar maintains the average and variance of a stream of numbers
|
||||
// in a space-efficient manner.
|
||||
type avgVar struct {
|
||||
count int64
|
||||
sum, sumsq float64
|
||||
}
|
||||
|
||||
func (av *avgVar) Init() {
|
||||
av.count = 0
|
||||
av.sum = 0.0
|
||||
av.sumsq = 0.0
|
||||
}
|
||||
|
||||
func (av *avgVar) Add(sample float64) {
|
||||
av.count++
|
||||
av.sum += sample
|
||||
av.sumsq += sample * sample
|
||||
}
|
||||
|
||||
func (av *avgVar) GetCount() int64 { return av.count }
|
||||
|
||||
func (av *avgVar) GetAvg() float64 { return av.sum / float64(av.count) }
|
||||
|
||||
func (av *avgVar) GetTotal() float64 { return av.sum }
|
||||
|
||||
func (av *avgVar) GetVar() float64 {
|
||||
a := av.GetAvg()
|
||||
return av.sumsq/float64(av.count) - a*a
|
||||
}
|
||||
|
||||
func (av *avgVar) GetStdDev() float64 { return math.Sqrt(av.GetVar()) }
|
||||
|
|
@ -1,93 +0,0 @@
|
|||
package llrb
|
||||
|
||||
type ItemIterator func(i Item) bool
|
||||
|
||||
//func (t *Tree) Ascend(iterator ItemIterator) {
|
||||
// t.AscendGreaterOrEqual(Inf(-1), iterator)
|
||||
//}
|
||||
|
||||
func (t *LLRB) AscendRange(greaterOrEqual, lessThan Item, iterator ItemIterator) {
|
||||
t.ascendRange(t.root, greaterOrEqual, lessThan, iterator)
|
||||
}
|
||||
|
||||
func (t *LLRB) ascendRange(h *Node, inf, sup Item, iterator ItemIterator) bool {
|
||||
if h == nil {
|
||||
return true
|
||||
}
|
||||
if !less(h.Item, sup) {
|
||||
return t.ascendRange(h.Left, inf, sup, iterator)
|
||||
}
|
||||
if less(h.Item, inf) {
|
||||
return t.ascendRange(h.Right, inf, sup, iterator)
|
||||
}
|
||||
|
||||
if !t.ascendRange(h.Left, inf, sup, iterator) {
|
||||
return false
|
||||
}
|
||||
if !iterator(h.Item) {
|
||||
return false
|
||||
}
|
||||
return t.ascendRange(h.Right, inf, sup, iterator)
|
||||
}
|
||||
|
||||
// AscendGreaterOrEqual will call iterator once for each element greater or equal to
|
||||
// pivot in ascending order. It will stop whenever the iterator returns false.
|
||||
func (t *LLRB) AscendGreaterOrEqual(pivot Item, iterator ItemIterator) {
|
||||
t.ascendGreaterOrEqual(t.root, pivot, iterator)
|
||||
}
|
||||
|
||||
func (t *LLRB) ascendGreaterOrEqual(h *Node, pivot Item, iterator ItemIterator) bool {
|
||||
if h == nil {
|
||||
return true
|
||||
}
|
||||
if !less(h.Item, pivot) {
|
||||
if !t.ascendGreaterOrEqual(h.Left, pivot, iterator) {
|
||||
return false
|
||||
}
|
||||
if !iterator(h.Item) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return t.ascendGreaterOrEqual(h.Right, pivot, iterator)
|
||||
}
|
||||
|
||||
func (t *LLRB) AscendLessThan(pivot Item, iterator ItemIterator) {
|
||||
t.ascendLessThan(t.root, pivot, iterator)
|
||||
}
|
||||
|
||||
func (t *LLRB) ascendLessThan(h *Node, pivot Item, iterator ItemIterator) bool {
|
||||
if h == nil {
|
||||
return true
|
||||
}
|
||||
if !t.ascendLessThan(h.Left, pivot, iterator) {
|
||||
return false
|
||||
}
|
||||
if !iterator(h.Item) {
|
||||
return false
|
||||
}
|
||||
if less(h.Item, pivot) {
|
||||
return t.ascendLessThan(h.Left, pivot, iterator)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// DescendLessOrEqual will call iterator once for each element less than the
|
||||
// pivot in descending order. It will stop whenever the iterator returns false.
|
||||
func (t *LLRB) DescendLessOrEqual(pivot Item, iterator ItemIterator) {
|
||||
t.descendLessOrEqual(t.root, pivot, iterator)
|
||||
}
|
||||
|
||||
func (t *LLRB) descendLessOrEqual(h *Node, pivot Item, iterator ItemIterator) bool {
|
||||
if h == nil {
|
||||
return true
|
||||
}
|
||||
if less(h.Item, pivot) || !less(pivot, h.Item) {
|
||||
if !t.descendLessOrEqual(h.Right, pivot, iterator) {
|
||||
return false
|
||||
}
|
||||
if !iterator(h.Item) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return t.descendLessOrEqual(h.Left, pivot, iterator)
|
||||
}
|
||||
|
|
@ -1,76 +0,0 @@
|
|||
package llrb
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestAscendGreaterOrEqual(t *testing.T) {
|
||||
tree := New()
|
||||
tree.InsertNoReplace(Int(4))
|
||||
tree.InsertNoReplace(Int(6))
|
||||
tree.InsertNoReplace(Int(1))
|
||||
tree.InsertNoReplace(Int(3))
|
||||
var ary []Item
|
||||
tree.AscendGreaterOrEqual(Int(-1), func(i Item) bool {
|
||||
ary = append(ary, i)
|
||||
return true
|
||||
})
|
||||
expected := []Item{Int(1), Int(3), Int(4), Int(6)}
|
||||
if !reflect.DeepEqual(ary, expected) {
|
||||
t.Errorf("expected %v but got %v", expected, ary)
|
||||
}
|
||||
ary = nil
|
||||
tree.AscendGreaterOrEqual(Int(3), func(i Item) bool {
|
||||
ary = append(ary, i)
|
||||
return true
|
||||
})
|
||||
expected = []Item{Int(3), Int(4), Int(6)}
|
||||
if !reflect.DeepEqual(ary, expected) {
|
||||
t.Errorf("expected %v but got %v", expected, ary)
|
||||
}
|
||||
ary = nil
|
||||
tree.AscendGreaterOrEqual(Int(2), func(i Item) bool {
|
||||
ary = append(ary, i)
|
||||
return true
|
||||
})
|
||||
expected = []Item{Int(3), Int(4), Int(6)}
|
||||
if !reflect.DeepEqual(ary, expected) {
|
||||
t.Errorf("expected %v but got %v", expected, ary)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDescendLessOrEqual(t *testing.T) {
|
||||
tree := New()
|
||||
tree.InsertNoReplace(Int(4))
|
||||
tree.InsertNoReplace(Int(6))
|
||||
tree.InsertNoReplace(Int(1))
|
||||
tree.InsertNoReplace(Int(3))
|
||||
var ary []Item
|
||||
tree.DescendLessOrEqual(Int(10), func(i Item) bool {
|
||||
ary = append(ary, i)
|
||||
return true
|
||||
})
|
||||
expected := []Item{Int(6), Int(4), Int(3), Int(1)}
|
||||
if !reflect.DeepEqual(ary, expected) {
|
||||
t.Errorf("expected %v but got %v", expected, ary)
|
||||
}
|
||||
ary = nil
|
||||
tree.DescendLessOrEqual(Int(4), func(i Item) bool {
|
||||
ary = append(ary, i)
|
||||
return true
|
||||
})
|
||||
expected = []Item{Int(4), Int(3), Int(1)}
|
||||
if !reflect.DeepEqual(ary, expected) {
|
||||
t.Errorf("expected %v but got %v", expected, ary)
|
||||
}
|
||||
ary = nil
|
||||
tree.DescendLessOrEqual(Int(5), func(i Item) bool {
|
||||
ary = append(ary, i)
|
||||
return true
|
||||
})
|
||||
expected = []Item{Int(4), Int(3), Int(1)}
|
||||
if !reflect.DeepEqual(ary, expected) {
|
||||
t.Errorf("expected %v but got %v", expected, ary)
|
||||
}
|
||||
}
|
||||
|
|
@ -1,46 +0,0 @@
|
|||
// Copyright 2010 Petar Maymounkov. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package llrb
|
||||
|
||||
// GetHeight() returns an item in the tree with key @key, and it's height in the tree
|
||||
func (t *LLRB) GetHeight(key Item) (result Item, depth int) {
|
||||
return t.getHeight(t.root, key)
|
||||
}
|
||||
|
||||
func (t *LLRB) getHeight(h *Node, item Item) (Item, int) {
|
||||
if h == nil {
|
||||
return nil, 0
|
||||
}
|
||||
if less(item, h.Item) {
|
||||
result, depth := t.getHeight(h.Left, item)
|
||||
return result, depth + 1
|
||||
}
|
||||
if less(h.Item, item) {
|
||||
result, depth := t.getHeight(h.Right, item)
|
||||
return result, depth + 1
|
||||
}
|
||||
return h.Item, 0
|
||||
}
|
||||
|
||||
// HeightStats() returns the average and standard deviation of the height
|
||||
// of elements in the tree
|
||||
func (t *LLRB) HeightStats() (avg, stddev float64) {
|
||||
av := &avgVar{}
|
||||
heightStats(t.root, 0, av)
|
||||
return av.GetAvg(), av.GetStdDev()
|
||||
}
|
||||
|
||||
func heightStats(h *Node, d int, av *avgVar) {
|
||||
if h == nil {
|
||||
return
|
||||
}
|
||||
av.Add(float64(d))
|
||||
if h.Left != nil {
|
||||
heightStats(h.Left, d+1, av)
|
||||
}
|
||||
if h.Right != nil {
|
||||
heightStats(h.Right, d+1, av)
|
||||
}
|
||||
}
|
||||
|
|
@ -1,456 +0,0 @@
|
|||
// Copyright 2010 Petar Maymounkov. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// A Left-Leaning Red-Black (LLRB) implementation of 2-3 balanced binary search trees,
|
||||
// based on the following work:
|
||||
//
|
||||
// http://www.cs.princeton.edu/~rs/talks/LLRB/08Penn.pdf
|
||||
// http://www.cs.princeton.edu/~rs/talks/LLRB/LLRB.pdf
|
||||
// http://www.cs.princeton.edu/~rs/talks/LLRB/Java/RedBlackBST.java
|
||||
//
|
||||
// 2-3 trees (and the run-time equivalent 2-3-4 trees) are the de facto standard BST
|
||||
// algoritms found in implementations of Python, Java, and other libraries. The LLRB
|
||||
// implementation of 2-3 trees is a recent improvement on the traditional implementation,
|
||||
// observed and documented by Robert Sedgewick.
|
||||
//
|
||||
package llrb
|
||||
|
||||
// Tree is a Left-Leaning Red-Black (LLRB) implementation of 2-3 trees
|
||||
type LLRB struct {
|
||||
count int
|
||||
root *Node
|
||||
}
|
||||
|
||||
type Node struct {
|
||||
Item
|
||||
Left, Right *Node // Pointers to left and right child nodes
|
||||
Black bool // If set, the color of the link (incoming from the parent) is black
|
||||
// In the LLRB, new nodes are always red, hence the zero-value for node
|
||||
}
|
||||
|
||||
type Item interface {
|
||||
Less(than Item) bool
|
||||
}
|
||||
|
||||
//
|
||||
func less(x, y Item) bool {
|
||||
if x == pinf {
|
||||
return false
|
||||
}
|
||||
if x == ninf {
|
||||
return true
|
||||
}
|
||||
return x.Less(y)
|
||||
}
|
||||
|
||||
// Inf returns an Item that is "bigger than" any other item, if sign is positive.
|
||||
// Otherwise it returns an Item that is "smaller than" any other item.
|
||||
func Inf(sign int) Item {
|
||||
if sign == 0 {
|
||||
panic("sign")
|
||||
}
|
||||
if sign > 0 {
|
||||
return pinf
|
||||
}
|
||||
return ninf
|
||||
}
|
||||
|
||||
var (
|
||||
ninf = nInf{}
|
||||
pinf = pInf{}
|
||||
)
|
||||
|
||||
type nInf struct{}
|
||||
|
||||
func (nInf) Less(Item) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
type pInf struct{}
|
||||
|
||||
func (pInf) Less(Item) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// New() allocates a new tree
|
||||
func New() *LLRB {
|
||||
return &LLRB{}
|
||||
}
|
||||
|
||||
// SetRoot sets the root node of the tree.
|
||||
// It is intended to be used by functions that deserialize the tree.
|
||||
func (t *LLRB) SetRoot(r *Node) {
|
||||
t.root = r
|
||||
}
|
||||
|
||||
// Root returns the root node of the tree.
|
||||
// It is intended to be used by functions that serialize the tree.
|
||||
func (t *LLRB) Root() *Node {
|
||||
return t.root
|
||||
}
|
||||
|
||||
// Len returns the number of nodes in the tree.
|
||||
func (t *LLRB) Len() int { return t.count }
|
||||
|
||||
// Has returns true if the tree contains an element whose order is the same as that of key.
|
||||
func (t *LLRB) Has(key Item) bool {
|
||||
return t.Get(key) != nil
|
||||
}
|
||||
|
||||
// Get retrieves an element from the tree whose order is the same as that of key.
|
||||
func (t *LLRB) Get(key Item) Item {
|
||||
h := t.root
|
||||
for h != nil {
|
||||
switch {
|
||||
case less(key, h.Item):
|
||||
h = h.Left
|
||||
case less(h.Item, key):
|
||||
h = h.Right
|
||||
default:
|
||||
return h.Item
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Min returns the minimum element in the tree.
|
||||
func (t *LLRB) Min() Item {
|
||||
h := t.root
|
||||
if h == nil {
|
||||
return nil
|
||||
}
|
||||
for h.Left != nil {
|
||||
h = h.Left
|
||||
}
|
||||
return h.Item
|
||||
}
|
||||
|
||||
// Max returns the maximum element in the tree.
|
||||
func (t *LLRB) Max() Item {
|
||||
h := t.root
|
||||
if h == nil {
|
||||
return nil
|
||||
}
|
||||
for h.Right != nil {
|
||||
h = h.Right
|
||||
}
|
||||
return h.Item
|
||||
}
|
||||
|
||||
func (t *LLRB) ReplaceOrInsertBulk(items ...Item) {
|
||||
for _, i := range items {
|
||||
t.ReplaceOrInsert(i)
|
||||
}
|
||||
}
|
||||
|
||||
func (t *LLRB) InsertNoReplaceBulk(items ...Item) {
|
||||
for _, i := range items {
|
||||
t.InsertNoReplace(i)
|
||||
}
|
||||
}
|
||||
|
||||
// ReplaceOrInsert inserts item into the tree. If an existing
|
||||
// element has the same order, it is removed from the tree and returned.
|
||||
func (t *LLRB) ReplaceOrInsert(item Item) Item {
|
||||
if item == nil {
|
||||
panic("inserting nil item")
|
||||
}
|
||||
var replaced Item
|
||||
t.root, replaced = t.replaceOrInsert(t.root, item)
|
||||
t.root.Black = true
|
||||
if replaced == nil {
|
||||
t.count++
|
||||
}
|
||||
return replaced
|
||||
}
|
||||
|
||||
func (t *LLRB) replaceOrInsert(h *Node, item Item) (*Node, Item) {
|
||||
if h == nil {
|
||||
return newNode(item), nil
|
||||
}
|
||||
|
||||
h = walkDownRot23(h)
|
||||
|
||||
var replaced Item
|
||||
if less(item, h.Item) { // BUG
|
||||
h.Left, replaced = t.replaceOrInsert(h.Left, item)
|
||||
} else if less(h.Item, item) {
|
||||
h.Right, replaced = t.replaceOrInsert(h.Right, item)
|
||||
} else {
|
||||
replaced, h.Item = h.Item, item
|
||||
}
|
||||
|
||||
h = walkUpRot23(h)
|
||||
|
||||
return h, replaced
|
||||
}
|
||||
|
||||
// InsertNoReplace inserts item into the tree. If an existing
|
||||
// element has the same order, both elements remain in the tree.
|
||||
func (t *LLRB) InsertNoReplace(item Item) {
|
||||
if item == nil {
|
||||
panic("inserting nil item")
|
||||
}
|
||||
t.root = t.insertNoReplace(t.root, item)
|
||||
t.root.Black = true
|
||||
t.count++
|
||||
}
|
||||
|
||||
func (t *LLRB) insertNoReplace(h *Node, item Item) *Node {
|
||||
if h == nil {
|
||||
return newNode(item)
|
||||
}
|
||||
|
||||
h = walkDownRot23(h)
|
||||
|
||||
if less(item, h.Item) {
|
||||
h.Left = t.insertNoReplace(h.Left, item)
|
||||
} else {
|
||||
h.Right = t.insertNoReplace(h.Right, item)
|
||||
}
|
||||
|
||||
return walkUpRot23(h)
|
||||
}
|
||||
|
||||
// Rotation driver routines for 2-3 algorithm
|
||||
|
||||
func walkDownRot23(h *Node) *Node { return h }
|
||||
|
||||
func walkUpRot23(h *Node) *Node {
|
||||
if isRed(h.Right) && !isRed(h.Left) {
|
||||
h = rotateLeft(h)
|
||||
}
|
||||
|
||||
if isRed(h.Left) && isRed(h.Left.Left) {
|
||||
h = rotateRight(h)
|
||||
}
|
||||
|
||||
if isRed(h.Left) && isRed(h.Right) {
|
||||
flip(h)
|
||||
}
|
||||
|
||||
return h
|
||||
}
|
||||
|
||||
// Rotation driver routines for 2-3-4 algorithm
|
||||
|
||||
func walkDownRot234(h *Node) *Node {
|
||||
if isRed(h.Left) && isRed(h.Right) {
|
||||
flip(h)
|
||||
}
|
||||
|
||||
return h
|
||||
}
|
||||
|
||||
func walkUpRot234(h *Node) *Node {
|
||||
if isRed(h.Right) && !isRed(h.Left) {
|
||||
h = rotateLeft(h)
|
||||
}
|
||||
|
||||
if isRed(h.Left) && isRed(h.Left.Left) {
|
||||
h = rotateRight(h)
|
||||
}
|
||||
|
||||
return h
|
||||
}
|
||||
|
||||
// DeleteMin deletes the minimum element in the tree and returns the
|
||||
// deleted item or nil otherwise.
|
||||
func (t *LLRB) DeleteMin() Item {
|
||||
var deleted Item
|
||||
t.root, deleted = deleteMin(t.root)
|
||||
if t.root != nil {
|
||||
t.root.Black = true
|
||||
}
|
||||
if deleted != nil {
|
||||
t.count--
|
||||
}
|
||||
return deleted
|
||||
}
|
||||
|
||||
// deleteMin code for LLRB 2-3 trees
|
||||
func deleteMin(h *Node) (*Node, Item) {
|
||||
if h == nil {
|
||||
return nil, nil
|
||||
}
|
||||
if h.Left == nil {
|
||||
return nil, h.Item
|
||||
}
|
||||
|
||||
if !isRed(h.Left) && !isRed(h.Left.Left) {
|
||||
h = moveRedLeft(h)
|
||||
}
|
||||
|
||||
var deleted Item
|
||||
h.Left, deleted = deleteMin(h.Left)
|
||||
|
||||
return fixUp(h), deleted
|
||||
}
|
||||
|
||||
// DeleteMax deletes the maximum element in the tree and returns
|
||||
// the deleted item or nil otherwise
|
||||
func (t *LLRB) DeleteMax() Item {
|
||||
var deleted Item
|
||||
t.root, deleted = deleteMax(t.root)
|
||||
if t.root != nil {
|
||||
t.root.Black = true
|
||||
}
|
||||
if deleted != nil {
|
||||
t.count--
|
||||
}
|
||||
return deleted
|
||||
}
|
||||
|
||||
func deleteMax(h *Node) (*Node, Item) {
|
||||
if h == nil {
|
||||
return nil, nil
|
||||
}
|
||||
if isRed(h.Left) {
|
||||
h = rotateRight(h)
|
||||
}
|
||||
if h.Right == nil {
|
||||
return nil, h.Item
|
||||
}
|
||||
if !isRed(h.Right) && !isRed(h.Right.Left) {
|
||||
h = moveRedRight(h)
|
||||
}
|
||||
var deleted Item
|
||||
h.Right, deleted = deleteMax(h.Right)
|
||||
|
||||
return fixUp(h), deleted
|
||||
}
|
||||
|
||||
// Delete deletes an item from the tree whose key equals key.
|
||||
// The deleted item is return, otherwise nil is returned.
|
||||
func (t *LLRB) Delete(key Item) Item {
|
||||
var deleted Item
|
||||
t.root, deleted = t.delete(t.root, key)
|
||||
if t.root != nil {
|
||||
t.root.Black = true
|
||||
}
|
||||
if deleted != nil {
|
||||
t.count--
|
||||
}
|
||||
return deleted
|
||||
}
|
||||
|
||||
func (t *LLRB) delete(h *Node, item Item) (*Node, Item) {
|
||||
var deleted Item
|
||||
if h == nil {
|
||||
return nil, nil
|
||||
}
|
||||
if less(item, h.Item) {
|
||||
if h.Left == nil { // item not present. Nothing to delete
|
||||
return h, nil
|
||||
}
|
||||
if !isRed(h.Left) && !isRed(h.Left.Left) {
|
||||
h = moveRedLeft(h)
|
||||
}
|
||||
h.Left, deleted = t.delete(h.Left, item)
|
||||
} else {
|
||||
if isRed(h.Left) {
|
||||
h = rotateRight(h)
|
||||
}
|
||||
// If @item equals @h.Item and no right children at @h
|
||||
if !less(h.Item, item) && h.Right == nil {
|
||||
return nil, h.Item
|
||||
}
|
||||
// PETAR: Added 'h.Right != nil' below
|
||||
if h.Right != nil && !isRed(h.Right) && !isRed(h.Right.Left) {
|
||||
h = moveRedRight(h)
|
||||
}
|
||||
// If @item equals @h.Item, and (from above) 'h.Right != nil'
|
||||
if !less(h.Item, item) {
|
||||
var subDeleted Item
|
||||
h.Right, subDeleted = deleteMin(h.Right)
|
||||
if subDeleted == nil {
|
||||
panic("logic")
|
||||
}
|
||||
deleted, h.Item = h.Item, subDeleted
|
||||
} else { // Else, @item is bigger than @h.Item
|
||||
h.Right, deleted = t.delete(h.Right, item)
|
||||
}
|
||||
}
|
||||
|
||||
return fixUp(h), deleted
|
||||
}
|
||||
|
||||
// Internal node manipulation routines
|
||||
|
||||
func newNode(item Item) *Node { return &Node{Item: item} }
|
||||
|
||||
func isRed(h *Node) bool {
|
||||
if h == nil {
|
||||
return false
|
||||
}
|
||||
return !h.Black
|
||||
}
|
||||
|
||||
func rotateLeft(h *Node) *Node {
|
||||
x := h.Right
|
||||
if x.Black {
|
||||
panic("rotating a black link")
|
||||
}
|
||||
h.Right = x.Left
|
||||
x.Left = h
|
||||
x.Black = h.Black
|
||||
h.Black = false
|
||||
return x
|
||||
}
|
||||
|
||||
func rotateRight(h *Node) *Node {
|
||||
x := h.Left
|
||||
if x.Black {
|
||||
panic("rotating a black link")
|
||||
}
|
||||
h.Left = x.Right
|
||||
x.Right = h
|
||||
x.Black = h.Black
|
||||
h.Black = false
|
||||
return x
|
||||
}
|
||||
|
||||
// REQUIRE: Left and Right children must be present
|
||||
func flip(h *Node) {
|
||||
h.Black = !h.Black
|
||||
h.Left.Black = !h.Left.Black
|
||||
h.Right.Black = !h.Right.Black
|
||||
}
|
||||
|
||||
// REQUIRE: Left and Right children must be present
|
||||
func moveRedLeft(h *Node) *Node {
|
||||
flip(h)
|
||||
if isRed(h.Right.Left) {
|
||||
h.Right = rotateRight(h.Right)
|
||||
h = rotateLeft(h)
|
||||
flip(h)
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
// REQUIRE: Left and Right children must be present
|
||||
func moveRedRight(h *Node) *Node {
|
||||
flip(h)
|
||||
if isRed(h.Left.Left) {
|
||||
h = rotateRight(h)
|
||||
flip(h)
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
func fixUp(h *Node) *Node {
|
||||
if isRed(h.Right) {
|
||||
h = rotateLeft(h)
|
||||
}
|
||||
|
||||
if isRed(h.Left) && isRed(h.Left.Left) {
|
||||
h = rotateRight(h)
|
||||
}
|
||||
|
||||
if isRed(h.Left) && isRed(h.Right) {
|
||||
flip(h)
|
||||
}
|
||||
|
||||
return h
|
||||
}
|
||||
|
|
@ -1,239 +0,0 @@
|
|||
// Copyright 2010 Petar Maymounkov. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package llrb
|
||||
|
||||
import (
|
||||
"math"
|
||||
"math/rand"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCases(t *testing.T) {
|
||||
tree := New()
|
||||
tree.ReplaceOrInsert(Int(1))
|
||||
tree.ReplaceOrInsert(Int(1))
|
||||
if tree.Len() != 1 {
|
||||
t.Errorf("expecting len 1")
|
||||
}
|
||||
if !tree.Has(Int(1)) {
|
||||
t.Errorf("expecting to find key=1")
|
||||
}
|
||||
|
||||
tree.Delete(Int(1))
|
||||
if tree.Len() != 0 {
|
||||
t.Errorf("expecting len 0")
|
||||
}
|
||||
if tree.Has(Int(1)) {
|
||||
t.Errorf("not expecting to find key=1")
|
||||
}
|
||||
|
||||
tree.Delete(Int(1))
|
||||
if tree.Len() != 0 {
|
||||
t.Errorf("expecting len 0")
|
||||
}
|
||||
if tree.Has(Int(1)) {
|
||||
t.Errorf("not expecting to find key=1")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReverseInsertOrder(t *testing.T) {
|
||||
tree := New()
|
||||
n := 100
|
||||
for i := 0; i < n; i++ {
|
||||
tree.ReplaceOrInsert(Int(n - i))
|
||||
}
|
||||
i := 0
|
||||
tree.AscendGreaterOrEqual(Int(0), func(item Item) bool {
|
||||
i++
|
||||
if item.(Int) != Int(i) {
|
||||
t.Errorf("bad order: got %d, expect %d", item.(Int), i)
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
func TestRange(t *testing.T) {
|
||||
tree := New()
|
||||
order := []String{
|
||||
"ab", "aba", "abc", "a", "aa", "aaa", "b", "a-", "a!",
|
||||
}
|
||||
for _, i := range order {
|
||||
tree.ReplaceOrInsert(i)
|
||||
}
|
||||
k := 0
|
||||
tree.AscendRange(String("ab"), String("ac"), func(item Item) bool {
|
||||
if k > 3 {
|
||||
t.Fatalf("returned more items than expected")
|
||||
}
|
||||
i1 := order[k]
|
||||
i2 := item.(String)
|
||||
if i1 != i2 {
|
||||
t.Errorf("expecting %s, got %s", i1, i2)
|
||||
}
|
||||
k++
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
func TestRandomInsertOrder(t *testing.T) {
|
||||
tree := New()
|
||||
n := 1000
|
||||
perm := rand.Perm(n)
|
||||
for i := 0; i < n; i++ {
|
||||
tree.ReplaceOrInsert(Int(perm[i]))
|
||||
}
|
||||
j := 0
|
||||
tree.AscendGreaterOrEqual(Int(0), func(item Item) bool {
|
||||
if item.(Int) != Int(j) {
|
||||
t.Fatalf("bad order")
|
||||
}
|
||||
j++
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
func TestRandomReplace(t *testing.T) {
|
||||
tree := New()
|
||||
n := 100
|
||||
perm := rand.Perm(n)
|
||||
for i := 0; i < n; i++ {
|
||||
tree.ReplaceOrInsert(Int(perm[i]))
|
||||
}
|
||||
perm = rand.Perm(n)
|
||||
for i := 0; i < n; i++ {
|
||||
if replaced := tree.ReplaceOrInsert(Int(perm[i])); replaced == nil || replaced.(Int) != Int(perm[i]) {
|
||||
t.Errorf("error replacing")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRandomInsertSequentialDelete(t *testing.T) {
|
||||
tree := New()
|
||||
n := 1000
|
||||
perm := rand.Perm(n)
|
||||
for i := 0; i < n; i++ {
|
||||
tree.ReplaceOrInsert(Int(perm[i]))
|
||||
}
|
||||
for i := 0; i < n; i++ {
|
||||
tree.Delete(Int(i))
|
||||
}
|
||||
}
|
||||
|
||||
func TestRandomInsertDeleteNonExistent(t *testing.T) {
|
||||
tree := New()
|
||||
n := 100
|
||||
perm := rand.Perm(n)
|
||||
for i := 0; i < n; i++ {
|
||||
tree.ReplaceOrInsert(Int(perm[i]))
|
||||
}
|
||||
if tree.Delete(Int(200)) != nil {
|
||||
t.Errorf("deleted non-existent item")
|
||||
}
|
||||
if tree.Delete(Int(-2)) != nil {
|
||||
t.Errorf("deleted non-existent item")
|
||||
}
|
||||
for i := 0; i < n; i++ {
|
||||
if u := tree.Delete(Int(i)); u == nil || u.(Int) != Int(i) {
|
||||
t.Errorf("delete failed")
|
||||
}
|
||||
}
|
||||
if tree.Delete(Int(200)) != nil {
|
||||
t.Errorf("deleted non-existent item")
|
||||
}
|
||||
if tree.Delete(Int(-2)) != nil {
|
||||
t.Errorf("deleted non-existent item")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRandomInsertPartialDeleteOrder(t *testing.T) {
|
||||
tree := New()
|
||||
n := 100
|
||||
perm := rand.Perm(n)
|
||||
for i := 0; i < n; i++ {
|
||||
tree.ReplaceOrInsert(Int(perm[i]))
|
||||
}
|
||||
for i := 1; i < n-1; i++ {
|
||||
tree.Delete(Int(i))
|
||||
}
|
||||
j := 0
|
||||
tree.AscendGreaterOrEqual(Int(0), func(item Item) bool {
|
||||
switch j {
|
||||
case 0:
|
||||
if item.(Int) != Int(0) {
|
||||
t.Errorf("expecting 0")
|
||||
}
|
||||
case 1:
|
||||
if item.(Int) != Int(n-1) {
|
||||
t.Errorf("expecting %d", n-1)
|
||||
}
|
||||
}
|
||||
j++
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
func TestRandomInsertStats(t *testing.T) {
|
||||
tree := New()
|
||||
n := 100000
|
||||
perm := rand.Perm(n)
|
||||
for i := 0; i < n; i++ {
|
||||
tree.ReplaceOrInsert(Int(perm[i]))
|
||||
}
|
||||
avg, _ := tree.HeightStats()
|
||||
expAvg := math.Log2(float64(n)) - 1.5
|
||||
if math.Abs(avg-expAvg) >= 2.0 {
|
||||
t.Errorf("too much deviation from expected average height")
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkInsert(b *testing.B) {
|
||||
tree := New()
|
||||
for i := 0; i < b.N; i++ {
|
||||
tree.ReplaceOrInsert(Int(b.N - i))
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkDelete(b *testing.B) {
|
||||
b.StopTimer()
|
||||
tree := New()
|
||||
for i := 0; i < b.N; i++ {
|
||||
tree.ReplaceOrInsert(Int(b.N - i))
|
||||
}
|
||||
b.StartTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
tree.Delete(Int(i))
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkDeleteMin(b *testing.B) {
|
||||
b.StopTimer()
|
||||
tree := New()
|
||||
for i := 0; i < b.N; i++ {
|
||||
tree.ReplaceOrInsert(Int(b.N - i))
|
||||
}
|
||||
b.StartTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
tree.DeleteMin()
|
||||
}
|
||||
}
|
||||
|
||||
func TestInsertNoReplace(t *testing.T) {
|
||||
tree := New()
|
||||
n := 1000
|
||||
for q := 0; q < 2; q++ {
|
||||
perm := rand.Perm(n)
|
||||
for i := 0; i < n; i++ {
|
||||
tree.InsertNoReplace(Int(perm[i]))
|
||||
}
|
||||
}
|
||||
j := 0
|
||||
tree.AscendGreaterOrEqual(Int(0), func(item Item) bool {
|
||||
if item.(Int) != Int(j/2) {
|
||||
t.Fatalf("bad order")
|
||||
}
|
||||
j++
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
|
@ -1,17 +0,0 @@
|
|||
// Copyright 2010 Petar Maymounkov. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package llrb
|
||||
|
||||
type Int int
|
||||
|
||||
func (x Int) Less(than Item) bool {
|
||||
return x < than.(Int)
|
||||
}
|
||||
|
||||
type String string
|
||||
|
||||
func (x String) Less(than Item) bool {
|
||||
return x < than.(String)
|
||||
}
|
||||
|
|
@ -1,19 +0,0 @@
|
|||
Copyright (c) 2011-2012 Peter Bourgon
|
||||
|
||||
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.
|
||||
|
|
@ -1,141 +0,0 @@
|
|||
# What is diskv?
|
||||
|
||||
Diskv (disk-vee) is a simple, persistent key-value store written in the Go
|
||||
language. It starts with an incredibly simple API for storing arbitrary data on
|
||||
a filesystem by key, and builds several layers of performance-enhancing
|
||||
abstraction on top. The end result is a conceptually simple, but highly
|
||||
performant, disk-backed storage system.
|
||||
|
||||
[![Build Status][1]][2]
|
||||
|
||||
[1]: https://drone.io/github.com/peterbourgon/diskv/status.png
|
||||
[2]: https://drone.io/github.com/peterbourgon/diskv/latest
|
||||
|
||||
|
||||
# Installing
|
||||
|
||||
Install [Go 1][3], either [from source][4] or [with a prepackaged binary][5].
|
||||
Then,
|
||||
|
||||
```bash
|
||||
$ go get github.com/peterbourgon/diskv
|
||||
```
|
||||
|
||||
[3]: http://golang.org
|
||||
[4]: http://golang.org/doc/install/source
|
||||
[5]: http://golang.org/doc/install
|
||||
|
||||
|
||||
# Usage
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/peterbourgon/diskv"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// Simplest transform function: put all the data files into the base dir.
|
||||
flatTransform := func(s string) []string { return []string{} }
|
||||
|
||||
// Initialize a new diskv store, rooted at "my-data-dir", with a 1MB cache.
|
||||
d := diskv.New(diskv.Options{
|
||||
BasePath: "my-data-dir",
|
||||
Transform: flatTransform,
|
||||
CacheSizeMax: 1024 * 1024,
|
||||
})
|
||||
|
||||
// Write three bytes to the key "alpha".
|
||||
key := "alpha"
|
||||
d.Write(key, []byte{'1', '2', '3'})
|
||||
|
||||
// Read the value back out of the store.
|
||||
value, _ := d.Read(key)
|
||||
fmt.Printf("%v\n", value)
|
||||
|
||||
// Erase the key+value from the store (and the disk).
|
||||
d.Erase(key)
|
||||
}
|
||||
```
|
||||
|
||||
More complex examples can be found in the "examples" subdirectory.
|
||||
|
||||
|
||||
# Theory
|
||||
|
||||
## Basic idea
|
||||
|
||||
At its core, diskv is a map of a key (`string`) to arbitrary data (`[]byte`).
|
||||
The data is written to a single file on disk, with the same name as the key.
|
||||
The key determines where that file will be stored, via a user-provided
|
||||
`TransformFunc`, which takes a key and returns a slice (`[]string`)
|
||||
corresponding to a path list where the key file will be stored. The simplest
|
||||
TransformFunc,
|
||||
|
||||
```go
|
||||
func SimpleTransform (key string) []string {
|
||||
return []string{}
|
||||
}
|
||||
```
|
||||
|
||||
will place all keys in the same, base directory. The design is inspired by
|
||||
[Redis diskstore][6]; a TransformFunc which emulates the default diskstore
|
||||
behavior is available in the content-addressable-storage example.
|
||||
|
||||
[6]: http://groups.google.com/group/redis-db/browse_thread/thread/d444bc786689bde9?pli=1
|
||||
|
||||
**Note** that your TransformFunc should ensure that one valid key doesn't
|
||||
transform to a subset of another valid key. That is, it shouldn't be possible
|
||||
to construct valid keys that resolve to directory names. As a concrete example,
|
||||
if your TransformFunc splits on every 3 characters, then
|
||||
|
||||
```go
|
||||
d.Write("abcabc", val) // OK: written to <base>/abc/abc/abcabc
|
||||
d.Write("abc", val) // Error: attempted write to <base>/abc/abc, but it's a directory
|
||||
```
|
||||
|
||||
This will be addressed in an upcoming version of diskv.
|
||||
|
||||
Probably the most important design principle behind diskv is that your data is
|
||||
always flatly available on the disk. diskv will never do anything that would
|
||||
prevent you from accessing, copying, backing up, or otherwise interacting with
|
||||
your data via common UNIX commandline tools.
|
||||
|
||||
## Adding a cache
|
||||
|
||||
An in-memory caching layer is provided by combining the BasicStore
|
||||
functionality with a simple map structure, and keeping it up-to-date as
|
||||
appropriate. Since the map structure in Go is not threadsafe, it's combined
|
||||
with a RWMutex to provide safe concurrent access.
|
||||
|
||||
## Adding order
|
||||
|
||||
diskv is a key-value store and therefore inherently unordered. An ordering
|
||||
system can be injected into the store by passing something which satisfies the
|
||||
diskv.Index interface. (A default implementation, using Google's
|
||||
[btree][7] package, is provided.) Basically, diskv keeps an ordered (by a
|
||||
user-provided Less function) index of the keys, which can be queried.
|
||||
|
||||
[7]: https://github.com/google/btree
|
||||
|
||||
## Adding compression
|
||||
|
||||
Something which implements the diskv.Compression interface may be passed
|
||||
during store creation, so that all Writes and Reads are filtered through
|
||||
a compression/decompression pipeline. Several default implementations,
|
||||
using stdlib compression algorithms, are provided. Note that data is cached
|
||||
compressed; the cost of decompression is borne with each Read.
|
||||
|
||||
## Streaming
|
||||
|
||||
diskv also now provides ReadStream and WriteStream methods, to allow very large
|
||||
data to be handled efficiently.
|
||||
|
||||
|
||||
# Future plans
|
||||
|
||||
* Needs plenty of robust testing: huge datasets, etc...
|
||||
* More thorough benchmarking
|
||||
* Your suggestions for use-cases I haven't thought of
|
||||
|
|
@ -1,336 +0,0 @@
|
|||
package diskv
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func cmpBytes(a, b []byte) bool {
|
||||
if len(a) != len(b) {
|
||||
return false
|
||||
}
|
||||
for i := 0; i < len(a); i++ {
|
||||
if a[i] != b[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (d *Diskv) isCached(key string) bool {
|
||||
d.mu.RLock()
|
||||
defer d.mu.RUnlock()
|
||||
_, ok := d.cache[key]
|
||||
return ok
|
||||
}
|
||||
|
||||
func TestWriteReadErase(t *testing.T) {
|
||||
d := New(Options{
|
||||
BasePath: "test-data",
|
||||
CacheSizeMax: 1024,
|
||||
})
|
||||
defer d.EraseAll()
|
||||
k, v := "a", []byte{'b'}
|
||||
if err := d.Write(k, v); err != nil {
|
||||
t.Fatalf("write: %s", err)
|
||||
}
|
||||
if readVal, err := d.Read(k); err != nil {
|
||||
t.Fatalf("read: %s", err)
|
||||
} else if bytes.Compare(v, readVal) != 0 {
|
||||
t.Fatalf("read: expected %s, got %s", v, readVal)
|
||||
}
|
||||
if err := d.Erase(k); err != nil {
|
||||
t.Fatalf("erase: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWRECache(t *testing.T) {
|
||||
d := New(Options{
|
||||
BasePath: "test-data",
|
||||
CacheSizeMax: 1024,
|
||||
})
|
||||
defer d.EraseAll()
|
||||
k, v := "xxx", []byte{' ', ' ', ' '}
|
||||
if d.isCached(k) {
|
||||
t.Fatalf("key cached before Write and Read")
|
||||
}
|
||||
if err := d.Write(k, v); err != nil {
|
||||
t.Fatalf("write: %s", err)
|
||||
}
|
||||
if d.isCached(k) {
|
||||
t.Fatalf("key cached before Read")
|
||||
}
|
||||
if readVal, err := d.Read(k); err != nil {
|
||||
t.Fatalf("read: %s", err)
|
||||
} else if bytes.Compare(v, readVal) != 0 {
|
||||
t.Fatalf("read: expected %s, got %s", v, readVal)
|
||||
}
|
||||
for i := 0; i < 10 && !d.isCached(k); i++ {
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
if !d.isCached(k) {
|
||||
t.Fatalf("key not cached after Read")
|
||||
}
|
||||
if err := d.Erase(k); err != nil {
|
||||
t.Fatalf("erase: %s", err)
|
||||
}
|
||||
if d.isCached(k) {
|
||||
t.Fatalf("key cached after Erase")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStrings(t *testing.T) {
|
||||
d := New(Options{
|
||||
BasePath: "test-data",
|
||||
CacheSizeMax: 1024,
|
||||
})
|
||||
defer d.EraseAll()
|
||||
|
||||
keys := map[string]bool{"a": false, "b": false, "c": false, "d": false}
|
||||
v := []byte{'1'}
|
||||
for k := range keys {
|
||||
if err := d.Write(k, v); err != nil {
|
||||
t.Fatalf("write: %s: %s", k, err)
|
||||
}
|
||||
}
|
||||
|
||||
for k := range d.Keys(nil) {
|
||||
if _, present := keys[k]; present {
|
||||
t.Logf("got: %s", k)
|
||||
keys[k] = true
|
||||
} else {
|
||||
t.Fatalf("strings() returns unknown key: %s", k)
|
||||
}
|
||||
}
|
||||
|
||||
for k, found := range keys {
|
||||
if !found {
|
||||
t.Errorf("never got %s", k)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestZeroByteCache(t *testing.T) {
|
||||
d := New(Options{
|
||||
BasePath: "test-data",
|
||||
CacheSizeMax: 0,
|
||||
})
|
||||
defer d.EraseAll()
|
||||
|
||||
k, v := "a", []byte{'1', '2', '3'}
|
||||
if err := d.Write(k, v); err != nil {
|
||||
t.Fatalf("Write: %s", err)
|
||||
}
|
||||
|
||||
if d.isCached(k) {
|
||||
t.Fatalf("key cached, expected not-cached")
|
||||
}
|
||||
|
||||
if _, err := d.Read(k); err != nil {
|
||||
t.Fatalf("Read: %s", err)
|
||||
}
|
||||
|
||||
if d.isCached(k) {
|
||||
t.Fatalf("key cached, expected not-cached")
|
||||
}
|
||||
}
|
||||
|
||||
func TestOneByteCache(t *testing.T) {
|
||||
d := New(Options{
|
||||
BasePath: "test-data",
|
||||
CacheSizeMax: 1,
|
||||
})
|
||||
defer d.EraseAll()
|
||||
|
||||
k1, k2, v1, v2 := "a", "b", []byte{'1'}, []byte{'1', '2'}
|
||||
if err := d.Write(k1, v1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if v, err := d.Read(k1); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if !cmpBytes(v, v1) {
|
||||
t.Fatalf("Read: expected %s, got %s", string(v1), string(v))
|
||||
}
|
||||
|
||||
for i := 0; i < 10 && !d.isCached(k1); i++ {
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
if !d.isCached(k1) {
|
||||
t.Fatalf("expected 1-byte value to be cached, but it wasn't")
|
||||
}
|
||||
|
||||
if err := d.Write(k2, v2); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := d.Read(k2); err != nil {
|
||||
t.Fatalf("--> %s", err)
|
||||
}
|
||||
|
||||
for i := 0; i < 10 && (!d.isCached(k1) || d.isCached(k2)); i++ {
|
||||
time.Sleep(10 * time.Millisecond) // just wait for lazy-cache
|
||||
}
|
||||
if !d.isCached(k1) {
|
||||
t.Fatalf("1-byte value was uncached for no reason")
|
||||
}
|
||||
|
||||
if d.isCached(k2) {
|
||||
t.Fatalf("2-byte value was cached, but cache max size is 1")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStaleCache(t *testing.T) {
|
||||
d := New(Options{
|
||||
BasePath: "test-data",
|
||||
CacheSizeMax: 1,
|
||||
})
|
||||
defer d.EraseAll()
|
||||
|
||||
k, first, second := "a", "first", "second"
|
||||
if err := d.Write(k, []byte(first)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
v, err := d.Read(k)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(v) != first {
|
||||
t.Errorf("expected '%s', got '%s'", first, v)
|
||||
}
|
||||
|
||||
if err := d.Write(k, []byte(second)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
v, err = d.Read(k)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if string(v) != second {
|
||||
t.Errorf("expected '%s', got '%s'", second, v)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHas(t *testing.T) {
|
||||
d := New(Options{
|
||||
BasePath: "test-data",
|
||||
CacheSizeMax: 1024,
|
||||
})
|
||||
defer d.EraseAll()
|
||||
|
||||
for k, v := range map[string]string{
|
||||
"a": "1",
|
||||
"foo": "2",
|
||||
"012345": "3",
|
||||
} {
|
||||
d.Write(k, []byte(v))
|
||||
}
|
||||
|
||||
d.Read("foo") // cache one of them
|
||||
if !d.isCached("foo") {
|
||||
t.Errorf("'foo' didn't get cached")
|
||||
}
|
||||
|
||||
for _, tuple := range []struct {
|
||||
key string
|
||||
expected bool
|
||||
}{
|
||||
{"a", true},
|
||||
{"b", false},
|
||||
{"foo", true},
|
||||
{"bar", false},
|
||||
{"01234", false},
|
||||
{"012345", true},
|
||||
{"0123456", false},
|
||||
} {
|
||||
if expected, got := tuple.expected, d.Has(tuple.key); expected != got {
|
||||
t.Errorf("Has(%s): expected %v, got %v", tuple.key, expected, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type BrokenReader struct{}
|
||||
|
||||
func (BrokenReader) Read(p []byte) (n int, err error) {
|
||||
return 0, errors.New("failed to read")
|
||||
}
|
||||
|
||||
func TestRemovesIncompleteFiles(t *testing.T) {
|
||||
opts := Options{
|
||||
BasePath: "test-data",
|
||||
CacheSizeMax: 1024,
|
||||
}
|
||||
d := New(opts)
|
||||
defer d.EraseAll()
|
||||
|
||||
key, stream, sync := "key", BrokenReader{}, false
|
||||
|
||||
if err := d.WriteStream(key, stream, sync); err == nil {
|
||||
t.Fatalf("Expected i/o copy error, none received.")
|
||||
}
|
||||
|
||||
if _, err := d.Read(key); err == nil {
|
||||
t.Fatal("Could read the key, but it shouldn't exist")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTempDir(t *testing.T) {
|
||||
opts := Options{
|
||||
BasePath: "test-data",
|
||||
TempDir: "test-data-temp",
|
||||
CacheSizeMax: 1024,
|
||||
}
|
||||
d := New(opts)
|
||||
defer d.EraseAll()
|
||||
|
||||
k, v := "a", []byte{'b'}
|
||||
if err := d.Write(k, v); err != nil {
|
||||
t.Fatalf("write: %s", err)
|
||||
}
|
||||
if readVal, err := d.Read(k); err != nil {
|
||||
t.Fatalf("read: %s", err)
|
||||
} else if bytes.Compare(v, readVal) != 0 {
|
||||
t.Fatalf("read: expected %s, got %s", v, readVal)
|
||||
}
|
||||
if err := d.Erase(k); err != nil {
|
||||
t.Fatalf("erase: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
type CrashingReader struct{}
|
||||
|
||||
func (CrashingReader) Read(p []byte) (n int, err error) {
|
||||
panic("System has crashed while reading the stream")
|
||||
}
|
||||
|
||||
func TestAtomicWrite(t *testing.T) {
|
||||
opts := Options{
|
||||
BasePath: "test-data",
|
||||
// Test would fail if TempDir is not set here.
|
||||
TempDir: "test-data-temp",
|
||||
CacheSizeMax: 1024,
|
||||
}
|
||||
d := New(opts)
|
||||
defer d.EraseAll()
|
||||
|
||||
key := "key"
|
||||
func() {
|
||||
defer func() {
|
||||
recover() // Ignore panicking error
|
||||
}()
|
||||
|
||||
stream := CrashingReader{}
|
||||
d.WriteStream(key, stream, false)
|
||||
}()
|
||||
|
||||
if d.Has(key) {
|
||||
t.Fatal("Has key, but it shouldn't exist")
|
||||
}
|
||||
if _, ok := <-d.Keys(nil); ok {
|
||||
t.Fatal("Store isn't empty")
|
||||
}
|
||||
}
|
||||
|
|
@ -1,64 +0,0 @@
|
|||
package diskv
|
||||
|
||||
import (
|
||||
"compress/flate"
|
||||
"compress/gzip"
|
||||
"compress/zlib"
|
||||
"io"
|
||||
)
|
||||
|
||||
// Compression is an interface that Diskv uses to implement compression of
|
||||
// data. Writer takes a destination io.Writer and returns a WriteCloser that
|
||||
// compresses all data written through it. Reader takes a source io.Reader and
|
||||
// returns a ReadCloser that decompresses all data read through it. You may
|
||||
// define these methods on your own type, or use one of the NewCompression
|
||||
// helpers.
|
||||
type Compression interface {
|
||||
Writer(dst io.Writer) (io.WriteCloser, error)
|
||||
Reader(src io.Reader) (io.ReadCloser, error)
|
||||
}
|
||||
|
||||
// NewGzipCompression returns a Gzip-based Compression.
|
||||
func NewGzipCompression() Compression {
|
||||
return NewGzipCompressionLevel(flate.DefaultCompression)
|
||||
}
|
||||
|
||||
// NewGzipCompressionLevel returns a Gzip-based Compression with the given level.
|
||||
func NewGzipCompressionLevel(level int) Compression {
|
||||
return &genericCompression{
|
||||
wf: func(w io.Writer) (io.WriteCloser, error) { return gzip.NewWriterLevel(w, level) },
|
||||
rf: func(r io.Reader) (io.ReadCloser, error) { return gzip.NewReader(r) },
|
||||
}
|
||||
}
|
||||
|
||||
// NewZlibCompression returns a Zlib-based Compression.
|
||||
func NewZlibCompression() Compression {
|
||||
return NewZlibCompressionLevel(flate.DefaultCompression)
|
||||
}
|
||||
|
||||
// NewZlibCompressionLevel returns a Zlib-based Compression with the given level.
|
||||
func NewZlibCompressionLevel(level int) Compression {
|
||||
return NewZlibCompressionLevelDict(level, nil)
|
||||
}
|
||||
|
||||
// NewZlibCompressionLevelDict returns a Zlib-based Compression with the given
|
||||
// level, based on the given dictionary.
|
||||
func NewZlibCompressionLevelDict(level int, dict []byte) Compression {
|
||||
return &genericCompression{
|
||||
func(w io.Writer) (io.WriteCloser, error) { return zlib.NewWriterLevelDict(w, level, dict) },
|
||||
func(r io.Reader) (io.ReadCloser, error) { return zlib.NewReaderDict(r, dict) },
|
||||
}
|
||||
}
|
||||
|
||||
type genericCompression struct {
|
||||
wf func(w io.Writer) (io.WriteCloser, error)
|
||||
rf func(r io.Reader) (io.ReadCloser, error)
|
||||
}
|
||||
|
||||
func (g *genericCompression) Writer(dst io.Writer) (io.WriteCloser, error) {
|
||||
return g.wf(dst)
|
||||
}
|
||||
|
||||
func (g *genericCompression) Reader(src io.Reader) (io.ReadCloser, error) {
|
||||
return g.rf(src)
|
||||
}
|
||||
|
|
@ -1,72 +0,0 @@
|
|||
package diskv
|
||||
|
||||
import (
|
||||
"compress/flate"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func init() {
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
}
|
||||
|
||||
func testCompressionWith(t *testing.T, c Compression, name string) {
|
||||
d := New(Options{
|
||||
BasePath: "compression-test",
|
||||
CacheSizeMax: 0,
|
||||
Compression: c,
|
||||
})
|
||||
defer d.EraseAll()
|
||||
|
||||
sz := 4096
|
||||
val := make([]byte, sz)
|
||||
for i := 0; i < sz; i++ {
|
||||
val[i] = byte('a' + rand.Intn(26)) // {a-z}; should compress some
|
||||
}
|
||||
|
||||
key := "a"
|
||||
if err := d.Write(key, val); err != nil {
|
||||
t.Fatalf("write failed: %s", err)
|
||||
}
|
||||
|
||||
targetFile := fmt.Sprintf("%s%c%s", d.BasePath, os.PathSeparator, key)
|
||||
fi, err := os.Stat(targetFile)
|
||||
if err != nil {
|
||||
t.Fatalf("%s: %s", targetFile, err)
|
||||
}
|
||||
|
||||
if fi.Size() >= int64(sz) {
|
||||
t.Fatalf("%s: size=%d, expected smaller", targetFile, fi.Size())
|
||||
}
|
||||
t.Logf("%s compressed %d to %d", name, sz, fi.Size())
|
||||
|
||||
readVal, err := d.Read(key)
|
||||
if len(readVal) != sz {
|
||||
t.Fatalf("read: expected size=%d, got size=%d", sz, len(readVal))
|
||||
}
|
||||
|
||||
for i := 0; i < sz; i++ {
|
||||
if readVal[i] != val[i] {
|
||||
t.Fatalf("i=%d: expected %v, got %v", i, val[i], readVal[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGzipDefault(t *testing.T) {
|
||||
testCompressionWith(t, NewGzipCompression(), "gzip")
|
||||
}
|
||||
|
||||
func TestGzipBestCompression(t *testing.T) {
|
||||
testCompressionWith(t, NewGzipCompressionLevel(flate.BestCompression), "gzip-max")
|
||||
}
|
||||
|
||||
func TestGzipBestSpeed(t *testing.T) {
|
||||
testCompressionWith(t, NewGzipCompressionLevel(flate.BestSpeed), "gzip-min")
|
||||
}
|
||||
|
||||
func TestZlib(t *testing.T) {
|
||||
testCompressionWith(t, NewZlibCompression(), "zlib")
|
||||
}
|
||||
|
|
@ -1,624 +0,0 @@
|
|||
// Diskv (disk-vee) is a simple, persistent, key-value store.
|
||||
// It stores all data flatly on the filesystem.
|
||||
|
||||
package diskv
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultBasePath = "diskv"
|
||||
defaultFilePerm os.FileMode = 0666
|
||||
defaultPathPerm os.FileMode = 0777
|
||||
)
|
||||
|
||||
var (
|
||||
defaultTransform = func(s string) []string { return []string{} }
|
||||
errCanceled = errors.New("canceled")
|
||||
errEmptyKey = errors.New("empty key")
|
||||
errBadKey = errors.New("bad key")
|
||||
errImportDirectory = errors.New("can't import a directory")
|
||||
)
|
||||
|
||||
// TransformFunction transforms a key into a slice of strings, with each
|
||||
// element in the slice representing a directory in the file path where the
|
||||
// key's entry will eventually be stored.
|
||||
//
|
||||
// For example, if TransformFunc transforms "abcdef" to ["ab", "cde", "f"],
|
||||
// the final location of the data file will be <basedir>/ab/cde/f/abcdef
|
||||
type TransformFunction func(s string) []string
|
||||
|
||||
// Options define a set of properties that dictate Diskv behavior.
|
||||
// All values are optional.
|
||||
type Options struct {
|
||||
BasePath string
|
||||
Transform TransformFunction
|
||||
CacheSizeMax uint64 // bytes
|
||||
PathPerm os.FileMode
|
||||
FilePerm os.FileMode
|
||||
// If TempDir is set, it will enable filesystem atomic writes by
|
||||
// writing temporary files to that location before being moved
|
||||
// to BasePath.
|
||||
// Note that TempDir MUST be on the same device/partition as
|
||||
// BasePath.
|
||||
TempDir string
|
||||
|
||||
Index Index
|
||||
IndexLess LessFunction
|
||||
|
||||
Compression Compression
|
||||
}
|
||||
|
||||
// Diskv implements the Diskv interface. You shouldn't construct Diskv
|
||||
// structures directly; instead, use the New constructor.
|
||||
type Diskv struct {
|
||||
Options
|
||||
mu sync.RWMutex
|
||||
cache map[string][]byte
|
||||
cacheSize uint64
|
||||
}
|
||||
|
||||
// New returns an initialized Diskv structure, ready to use.
|
||||
// If the path identified by baseDir already contains data,
|
||||
// it will be accessible, but not yet cached.
|
||||
func New(o Options) *Diskv {
|
||||
if o.BasePath == "" {
|
||||
o.BasePath = defaultBasePath
|
||||
}
|
||||
if o.Transform == nil {
|
||||
o.Transform = defaultTransform
|
||||
}
|
||||
if o.PathPerm == 0 {
|
||||
o.PathPerm = defaultPathPerm
|
||||
}
|
||||
if o.FilePerm == 0 {
|
||||
o.FilePerm = defaultFilePerm
|
||||
}
|
||||
|
||||
d := &Diskv{
|
||||
Options: o,
|
||||
cache: map[string][]byte{},
|
||||
cacheSize: 0,
|
||||
}
|
||||
|
||||
if d.Index != nil && d.IndexLess != nil {
|
||||
d.Index.Initialize(d.IndexLess, d.Keys(nil))
|
||||
}
|
||||
|
||||
return d
|
||||
}
|
||||
|
||||
// Write synchronously writes the key-value pair to disk, making it immediately
|
||||
// available for reads. Write relies on the filesystem to perform an eventual
|
||||
// sync to physical media. If you need stronger guarantees, see WriteStream.
|
||||
func (d *Diskv) Write(key string, val []byte) error {
|
||||
return d.WriteStream(key, bytes.NewBuffer(val), false)
|
||||
}
|
||||
|
||||
// WriteStream writes the data represented by the io.Reader to the disk, under
|
||||
// the provided key. If sync is true, WriteStream performs an explicit sync on
|
||||
// the file as soon as it's written.
|
||||
//
|
||||
// bytes.Buffer provides io.Reader semantics for basic data types.
|
||||
func (d *Diskv) WriteStream(key string, r io.Reader, sync bool) error {
|
||||
if len(key) <= 0 {
|
||||
return errEmptyKey
|
||||
}
|
||||
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
|
||||
return d.writeStreamWithLock(key, r, sync)
|
||||
}
|
||||
|
||||
// createKeyFileWithLock either creates the key file directly, or
|
||||
// creates a temporary file in TempDir if it is set.
|
||||
func (d *Diskv) createKeyFileWithLock(key string) (*os.File, error) {
|
||||
if d.TempDir != "" {
|
||||
if err := os.MkdirAll(d.TempDir, d.PathPerm); err != nil {
|
||||
return nil, fmt.Errorf("temp mkdir: %s", err)
|
||||
}
|
||||
f, err := ioutil.TempFile(d.TempDir, "")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("temp file: %s", err)
|
||||
}
|
||||
|
||||
if err := f.Chmod(d.FilePerm); err != nil {
|
||||
f.Close() // error deliberately ignored
|
||||
os.Remove(f.Name()) // error deliberately ignored
|
||||
return nil, fmt.Errorf("chmod: %s", err)
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
|
||||
mode := os.O_WRONLY | os.O_CREATE | os.O_TRUNC // overwrite if exists
|
||||
f, err := os.OpenFile(d.completeFilename(key), mode, d.FilePerm)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open file: %s", err)
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
|
||||
// writeStream does no input validation checking.
|
||||
func (d *Diskv) writeStreamWithLock(key string, r io.Reader, sync bool) error {
|
||||
if err := d.ensurePathWithLock(key); err != nil {
|
||||
return fmt.Errorf("ensure path: %s", err)
|
||||
}
|
||||
|
||||
f, err := d.createKeyFileWithLock(key)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create key file: %s", err)
|
||||
}
|
||||
|
||||
wc := io.WriteCloser(&nopWriteCloser{f})
|
||||
if d.Compression != nil {
|
||||
wc, err = d.Compression.Writer(f)
|
||||
if err != nil {
|
||||
f.Close() // error deliberately ignored
|
||||
os.Remove(f.Name()) // error deliberately ignored
|
||||
return fmt.Errorf("compression writer: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
if _, err := io.Copy(wc, r); err != nil {
|
||||
f.Close() // error deliberately ignored
|
||||
os.Remove(f.Name()) // error deliberately ignored
|
||||
return fmt.Errorf("i/o copy: %s", err)
|
||||
}
|
||||
|
||||
if err := wc.Close(); err != nil {
|
||||
f.Close() // error deliberately ignored
|
||||
os.Remove(f.Name()) // error deliberately ignored
|
||||
return fmt.Errorf("compression close: %s", err)
|
||||
}
|
||||
|
||||
if sync {
|
||||
if err := f.Sync(); err != nil {
|
||||
f.Close() // error deliberately ignored
|
||||
os.Remove(f.Name()) // error deliberately ignored
|
||||
return fmt.Errorf("file sync: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := f.Close(); err != nil {
|
||||
return fmt.Errorf("file close: %s", err)
|
||||
}
|
||||
|
||||
if f.Name() != d.completeFilename(key) {
|
||||
if err := os.Rename(f.Name(), d.completeFilename(key)); err != nil {
|
||||
os.Remove(f.Name()) // error deliberately ignored
|
||||
return fmt.Errorf("rename: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
if d.Index != nil {
|
||||
d.Index.Insert(key)
|
||||
}
|
||||
|
||||
d.bustCacheWithLock(key) // cache only on read
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Import imports the source file into diskv under the destination key. If the
|
||||
// destination key already exists, it's overwritten. If move is true, the
|
||||
// source file is removed after a successful import.
|
||||
func (d *Diskv) Import(srcFilename, dstKey string, move bool) (err error) {
|
||||
if dstKey == "" {
|
||||
return errEmptyKey
|
||||
}
|
||||
|
||||
if fi, err := os.Stat(srcFilename); err != nil {
|
||||
return err
|
||||
} else if fi.IsDir() {
|
||||
return errImportDirectory
|
||||
}
|
||||
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
|
||||
if err := d.ensurePathWithLock(dstKey); err != nil {
|
||||
return fmt.Errorf("ensure path: %s", err)
|
||||
}
|
||||
|
||||
if move {
|
||||
if err := syscall.Rename(srcFilename, d.completeFilename(dstKey)); err == nil {
|
||||
d.bustCacheWithLock(dstKey)
|
||||
return nil
|
||||
} else if err != syscall.EXDEV {
|
||||
// If it failed due to being on a different device, fall back to copying
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
f, err := os.Open(srcFilename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
err = d.writeStreamWithLock(dstKey, f, false)
|
||||
if err == nil && move {
|
||||
err = os.Remove(srcFilename)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// Read reads the key and returns the value.
|
||||
// If the key is available in the cache, Read won't touch the disk.
|
||||
// If the key is not in the cache, Read will have the side-effect of
|
||||
// lazily caching the value.
|
||||
func (d *Diskv) Read(key string) ([]byte, error) {
|
||||
rc, err := d.ReadStream(key, false)
|
||||
if err != nil {
|
||||
return []byte{}, err
|
||||
}
|
||||
defer rc.Close()
|
||||
return ioutil.ReadAll(rc)
|
||||
}
|
||||
|
||||
// ReadStream reads the key and returns the value (data) as an io.ReadCloser.
|
||||
// If the value is cached from a previous read, and direct is false,
|
||||
// ReadStream will use the cached value. Otherwise, it will return a handle to
|
||||
// the file on disk, and cache the data on read.
|
||||
//
|
||||
// If direct is true, ReadStream will lazily delete any cached value for the
|
||||
// key, and return a direct handle to the file on disk.
|
||||
//
|
||||
// If compression is enabled, ReadStream taps into the io.Reader stream prior
|
||||
// to decompression, and caches the compressed data.
|
||||
func (d *Diskv) ReadStream(key string, direct bool) (io.ReadCloser, error) {
|
||||
d.mu.RLock()
|
||||
defer d.mu.RUnlock()
|
||||
|
||||
if val, ok := d.cache[key]; ok {
|
||||
if !direct {
|
||||
buf := bytes.NewBuffer(val)
|
||||
if d.Compression != nil {
|
||||
return d.Compression.Reader(buf)
|
||||
}
|
||||
return ioutil.NopCloser(buf), nil
|
||||
}
|
||||
|
||||
go func() {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
d.uncacheWithLock(key, uint64(len(val)))
|
||||
}()
|
||||
}
|
||||
|
||||
return d.readWithRLock(key)
|
||||
}
|
||||
|
||||
// read ignores the cache, and returns an io.ReadCloser representing the
|
||||
// decompressed data for the given key, streamed from the disk. Clients should
|
||||
// acquire a read lock on the Diskv and check the cache themselves before
|
||||
// calling read.
|
||||
func (d *Diskv) readWithRLock(key string) (io.ReadCloser, error) {
|
||||
filename := d.completeFilename(key)
|
||||
|
||||
fi, err := os.Stat(filename)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if fi.IsDir() {
|
||||
return nil, os.ErrNotExist
|
||||
}
|
||||
|
||||
f, err := os.Open(filename)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var r io.Reader
|
||||
if d.CacheSizeMax > 0 {
|
||||
r = newSiphon(f, d, key)
|
||||
} else {
|
||||
r = &closingReader{f}
|
||||
}
|
||||
|
||||
var rc = io.ReadCloser(ioutil.NopCloser(r))
|
||||
if d.Compression != nil {
|
||||
rc, err = d.Compression.Reader(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return rc, nil
|
||||
}
|
||||
|
||||
// closingReader provides a Reader that automatically closes the
|
||||
// embedded ReadCloser when it reaches EOF
|
||||
type closingReader struct {
|
||||
rc io.ReadCloser
|
||||
}
|
||||
|
||||
func (cr closingReader) Read(p []byte) (int, error) {
|
||||
n, err := cr.rc.Read(p)
|
||||
if err == io.EOF {
|
||||
if closeErr := cr.rc.Close(); closeErr != nil {
|
||||
return n, closeErr // close must succeed for Read to succeed
|
||||
}
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
// siphon is like a TeeReader: it copies all data read through it to an
|
||||
// internal buffer, and moves that buffer to the cache at EOF.
|
||||
type siphon struct {
|
||||
f *os.File
|
||||
d *Diskv
|
||||
key string
|
||||
buf *bytes.Buffer
|
||||
}
|
||||
|
||||
// newSiphon constructs a siphoning reader that represents the passed file.
|
||||
// When a successful series of reads ends in an EOF, the siphon will write
|
||||
// the buffered data to Diskv's cache under the given key.
|
||||
func newSiphon(f *os.File, d *Diskv, key string) io.Reader {
|
||||
return &siphon{
|
||||
f: f,
|
||||
d: d,
|
||||
key: key,
|
||||
buf: &bytes.Buffer{},
|
||||
}
|
||||
}
|
||||
|
||||
// Read implements the io.Reader interface for siphon.
|
||||
func (s *siphon) Read(p []byte) (int, error) {
|
||||
n, err := s.f.Read(p)
|
||||
|
||||
if err == nil {
|
||||
return s.buf.Write(p[0:n]) // Write must succeed for Read to succeed
|
||||
}
|
||||
|
||||
if err == io.EOF {
|
||||
s.d.cacheWithoutLock(s.key, s.buf.Bytes()) // cache may fail
|
||||
if closeErr := s.f.Close(); closeErr != nil {
|
||||
return n, closeErr // close must succeed for Read to succeed
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
return n, err
|
||||
}
|
||||
|
||||
// Erase synchronously erases the given key from the disk and the cache.
|
||||
func (d *Diskv) Erase(key string) error {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
|
||||
d.bustCacheWithLock(key)
|
||||
|
||||
// erase from index
|
||||
if d.Index != nil {
|
||||
d.Index.Delete(key)
|
||||
}
|
||||
|
||||
// erase from disk
|
||||
filename := d.completeFilename(key)
|
||||
if s, err := os.Stat(filename); err == nil {
|
||||
if s.IsDir() {
|
||||
return errBadKey
|
||||
}
|
||||
if err = os.Remove(filename); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
// Return err as-is so caller can do os.IsNotExist(err).
|
||||
return err
|
||||
}
|
||||
|
||||
// clean up and return
|
||||
d.pruneDirsWithLock(key)
|
||||
return nil
|
||||
}
|
||||
|
||||
// EraseAll will delete all of the data from the store, both in the cache and on
|
||||
// the disk. Note that EraseAll doesn't distinguish diskv-related data from non-
|
||||
// diskv-related data. Care should be taken to always specify a diskv base
|
||||
// directory that is exclusively for diskv data.
|
||||
func (d *Diskv) EraseAll() error {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
d.cache = make(map[string][]byte)
|
||||
d.cacheSize = 0
|
||||
if d.TempDir != "" {
|
||||
os.RemoveAll(d.TempDir) // errors ignored
|
||||
}
|
||||
return os.RemoveAll(d.BasePath)
|
||||
}
|
||||
|
||||
// Has returns true if the given key exists.
|
||||
func (d *Diskv) Has(key string) bool {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
|
||||
if _, ok := d.cache[key]; ok {
|
||||
return true
|
||||
}
|
||||
|
||||
filename := d.completeFilename(key)
|
||||
s, err := os.Stat(filename)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if s.IsDir() {
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// Keys returns a channel that will yield every key accessible by the store,
|
||||
// in undefined order. If a cancel channel is provided, closing it will
|
||||
// terminate and close the keys channel.
|
||||
func (d *Diskv) Keys(cancel <-chan struct{}) <-chan string {
|
||||
return d.KeysPrefix("", cancel)
|
||||
}
|
||||
|
||||
// KeysPrefix returns a channel that will yield every key accessible by the
|
||||
// store with the given prefix, in undefined order. If a cancel channel is
|
||||
// provided, closing it will terminate and close the keys channel. If the
|
||||
// provided prefix is the empty string, all keys will be yielded.
|
||||
func (d *Diskv) KeysPrefix(prefix string, cancel <-chan struct{}) <-chan string {
|
||||
var prepath string
|
||||
if prefix == "" {
|
||||
prepath = d.BasePath
|
||||
} else {
|
||||
prepath = d.pathFor(prefix)
|
||||
}
|
||||
c := make(chan string)
|
||||
go func() {
|
||||
filepath.Walk(prepath, walker(c, prefix, cancel))
|
||||
close(c)
|
||||
}()
|
||||
return c
|
||||
}
|
||||
|
||||
// walker returns a function which satisfies the filepath.WalkFunc interface.
|
||||
// It sends every non-directory file entry down the channel c.
|
||||
func walker(c chan<- string, prefix string, cancel <-chan struct{}) filepath.WalkFunc {
|
||||
return func(path string, info os.FileInfo, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if info.IsDir() || !strings.HasPrefix(info.Name(), prefix) {
|
||||
return nil // "pass"
|
||||
}
|
||||
|
||||
select {
|
||||
case c <- info.Name():
|
||||
case <-cancel:
|
||||
return errCanceled
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// pathFor returns the absolute path for location on the filesystem where the
|
||||
// data for the given key will be stored.
|
||||
func (d *Diskv) pathFor(key string) string {
|
||||
return filepath.Join(d.BasePath, filepath.Join(d.Transform(key)...))
|
||||
}
|
||||
|
||||
// ensurePathWithLock is a helper function that generates all necessary
|
||||
// directories on the filesystem for the given key.
|
||||
func (d *Diskv) ensurePathWithLock(key string) error {
|
||||
return os.MkdirAll(d.pathFor(key), d.PathPerm)
|
||||
}
|
||||
|
||||
// completeFilename returns the absolute path to the file for the given key.
|
||||
func (d *Diskv) completeFilename(key string) string {
|
||||
return filepath.Join(d.pathFor(key), key)
|
||||
}
|
||||
|
||||
// cacheWithLock attempts to cache the given key-value pair in the store's
|
||||
// cache. It can fail if the value is larger than the cache's maximum size.
|
||||
func (d *Diskv) cacheWithLock(key string, val []byte) error {
|
||||
valueSize := uint64(len(val))
|
||||
if err := d.ensureCacheSpaceWithLock(valueSize); err != nil {
|
||||
return fmt.Errorf("%s; not caching", err)
|
||||
}
|
||||
|
||||
// be very strict about memory guarantees
|
||||
if (d.cacheSize + valueSize) > d.CacheSizeMax {
|
||||
panic(fmt.Sprintf("failed to make room for value (%d/%d)", valueSize, d.CacheSizeMax))
|
||||
}
|
||||
|
||||
d.cache[key] = val
|
||||
d.cacheSize += valueSize
|
||||
return nil
|
||||
}
|
||||
|
||||
// cacheWithoutLock acquires the store's (write) mutex and calls cacheWithLock.
|
||||
func (d *Diskv) cacheWithoutLock(key string, val []byte) error {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
return d.cacheWithLock(key, val)
|
||||
}
|
||||
|
||||
func (d *Diskv) bustCacheWithLock(key string) {
|
||||
if val, ok := d.cache[key]; ok {
|
||||
d.uncacheWithLock(key, uint64(len(val)))
|
||||
}
|
||||
}
|
||||
|
||||
func (d *Diskv) uncacheWithLock(key string, sz uint64) {
|
||||
d.cacheSize -= sz
|
||||
delete(d.cache, key)
|
||||
}
|
||||
|
||||
// pruneDirsWithLock deletes empty directories in the path walk leading to the
|
||||
// key k. Typically this function is called after an Erase is made.
|
||||
func (d *Diskv) pruneDirsWithLock(key string) error {
|
||||
pathlist := d.Transform(key)
|
||||
for i := range pathlist {
|
||||
dir := filepath.Join(d.BasePath, filepath.Join(pathlist[:len(pathlist)-i]...))
|
||||
|
||||
// thanks to Steven Blenkinsop for this snippet
|
||||
switch fi, err := os.Stat(dir); true {
|
||||
case err != nil:
|
||||
return err
|
||||
case !fi.IsDir():
|
||||
panic(fmt.Sprintf("corrupt dirstate at %s", dir))
|
||||
}
|
||||
|
||||
nlinks, err := filepath.Glob(filepath.Join(dir, "*"))
|
||||
if err != nil {
|
||||
return err
|
||||
} else if len(nlinks) > 0 {
|
||||
return nil // has subdirs -- do not prune
|
||||
}
|
||||
if err = os.Remove(dir); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ensureCacheSpaceWithLock deletes entries from the cache in arbitrary order
|
||||
// until the cache has at least valueSize bytes available.
|
||||
func (d *Diskv) ensureCacheSpaceWithLock(valueSize uint64) error {
|
||||
if valueSize > d.CacheSizeMax {
|
||||
return fmt.Errorf("value size (%d bytes) too large for cache (%d bytes)", valueSize, d.CacheSizeMax)
|
||||
}
|
||||
|
||||
safe := func() bool { return (d.cacheSize + valueSize) <= d.CacheSizeMax }
|
||||
|
||||
for key, val := range d.cache {
|
||||
if safe() {
|
||||
break
|
||||
}
|
||||
|
||||
d.uncacheWithLock(key, uint64(len(val)))
|
||||
}
|
||||
|
||||
if !safe() {
|
||||
panic(fmt.Sprintf("%d bytes still won't fit in the cache! (max %d bytes)", valueSize, d.CacheSizeMax))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// nopWriteCloser wraps an io.Writer and provides a no-op Close method to
|
||||
// satisfy the io.WriteCloser interface.
|
||||
type nopWriteCloser struct {
|
||||
io.Writer
|
||||
}
|
||||
|
||||
func (wc *nopWriteCloser) Write(p []byte) (int, error) { return wc.Writer.Write(p) }
|
||||
func (wc *nopWriteCloser) Close() error { return nil }
|
||||
63
vendor/github.com/peterbourgon/diskv/examples/content-addressable-store/cas.go
generated
vendored
63
vendor/github.com/peterbourgon/diskv/examples/content-addressable-store/cas.go
generated
vendored
|
|
@ -1,63 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"github.com/peterbourgon/diskv"
|
||||
)
|
||||
|
||||
const transformBlockSize = 2 // grouping of chars per directory depth
|
||||
|
||||
func blockTransform(s string) []string {
|
||||
var (
|
||||
sliceSize = len(s) / transformBlockSize
|
||||
pathSlice = make([]string, sliceSize)
|
||||
)
|
||||
for i := 0; i < sliceSize; i++ {
|
||||
from, to := i*transformBlockSize, (i*transformBlockSize)+transformBlockSize
|
||||
pathSlice[i] = s[from:to]
|
||||
}
|
||||
return pathSlice
|
||||
}
|
||||
|
||||
func main() {
|
||||
d := diskv.New(diskv.Options{
|
||||
BasePath: "data",
|
||||
Transform: blockTransform,
|
||||
CacheSizeMax: 1024 * 1024, // 1MB
|
||||
})
|
||||
|
||||
for _, valueStr := range []string{
|
||||
"I am the very model of a modern Major-General",
|
||||
"I've information vegetable, animal, and mineral",
|
||||
"I know the kings of England, and I quote the fights historical",
|
||||
"From Marathon to Waterloo, in order categorical",
|
||||
"I'm very well acquainted, too, with matters mathematical",
|
||||
"I understand equations, both the simple and quadratical",
|
||||
"About binomial theorem I'm teeming with a lot o' news",
|
||||
"With many cheerful facts about the square of the hypotenuse",
|
||||
} {
|
||||
d.Write(md5sum(valueStr), []byte(valueStr))
|
||||
}
|
||||
|
||||
var keyCount int
|
||||
for key := range d.Keys(nil) {
|
||||
val, err := d.Read(key)
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("key %s had no value", key))
|
||||
}
|
||||
fmt.Printf("%s: %s\n", key, val)
|
||||
keyCount++
|
||||
}
|
||||
fmt.Printf("%d total keys\n", keyCount)
|
||||
|
||||
// d.EraseAll() // leave it commented out to see how data is kept on disk
|
||||
}
|
||||
|
||||
func md5sum(s string) string {
|
||||
h := md5.New()
|
||||
io.WriteString(h, s)
|
||||
return fmt.Sprintf("%x", h.Sum(nil))
|
||||
}
|
||||
30
vendor/github.com/peterbourgon/diskv/examples/super-simple-store/super-simple-store.go
generated
vendored
30
vendor/github.com/peterbourgon/diskv/examples/super-simple-store/super-simple-store.go
generated
vendored
|
|
@ -1,30 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/peterbourgon/diskv"
|
||||
)
|
||||
|
||||
func main() {
|
||||
d := diskv.New(diskv.Options{
|
||||
BasePath: "my-diskv-data-directory",
|
||||
Transform: func(s string) []string { return []string{} },
|
||||
CacheSizeMax: 1024 * 1024, // 1MB
|
||||
})
|
||||
|
||||
key := "alpha"
|
||||
if err := d.Write(key, []byte{'1', '2', '3'}); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
value, err := d.Read(key)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
fmt.Printf("%v\n", value)
|
||||
|
||||
if err := d.Erase(key); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
|
@ -1,76 +0,0 @@
|
|||
package diskv_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
|
||||
"github.com/peterbourgon/diskv"
|
||||
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestImportMove(t *testing.T) {
|
||||
b := []byte(`0123456789`)
|
||||
f, err := ioutil.TempFile("", "temp-test")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := f.Write(b); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.Close()
|
||||
|
||||
d := diskv.New(diskv.Options{
|
||||
BasePath: "test-import-move",
|
||||
})
|
||||
defer d.EraseAll()
|
||||
|
||||
key := "key"
|
||||
|
||||
if err := d.Write(key, []byte(`TBD`)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := d.Import(f.Name(), key, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if _, err := os.Stat(f.Name()); err == nil || !os.IsNotExist(err) {
|
||||
t.Errorf("expected temp file to be gone, but err = %v", err)
|
||||
}
|
||||
|
||||
if !d.Has(key) {
|
||||
t.Errorf("%q not present", key)
|
||||
}
|
||||
|
||||
if buf, err := d.Read(key); err != nil || bytes.Compare(b, buf) != 0 {
|
||||
t.Errorf("want %q, have %q (err = %v)", string(b), string(buf), err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestImportCopy(t *testing.T) {
|
||||
b := []byte(`¡åéîòü!`)
|
||||
|
||||
f, err := ioutil.TempFile("", "temp-test")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := f.Write(b); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.Close()
|
||||
|
||||
d := diskv.New(diskv.Options{
|
||||
BasePath: "test-import-copy",
|
||||
})
|
||||
defer d.EraseAll()
|
||||
|
||||
if err := d.Import(f.Name(), "key", false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if _, err := os.Stat(f.Name()); err != nil {
|
||||
t.Errorf("expected temp file to remain, but got err = %v", err)
|
||||
}
|
||||
}
|
||||
|
|
@ -1,115 +0,0 @@
|
|||
package diskv
|
||||
|
||||
import (
|
||||
"sync"
|
||||
|
||||
"github.com/google/btree"
|
||||
)
|
||||
|
||||
// Index is a generic interface for things that can
|
||||
// provide an ordered list of keys.
|
||||
type Index interface {
|
||||
Initialize(less LessFunction, keys <-chan string)
|
||||
Insert(key string)
|
||||
Delete(key string)
|
||||
Keys(from string, n int) []string
|
||||
}
|
||||
|
||||
// LessFunction is used to initialize an Index of keys in a specific order.
|
||||
type LessFunction func(string, string) bool
|
||||
|
||||
// btreeString is a custom data type that satisfies the BTree Less interface,
|
||||
// making the strings it wraps sortable by the BTree package.
|
||||
type btreeString struct {
|
||||
s string
|
||||
l LessFunction
|
||||
}
|
||||
|
||||
// Less satisfies the BTree.Less interface using the btreeString's LessFunction.
|
||||
func (s btreeString) Less(i btree.Item) bool {
|
||||
return s.l(s.s, i.(btreeString).s)
|
||||
}
|
||||
|
||||
// BTreeIndex is an implementation of the Index interface using google/btree.
|
||||
type BTreeIndex struct {
|
||||
sync.RWMutex
|
||||
LessFunction
|
||||
*btree.BTree
|
||||
}
|
||||
|
||||
// Initialize populates the BTree tree with data from the keys channel,
|
||||
// according to the passed less function. It's destructive to the BTreeIndex.
|
||||
func (i *BTreeIndex) Initialize(less LessFunction, keys <-chan string) {
|
||||
i.Lock()
|
||||
defer i.Unlock()
|
||||
i.LessFunction = less
|
||||
i.BTree = rebuild(less, keys)
|
||||
}
|
||||
|
||||
// Insert inserts the given key (only) into the BTree tree.
|
||||
func (i *BTreeIndex) Insert(key string) {
|
||||
i.Lock()
|
||||
defer i.Unlock()
|
||||
if i.BTree == nil || i.LessFunction == nil {
|
||||
panic("uninitialized index")
|
||||
}
|
||||
i.BTree.ReplaceOrInsert(btreeString{s: key, l: i.LessFunction})
|
||||
}
|
||||
|
||||
// Delete removes the given key (only) from the BTree tree.
|
||||
func (i *BTreeIndex) Delete(key string) {
|
||||
i.Lock()
|
||||
defer i.Unlock()
|
||||
if i.BTree == nil || i.LessFunction == nil {
|
||||
panic("uninitialized index")
|
||||
}
|
||||
i.BTree.Delete(btreeString{s: key, l: i.LessFunction})
|
||||
}
|
||||
|
||||
// Keys yields a maximum of n keys in order. If the passed 'from' key is empty,
|
||||
// Keys will return the first n keys. If the passed 'from' key is non-empty, the
|
||||
// first key in the returned slice will be the key that immediately follows the
|
||||
// passed key, in key order.
|
||||
func (i *BTreeIndex) Keys(from string, n int) []string {
|
||||
i.RLock()
|
||||
defer i.RUnlock()
|
||||
|
||||
if i.BTree == nil || i.LessFunction == nil {
|
||||
panic("uninitialized index")
|
||||
}
|
||||
|
||||
if i.BTree.Len() <= 0 {
|
||||
return []string{}
|
||||
}
|
||||
|
||||
btreeFrom := btreeString{s: from, l: i.LessFunction}
|
||||
skipFirst := true
|
||||
if len(from) <= 0 || !i.BTree.Has(btreeFrom) {
|
||||
// no such key, so fabricate an always-smallest item
|
||||
btreeFrom = btreeString{s: "", l: func(string, string) bool { return true }}
|
||||
skipFirst = false
|
||||
}
|
||||
|
||||
keys := []string{}
|
||||
iterator := func(i btree.Item) bool {
|
||||
keys = append(keys, i.(btreeString).s)
|
||||
return len(keys) < n
|
||||
}
|
||||
i.BTree.AscendGreaterOrEqual(btreeFrom, iterator)
|
||||
|
||||
if skipFirst && len(keys) > 0 {
|
||||
keys = keys[1:]
|
||||
}
|
||||
|
||||
return keys
|
||||
}
|
||||
|
||||
// rebuildIndex does the work of regenerating the index
|
||||
// with the given keys.
|
||||
func rebuild(less LessFunction, keys <-chan string) *btree.BTree {
|
||||
tree := btree.New(2)
|
||||
for key := range keys {
|
||||
tree.ReplaceOrInsert(btreeString{s: key, l: less})
|
||||
}
|
||||
return tree
|
||||
}
|
||||
|
|
@ -1,148 +0,0 @@
|
|||
package diskv
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func strLess(a, b string) bool { return a < b }
|
||||
|
||||
func cmpStrings(a, b []string) bool {
|
||||
if len(a) != len(b) {
|
||||
return false
|
||||
}
|
||||
for i := 0; i < len(a); i++ {
|
||||
if a[i] != b[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (d *Diskv) isIndexed(key string) bool {
|
||||
if d.Index == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
for _, got := range d.Index.Keys("", 1000) {
|
||||
if got == key {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func TestIndexOrder(t *testing.T) {
|
||||
d := New(Options{
|
||||
BasePath: "index-test",
|
||||
Transform: func(string) []string { return []string{} },
|
||||
CacheSizeMax: 1024,
|
||||
Index: &BTreeIndex{},
|
||||
IndexLess: strLess,
|
||||
})
|
||||
defer d.EraseAll()
|
||||
|
||||
v := []byte{'1', '2', '3'}
|
||||
d.Write("a", v)
|
||||
if !d.isIndexed("a") {
|
||||
t.Fatalf("'a' not indexed after write")
|
||||
}
|
||||
d.Write("1", v)
|
||||
d.Write("m", v)
|
||||
d.Write("-", v)
|
||||
d.Write("A", v)
|
||||
|
||||
expectedKeys := []string{"-", "1", "A", "a", "m"}
|
||||
keys := []string{}
|
||||
for _, key := range d.Index.Keys("", 100) {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
|
||||
if !cmpStrings(keys, expectedKeys) {
|
||||
t.Fatalf("got %s, expected %s", keys, expectedKeys)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIndexLoad(t *testing.T) {
|
||||
d1 := New(Options{
|
||||
BasePath: "index-test",
|
||||
Transform: func(string) []string { return []string{} },
|
||||
CacheSizeMax: 1024,
|
||||
})
|
||||
defer d1.EraseAll()
|
||||
|
||||
val := []byte{'1', '2', '3'}
|
||||
keys := []string{"a", "b", "c", "d", "e", "f", "g"}
|
||||
for _, key := range keys {
|
||||
d1.Write(key, val)
|
||||
}
|
||||
|
||||
d2 := New(Options{
|
||||
BasePath: "index-test",
|
||||
Transform: func(string) []string { return []string{} },
|
||||
CacheSizeMax: 1024,
|
||||
Index: &BTreeIndex{},
|
||||
IndexLess: strLess,
|
||||
})
|
||||
defer d2.EraseAll()
|
||||
|
||||
// check d2 has properly loaded existing d1 data
|
||||
for _, key := range keys {
|
||||
if !d2.isIndexed(key) {
|
||||
t.Fatalf("key '%s' not indexed on secondary", key)
|
||||
}
|
||||
}
|
||||
|
||||
// cache one
|
||||
if readValue, err := d2.Read(keys[0]); err != nil {
|
||||
t.Fatalf("%s", err)
|
||||
} else if bytes.Compare(val, readValue) != 0 {
|
||||
t.Fatalf("%s: got %s, expected %s", keys[0], readValue, val)
|
||||
}
|
||||
|
||||
// make sure it got cached
|
||||
for i := 0; i < 10 && !d2.isCached(keys[0]); i++ {
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
if !d2.isCached(keys[0]) {
|
||||
t.Fatalf("key '%s' not cached", keys[0])
|
||||
}
|
||||
|
||||
// kill the disk
|
||||
d1.EraseAll()
|
||||
|
||||
// cached value should still be there in the second
|
||||
if readValue, err := d2.Read(keys[0]); err != nil {
|
||||
t.Fatalf("%s", err)
|
||||
} else if bytes.Compare(val, readValue) != 0 {
|
||||
t.Fatalf("%s: got %s, expected %s", keys[0], readValue, val)
|
||||
}
|
||||
|
||||
// but not in the original
|
||||
if _, err := d1.Read(keys[0]); err == nil {
|
||||
t.Fatalf("expected error reading from flushed store")
|
||||
}
|
||||
}
|
||||
|
||||
func TestIndexKeysEmptyFrom(t *testing.T) {
|
||||
d := New(Options{
|
||||
BasePath: "index-test",
|
||||
Transform: func(string) []string { return []string{} },
|
||||
CacheSizeMax: 1024,
|
||||
Index: &BTreeIndex{},
|
||||
IndexLess: strLess,
|
||||
})
|
||||
defer d.EraseAll()
|
||||
|
||||
for _, k := range []string{"a", "c", "z", "b", "x", "b", "y"} {
|
||||
d.Write(k, []byte("1"))
|
||||
}
|
||||
|
||||
want := []string{"a", "b", "c", "x", "y", "z"}
|
||||
have := d.Index.Keys("", 99)
|
||||
if !reflect.DeepEqual(want, have) {
|
||||
t.Errorf("want %v, have %v", want, have)
|
||||
}
|
||||
}
|
||||
|
|
@ -1,121 +0,0 @@
|
|||
package diskv
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io/ioutil"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ReadStream from cache shouldn't panic on a nil dereference from a nonexistent
|
||||
// Compression :)
|
||||
func TestIssue2A(t *testing.T) {
|
||||
d := New(Options{
|
||||
BasePath: "test-issue-2a",
|
||||
Transform: func(string) []string { return []string{} },
|
||||
CacheSizeMax: 1024,
|
||||
})
|
||||
defer d.EraseAll()
|
||||
|
||||
input := "abcdefghijklmnopqrstuvwxy"
|
||||
key, writeBuf, sync := "a", bytes.NewBufferString(input), false
|
||||
if err := d.WriteStream(key, writeBuf, sync); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
for i := 0; i < 2; i++ {
|
||||
began := time.Now()
|
||||
rc, err := d.ReadStream(key, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
buf, err := ioutil.ReadAll(rc)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !cmpBytes(buf, []byte(input)) {
|
||||
t.Fatalf("read #%d: '%s' != '%s'", i+1, string(buf), input)
|
||||
}
|
||||
rc.Close()
|
||||
t.Logf("read #%d in %s", i+1, time.Since(began))
|
||||
}
|
||||
}
|
||||
|
||||
// ReadStream on a key that resolves to a directory should return an error.
|
||||
func TestIssue2B(t *testing.T) {
|
||||
blockTransform := func(s string) []string {
|
||||
transformBlockSize := 3
|
||||
sliceSize := len(s) / transformBlockSize
|
||||
pathSlice := make([]string, sliceSize)
|
||||
for i := 0; i < sliceSize; i++ {
|
||||
from, to := i*transformBlockSize, (i*transformBlockSize)+transformBlockSize
|
||||
pathSlice[i] = s[from:to]
|
||||
}
|
||||
return pathSlice
|
||||
}
|
||||
|
||||
d := New(Options{
|
||||
BasePath: "test-issue-2b",
|
||||
Transform: blockTransform,
|
||||
CacheSizeMax: 0,
|
||||
})
|
||||
defer d.EraseAll()
|
||||
|
||||
v := []byte{'1', '2', '3'}
|
||||
if err := d.Write("abcabc", v); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
_, err := d.ReadStream("abc", false)
|
||||
if err == nil {
|
||||
t.Fatal("ReadStream('abc') should return error")
|
||||
}
|
||||
t.Logf("ReadStream('abc') returned error: %v", err)
|
||||
}
|
||||
|
||||
// Ensure ReadStream with direct=true isn't racy.
|
||||
func TestIssue17(t *testing.T) {
|
||||
var (
|
||||
basePath = "test-data"
|
||||
)
|
||||
|
||||
dWrite := New(Options{
|
||||
BasePath: basePath,
|
||||
CacheSizeMax: 0,
|
||||
})
|
||||
defer dWrite.EraseAll()
|
||||
|
||||
dRead := New(Options{
|
||||
BasePath: basePath,
|
||||
CacheSizeMax: 50,
|
||||
})
|
||||
|
||||
cases := map[string]string{
|
||||
"a": `1234567890`,
|
||||
"b": `2345678901`,
|
||||
"c": `3456789012`,
|
||||
"d": `4567890123`,
|
||||
"e": `5678901234`,
|
||||
}
|
||||
|
||||
for k, v := range cases {
|
||||
if err := dWrite.Write(k, []byte(v)); err != nil {
|
||||
t.Fatalf("during write: %s", err)
|
||||
}
|
||||
dRead.Read(k) // ensure it's added to cache
|
||||
}
|
||||
|
||||
var wg sync.WaitGroup
|
||||
start := make(chan struct{})
|
||||
for k, v := range cases {
|
||||
wg.Add(1)
|
||||
go func(k, v string) {
|
||||
<-start
|
||||
dRead.ReadStream(k, true)
|
||||
wg.Done()
|
||||
}(k, v)
|
||||
}
|
||||
close(start)
|
||||
wg.Wait()
|
||||
}
|
||||
|
|
@ -1,231 +0,0 @@
|
|||
package diskv_test
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/peterbourgon/diskv"
|
||||
)
|
||||
|
||||
var (
|
||||
keysTestData = map[string]string{
|
||||
"ab01cd01": "When we started building CoreOS",
|
||||
"ab01cd02": "we looked at all the various components available to us",
|
||||
"ab01cd03": "re-using the best tools",
|
||||
"ef01gh04": "and building the ones that did not exist",
|
||||
"ef02gh05": "We believe strongly in the Unix philosophy",
|
||||
"xxxxxxxx": "tools should be independently useful",
|
||||
}
|
||||
|
||||
prefixes = []string{
|
||||
"", // all
|
||||
"a",
|
||||
"ab",
|
||||
"ab0",
|
||||
"ab01",
|
||||
"ab01cd0",
|
||||
"ab01cd01",
|
||||
"ab01cd01x", // none
|
||||
"b", // none
|
||||
"b0", // none
|
||||
"0", // none
|
||||
"01", // none
|
||||
"e",
|
||||
"ef",
|
||||
"efx", // none
|
||||
"ef01gh0",
|
||||
"ef01gh04",
|
||||
"ef01gh05",
|
||||
"ef01gh06", // none
|
||||
}
|
||||
)
|
||||
|
||||
func TestKeysFlat(t *testing.T) {
|
||||
transform := func(s string) []string {
|
||||
if s == "" {
|
||||
t.Fatalf(`transform should not be called with ""`)
|
||||
}
|
||||
return []string{}
|
||||
}
|
||||
d := diskv.New(diskv.Options{
|
||||
BasePath: "test-data",
|
||||
Transform: transform,
|
||||
})
|
||||
defer d.EraseAll()
|
||||
|
||||
for k, v := range keysTestData {
|
||||
d.Write(k, []byte(v))
|
||||
}
|
||||
|
||||
checkKeys(t, d.Keys(nil), keysTestData)
|
||||
}
|
||||
|
||||
func TestKeysNested(t *testing.T) {
|
||||
d := diskv.New(diskv.Options{
|
||||
BasePath: "test-data",
|
||||
Transform: blockTransform(2),
|
||||
})
|
||||
defer d.EraseAll()
|
||||
|
||||
for k, v := range keysTestData {
|
||||
d.Write(k, []byte(v))
|
||||
}
|
||||
|
||||
checkKeys(t, d.Keys(nil), keysTestData)
|
||||
}
|
||||
|
||||
func TestKeysPrefixFlat(t *testing.T) {
|
||||
d := diskv.New(diskv.Options{
|
||||
BasePath: "test-data",
|
||||
})
|
||||
defer d.EraseAll()
|
||||
|
||||
for k, v := range keysTestData {
|
||||
d.Write(k, []byte(v))
|
||||
}
|
||||
|
||||
for _, prefix := range prefixes {
|
||||
checkKeys(t, d.KeysPrefix(prefix, nil), filterPrefix(keysTestData, prefix))
|
||||
}
|
||||
}
|
||||
|
||||
func TestKeysPrefixNested(t *testing.T) {
|
||||
d := diskv.New(diskv.Options{
|
||||
BasePath: "test-data",
|
||||
Transform: blockTransform(2),
|
||||
})
|
||||
defer d.EraseAll()
|
||||
|
||||
for k, v := range keysTestData {
|
||||
d.Write(k, []byte(v))
|
||||
}
|
||||
|
||||
for _, prefix := range prefixes {
|
||||
checkKeys(t, d.KeysPrefix(prefix, nil), filterPrefix(keysTestData, prefix))
|
||||
}
|
||||
}
|
||||
|
||||
func TestKeysCancel(t *testing.T) {
|
||||
d := diskv.New(diskv.Options{
|
||||
BasePath: "test-data",
|
||||
})
|
||||
defer d.EraseAll()
|
||||
|
||||
for k, v := range keysTestData {
|
||||
d.Write(k, []byte(v))
|
||||
}
|
||||
|
||||
var (
|
||||
cancel = make(chan struct{})
|
||||
received = 0
|
||||
cancelAfter = len(keysTestData) / 2
|
||||
)
|
||||
|
||||
for key := range d.Keys(cancel) {
|
||||
received++
|
||||
|
||||
if received >= cancelAfter {
|
||||
close(cancel)
|
||||
runtime.Gosched() // allow walker to detect cancel
|
||||
}
|
||||
|
||||
t.Logf("received %d: %q", received, key)
|
||||
}
|
||||
|
||||
if want, have := cancelAfter, received; want != have {
|
||||
t.Errorf("want %d, have %d")
|
||||
}
|
||||
}
|
||||
|
||||
func checkKeys(t *testing.T, c <-chan string, want map[string]string) {
|
||||
for k := range c {
|
||||
if _, ok := want[k]; !ok {
|
||||
t.Errorf("%q yielded but not expected", k)
|
||||
continue
|
||||
}
|
||||
|
||||
delete(want, k)
|
||||
t.Logf("%q yielded OK", k)
|
||||
}
|
||||
|
||||
if len(want) != 0 {
|
||||
t.Errorf("%d expected key(s) not yielded: %s", len(want), strings.Join(flattenKeys(want), ", "))
|
||||
}
|
||||
}
|
||||
|
||||
func blockTransform(blockSize int) func(string) []string {
|
||||
return func(s string) []string {
|
||||
var (
|
||||
sliceSize = len(s) / blockSize
|
||||
pathSlice = make([]string, sliceSize)
|
||||
)
|
||||
for i := 0; i < sliceSize; i++ {
|
||||
from, to := i*blockSize, (i*blockSize)+blockSize
|
||||
pathSlice[i] = s[from:to]
|
||||
}
|
||||
return pathSlice
|
||||
}
|
||||
}
|
||||
|
||||
func filterPrefix(in map[string]string, prefix string) map[string]string {
|
||||
out := map[string]string{}
|
||||
for k, v := range in {
|
||||
if strings.HasPrefix(k, prefix) {
|
||||
out[k] = v
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestFilterPrefix(t *testing.T) {
|
||||
input := map[string]string{
|
||||
"all": "",
|
||||
"and": "",
|
||||
"at": "",
|
||||
"available": "",
|
||||
"best": "",
|
||||
"building": "",
|
||||
"components": "",
|
||||
"coreos": "",
|
||||
"did": "",
|
||||
"exist": "",
|
||||
"looked": "",
|
||||
"not": "",
|
||||
"ones": "",
|
||||
"re-using": "",
|
||||
"started": "",
|
||||
"that": "",
|
||||
"the": "",
|
||||
"to": "",
|
||||
"tools": "",
|
||||
"us": "",
|
||||
"various": "",
|
||||
"we": "",
|
||||
"when": "",
|
||||
}
|
||||
|
||||
for prefix, want := range map[string]map[string]string{
|
||||
"a": map[string]string{"all": "", "and": "", "at": "", "available": ""},
|
||||
"al": map[string]string{"all": ""},
|
||||
"all": map[string]string{"all": ""},
|
||||
"alll": map[string]string{},
|
||||
"c": map[string]string{"components": "", "coreos": ""},
|
||||
"co": map[string]string{"components": "", "coreos": ""},
|
||||
"com": map[string]string{"components": ""},
|
||||
} {
|
||||
have := filterPrefix(input, prefix)
|
||||
if !reflect.DeepEqual(want, have) {
|
||||
t.Errorf("%q: want %v, have %v", prefix, flattenKeys(want), flattenKeys(have))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func flattenKeys(m map[string]string) []string {
|
||||
a := make([]string, 0, len(m))
|
||||
for k := range m {
|
||||
a = append(a, k)
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
|
@ -1,153 +0,0 @@
|
|||
package diskv
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func shuffle(keys []string) {
|
||||
ints := rand.Perm(len(keys))
|
||||
for i := range keys {
|
||||
keys[i], keys[ints[i]] = keys[ints[i]], keys[i]
|
||||
}
|
||||
}
|
||||
|
||||
func genValue(size int) []byte {
|
||||
v := make([]byte, size)
|
||||
for i := 0; i < size; i++ {
|
||||
v[i] = uint8((rand.Int() % 26) + 97) // a-z
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
const (
|
||||
keyCount = 1000
|
||||
)
|
||||
|
||||
func genKeys() []string {
|
||||
keys := make([]string, keyCount)
|
||||
for i := 0; i < keyCount; i++ {
|
||||
keys[i] = fmt.Sprintf("%d", i)
|
||||
}
|
||||
return keys
|
||||
}
|
||||
|
||||
func (d *Diskv) load(keys []string, val []byte) {
|
||||
for _, key := range keys {
|
||||
d.Write(key, val)
|
||||
}
|
||||
}
|
||||
|
||||
func benchRead(b *testing.B, size, cachesz int) {
|
||||
b.StopTimer()
|
||||
d := New(Options{
|
||||
BasePath: "speed-test",
|
||||
Transform: func(string) []string { return []string{} },
|
||||
CacheSizeMax: uint64(cachesz),
|
||||
})
|
||||
defer d.EraseAll()
|
||||
|
||||
keys := genKeys()
|
||||
value := genValue(size)
|
||||
d.load(keys, value)
|
||||
shuffle(keys)
|
||||
b.SetBytes(int64(size))
|
||||
|
||||
b.StartTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
_, _ = d.Read(keys[i%len(keys)])
|
||||
}
|
||||
b.StopTimer()
|
||||
}
|
||||
|
||||
func benchWrite(b *testing.B, size int, withIndex bool) {
|
||||
b.StopTimer()
|
||||
|
||||
options := Options{
|
||||
BasePath: "speed-test",
|
||||
Transform: func(string) []string { return []string{} },
|
||||
CacheSizeMax: 0,
|
||||
}
|
||||
if withIndex {
|
||||
options.Index = &BTreeIndex{}
|
||||
options.IndexLess = strLess
|
||||
}
|
||||
|
||||
d := New(options)
|
||||
defer d.EraseAll()
|
||||
keys := genKeys()
|
||||
value := genValue(size)
|
||||
shuffle(keys)
|
||||
b.SetBytes(int64(size))
|
||||
|
||||
b.StartTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
d.Write(keys[i%len(keys)], value)
|
||||
}
|
||||
b.StopTimer()
|
||||
}
|
||||
|
||||
func BenchmarkWrite__32B_NoIndex(b *testing.B) {
|
||||
benchWrite(b, 32, false)
|
||||
}
|
||||
|
||||
func BenchmarkWrite__1KB_NoIndex(b *testing.B) {
|
||||
benchWrite(b, 1024, false)
|
||||
}
|
||||
|
||||
func BenchmarkWrite__4KB_NoIndex(b *testing.B) {
|
||||
benchWrite(b, 4096, false)
|
||||
}
|
||||
|
||||
func BenchmarkWrite_10KB_NoIndex(b *testing.B) {
|
||||
benchWrite(b, 10240, false)
|
||||
}
|
||||
|
||||
func BenchmarkWrite__32B_WithIndex(b *testing.B) {
|
||||
benchWrite(b, 32, true)
|
||||
}
|
||||
|
||||
func BenchmarkWrite__1KB_WithIndex(b *testing.B) {
|
||||
benchWrite(b, 1024, true)
|
||||
}
|
||||
|
||||
func BenchmarkWrite__4KB_WithIndex(b *testing.B) {
|
||||
benchWrite(b, 4096, true)
|
||||
}
|
||||
|
||||
func BenchmarkWrite_10KB_WithIndex(b *testing.B) {
|
||||
benchWrite(b, 10240, true)
|
||||
}
|
||||
|
||||
func BenchmarkRead__32B_NoCache(b *testing.B) {
|
||||
benchRead(b, 32, 0)
|
||||
}
|
||||
|
||||
func BenchmarkRead__1KB_NoCache(b *testing.B) {
|
||||
benchRead(b, 1024, 0)
|
||||
}
|
||||
|
||||
func BenchmarkRead__4KB_NoCache(b *testing.B) {
|
||||
benchRead(b, 4096, 0)
|
||||
}
|
||||
|
||||
func BenchmarkRead_10KB_NoCache(b *testing.B) {
|
||||
benchRead(b, 10240, 0)
|
||||
}
|
||||
|
||||
func BenchmarkRead__32B_WithCache(b *testing.B) {
|
||||
benchRead(b, 32, keyCount*32*2)
|
||||
}
|
||||
|
||||
func BenchmarkRead__1KB_WithCache(b *testing.B) {
|
||||
benchRead(b, 1024, keyCount*1024*2)
|
||||
}
|
||||
|
||||
func BenchmarkRead__4KB_WithCache(b *testing.B) {
|
||||
benchRead(b, 4096, keyCount*4096*2)
|
||||
}
|
||||
|
||||
func BenchmarkRead_10KB_WithCache(b *testing.B) {
|
||||
benchRead(b, 10240, keyCount*4096*2)
|
||||
}
|
||||
|
|
@ -1,117 +0,0 @@
|
|||
package diskv
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io/ioutil"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestBasicStreamCaching(t *testing.T) {
|
||||
d := New(Options{
|
||||
BasePath: "test-data",
|
||||
CacheSizeMax: 1024,
|
||||
})
|
||||
defer d.EraseAll()
|
||||
|
||||
input := "a1b2c3"
|
||||
key, writeBuf, sync := "a", bytes.NewBufferString(input), true
|
||||
if err := d.WriteStream(key, writeBuf, sync); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if d.isCached(key) {
|
||||
t.Fatalf("'%s' cached, but shouldn't be (yet)", key)
|
||||
}
|
||||
|
||||
rc, err := d.ReadStream(key, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
readBuf, err := ioutil.ReadAll(rc)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if !cmpBytes(readBuf, []byte(input)) {
|
||||
t.Fatalf("'%s' != '%s'", string(readBuf), input)
|
||||
}
|
||||
|
||||
if !d.isCached(key) {
|
||||
t.Fatalf("'%s' isn't cached, but should be", key)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadStreamDirect(t *testing.T) {
|
||||
var (
|
||||
basePath = "test-data"
|
||||
)
|
||||
dWrite := New(Options{
|
||||
BasePath: basePath,
|
||||
CacheSizeMax: 0,
|
||||
})
|
||||
defer dWrite.EraseAll()
|
||||
dRead := New(Options{
|
||||
BasePath: basePath,
|
||||
CacheSizeMax: 1024,
|
||||
})
|
||||
|
||||
// Write
|
||||
key, val1, val2 := "a", []byte(`1234567890`), []byte(`aaaaaaaaaa`)
|
||||
if err := dWrite.Write(key, val1); err != nil {
|
||||
t.Fatalf("during first write: %s", err)
|
||||
}
|
||||
|
||||
// First, caching read.
|
||||
val, err := dRead.Read(key)
|
||||
if err != nil {
|
||||
t.Fatalf("during initial read: %s", err)
|
||||
}
|
||||
t.Logf("read 1: %s => %s", key, string(val))
|
||||
if !cmpBytes(val1, val) {
|
||||
t.Errorf("expected %q, got %q", string(val1), string(val))
|
||||
}
|
||||
if !dRead.isCached(key) {
|
||||
t.Errorf("%q should be cached, but isn't", key)
|
||||
}
|
||||
|
||||
// Write a different value.
|
||||
if err := dWrite.Write(key, val2); err != nil {
|
||||
t.Fatalf("during second write: %s", err)
|
||||
}
|
||||
|
||||
// Second read, should hit cache and get the old value.
|
||||
val, err = dRead.Read(key)
|
||||
if err != nil {
|
||||
t.Fatalf("during second (cache-hit) read: %s", err)
|
||||
}
|
||||
t.Logf("read 2: %s => %s", key, string(val))
|
||||
if !cmpBytes(val1, val) {
|
||||
t.Errorf("expected %q, got %q", string(val1), string(val))
|
||||
}
|
||||
|
||||
// Third, direct read, should get the updated value.
|
||||
rc, err := dRead.ReadStream(key, true)
|
||||
if err != nil {
|
||||
t.Fatalf("during third (direct) read, ReadStream: %s", err)
|
||||
}
|
||||
defer rc.Close()
|
||||
val, err = ioutil.ReadAll(rc)
|
||||
if err != nil {
|
||||
t.Fatalf("during third (direct) read, ReadAll: %s", err)
|
||||
}
|
||||
t.Logf("read 3: %s => %s", key, string(val))
|
||||
if !cmpBytes(val2, val) {
|
||||
t.Errorf("expected %q, got %q", string(val1), string(val))
|
||||
}
|
||||
|
||||
// Fourth read, should hit cache and get the new value.
|
||||
val, err = dRead.Read(key)
|
||||
if err != nil {
|
||||
t.Fatalf("during fourth (cache-hit) read: %s", err)
|
||||
}
|
||||
t.Logf("read 4: %s => %s", key, string(val))
|
||||
if !cmpBytes(val2, val) {
|
||||
t.Errorf("expected %q, got %q", string(val1), string(val))
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
# This source code refers to The Go Authors for copyright purposes.
|
||||
# The master list of authors is in the main Go distribution,
|
||||
# visible at http://tip.golang.org/AUTHORS.
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
# Contributing to Go
|
||||
|
||||
Go is an open source project.
|
||||
|
||||
It is the work of hundreds of contributors. We appreciate your help!
|
||||
|
||||
## Filing issues
|
||||
|
||||
When [filing an issue](https://golang.org/issue/new), make sure to answer these five questions:
|
||||
|
||||
1. What version of Go are you using (`go version`)?
|
||||
2. What operating system and processor architecture are you using?
|
||||
3. What did you do?
|
||||
4. What did you expect to see?
|
||||
5. What did you see instead?
|
||||
|
||||
General questions should go to the [golang-nuts mailing list](https://groups.google.com/group/golang-nuts) instead of the issue tracker.
|
||||
The gophers there will answer or ask you to file an issue if you've tripped over a bug.
|
||||
|
||||
## Contributing code
|
||||
|
||||
Please read the [Contribution Guidelines](https://golang.org/doc/contribute.html)
|
||||
before sending patches.
|
||||
|
||||
Unless otherwise noted, the Go source files are distributed under
|
||||
the BSD-style license found in the LICENSE file.
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
# This source code was written by the Go contributors.
|
||||
# The master list of contributors is in the main Go distribution,
|
||||
# visible at http://tip.golang.org/CONTRIBUTORS.
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
Copyright (c) 2009 The Go Authors. All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are
|
||||
met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above
|
||||
copyright notice, this list of conditions and the following disclaimer
|
||||
in the documentation and/or other materials provided with the
|
||||
distribution.
|
||||
* Neither the name of Google Inc. nor the names of its
|
||||
contributors may be used to endorse or promote products derived from
|
||||
this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
Additional IP Rights Grant (Patents)
|
||||
|
||||
"This implementation" means the copyrightable works distributed by
|
||||
Google as part of the Go project.
|
||||
|
||||
Google 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,
|
||||
transfer and otherwise run, modify and propagate the contents of this
|
||||
implementation of Go, where such license applies only to those patent
|
||||
claims, both currently owned or controlled by Google and acquired in
|
||||
the future, licensable by Google that are necessarily infringed by this
|
||||
implementation of Go. This grant does not include claims that would be
|
||||
infringed only as a consequence of further modification of this
|
||||
implementation. If you or your agent or exclusive licensee institute or
|
||||
order or agree to the institution of patent litigation against any
|
||||
entity (including a cross-claim or counterclaim in a lawsuit) alleging
|
||||
that this implementation of Go or any code incorporated within this
|
||||
implementation of Go constitutes direct or contributory patent
|
||||
infringement, or inducement of patent infringement, then any patent
|
||||
rights granted to you under this License for this implementation of Go
|
||||
shall terminate as of the date such litigation is filed.
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
# Go Time
|
||||
|
||||
This repository provides supplementary Go time packages.
|
||||
|
||||
## Download/Install
|
||||
|
||||
The easiest way to install is to run `go get -u golang.org/x/time`. You can
|
||||
also manually git clone the repository to `$GOPATH/src/golang.org/x/time`.
|
||||
|
||||
## Report Issues / Send Patches
|
||||
|
||||
This repository uses Gerrit for code changes. To learn how to submit changes to
|
||||
this repository, see https://golang.org/doc/contribute.html.
|
||||
|
||||
The main issue tracker for the time repository is located at
|
||||
https://github.com/golang/go/issues. Prefix your issue with "x/time:" in the
|
||||
subject line, so it is easy to find.
|
||||
|
|
@ -0,0 +1,380 @@
|
|||
// Copyright 2015 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package rate provides a rate limiter.
|
||||
package rate
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Limit defines the maximum frequency of some events.
|
||||
// Limit is represented as number of events per second.
|
||||
// A zero Limit allows no events.
|
||||
type Limit float64
|
||||
|
||||
// Inf is the infinite rate limit; it allows all events (even if burst is zero).
|
||||
const Inf = Limit(math.MaxFloat64)
|
||||
|
||||
// Every converts a minimum time interval between events to a Limit.
|
||||
func Every(interval time.Duration) Limit {
|
||||
if interval <= 0 {
|
||||
return Inf
|
||||
}
|
||||
return 1 / Limit(interval.Seconds())
|
||||
}
|
||||
|
||||
// A Limiter controls how frequently events are allowed to happen.
|
||||
// It implements a "token bucket" of size b, initially full and refilled
|
||||
// at rate r tokens per second.
|
||||
// Informally, in any large enough time interval, the Limiter limits the
|
||||
// rate to r tokens per second, with a maximum burst size of b events.
|
||||
// As a special case, if r == Inf (the infinite rate), b is ignored.
|
||||
// See https://en.wikipedia.org/wiki/Token_bucket for more about token buckets.
|
||||
//
|
||||
// The zero value is a valid Limiter, but it will reject all events.
|
||||
// Use NewLimiter to create non-zero Limiters.
|
||||
//
|
||||
// Limiter has three main methods, Allow, Reserve, and Wait.
|
||||
// Most callers should use Wait.
|
||||
//
|
||||
// Each of the three methods consumes a single token.
|
||||
// They differ in their behavior when no token is available.
|
||||
// If no token is available, Allow returns false.
|
||||
// If no token is available, Reserve returns a reservation for a future token
|
||||
// and the amount of time the caller must wait before using it.
|
||||
// If no token is available, Wait blocks until one can be obtained
|
||||
// or its associated context.Context is canceled.
|
||||
//
|
||||
// The methods AllowN, ReserveN, and WaitN consume n tokens.
|
||||
type Limiter struct {
|
||||
limit Limit
|
||||
burst int
|
||||
|
||||
mu sync.Mutex
|
||||
tokens float64
|
||||
// last is the last time the limiter's tokens field was updated
|
||||
last time.Time
|
||||
// lastEvent is the latest time of a rate-limited event (past or future)
|
||||
lastEvent time.Time
|
||||
}
|
||||
|
||||
// Limit returns the maximum overall event rate.
|
||||
func (lim *Limiter) Limit() Limit {
|
||||
lim.mu.Lock()
|
||||
defer lim.mu.Unlock()
|
||||
return lim.limit
|
||||
}
|
||||
|
||||
// Burst returns the maximum burst size. Burst is the maximum number of tokens
|
||||
// that can be consumed in a single call to Allow, Reserve, or Wait, so higher
|
||||
// Burst values allow more events to happen at once.
|
||||
// A zero Burst allows no events, unless limit == Inf.
|
||||
func (lim *Limiter) Burst() int {
|
||||
return lim.burst
|
||||
}
|
||||
|
||||
// NewLimiter returns a new Limiter that allows events up to rate r and permits
|
||||
// bursts of at most b tokens.
|
||||
func NewLimiter(r Limit, b int) *Limiter {
|
||||
return &Limiter{
|
||||
limit: r,
|
||||
burst: b,
|
||||
}
|
||||
}
|
||||
|
||||
// Allow is shorthand for AllowN(time.Now(), 1).
|
||||
func (lim *Limiter) Allow() bool {
|
||||
return lim.AllowN(time.Now(), 1)
|
||||
}
|
||||
|
||||
// AllowN reports whether n events may happen at time now.
|
||||
// Use this method if you intend to drop / skip events that exceed the rate limit.
|
||||
// Otherwise use Reserve or Wait.
|
||||
func (lim *Limiter) AllowN(now time.Time, n int) bool {
|
||||
return lim.reserveN(now, n, 0).ok
|
||||
}
|
||||
|
||||
// A Reservation holds information about events that are permitted by a Limiter to happen after a delay.
|
||||
// A Reservation may be canceled, which may enable the Limiter to permit additional events.
|
||||
type Reservation struct {
|
||||
ok bool
|
||||
lim *Limiter
|
||||
tokens int
|
||||
timeToAct time.Time
|
||||
// This is the Limit at reservation time, it can change later.
|
||||
limit Limit
|
||||
}
|
||||
|
||||
// OK returns whether the limiter can provide the requested number of tokens
|
||||
// within the maximum wait time. If OK is false, Delay returns InfDuration, and
|
||||
// Cancel does nothing.
|
||||
func (r *Reservation) OK() bool {
|
||||
return r.ok
|
||||
}
|
||||
|
||||
// Delay is shorthand for DelayFrom(time.Now()).
|
||||
func (r *Reservation) Delay() time.Duration {
|
||||
return r.DelayFrom(time.Now())
|
||||
}
|
||||
|
||||
// InfDuration is the duration returned by Delay when a Reservation is not OK.
|
||||
const InfDuration = time.Duration(1<<63 - 1)
|
||||
|
||||
// DelayFrom returns the duration for which the reservation holder must wait
|
||||
// before taking the reserved action. Zero duration means act immediately.
|
||||
// InfDuration means the limiter cannot grant the tokens requested in this
|
||||
// Reservation within the maximum wait time.
|
||||
func (r *Reservation) DelayFrom(now time.Time) time.Duration {
|
||||
if !r.ok {
|
||||
return InfDuration
|
||||
}
|
||||
delay := r.timeToAct.Sub(now)
|
||||
if delay < 0 {
|
||||
return 0
|
||||
}
|
||||
return delay
|
||||
}
|
||||
|
||||
// Cancel is shorthand for CancelAt(time.Now()).
|
||||
func (r *Reservation) Cancel() {
|
||||
r.CancelAt(time.Now())
|
||||
return
|
||||
}
|
||||
|
||||
// CancelAt indicates that the reservation holder will not perform the reserved action
|
||||
// and reverses the effects of this Reservation on the rate limit as much as possible,
|
||||
// considering that other reservations may have already been made.
|
||||
func (r *Reservation) CancelAt(now time.Time) {
|
||||
if !r.ok {
|
||||
return
|
||||
}
|
||||
|
||||
r.lim.mu.Lock()
|
||||
defer r.lim.mu.Unlock()
|
||||
|
||||
if r.lim.limit == Inf || r.tokens == 0 || r.timeToAct.Before(now) {
|
||||
return
|
||||
}
|
||||
|
||||
// calculate tokens to restore
|
||||
// The duration between lim.lastEvent and r.timeToAct tells us how many tokens were reserved
|
||||
// after r was obtained. These tokens should not be restored.
|
||||
restoreTokens := float64(r.tokens) - r.limit.tokensFromDuration(r.lim.lastEvent.Sub(r.timeToAct))
|
||||
if restoreTokens <= 0 {
|
||||
return
|
||||
}
|
||||
// advance time to now
|
||||
now, _, tokens := r.lim.advance(now)
|
||||
// calculate new number of tokens
|
||||
tokens += restoreTokens
|
||||
if burst := float64(r.lim.burst); tokens > burst {
|
||||
tokens = burst
|
||||
}
|
||||
// update state
|
||||
r.lim.last = now
|
||||
r.lim.tokens = tokens
|
||||
if r.timeToAct == r.lim.lastEvent {
|
||||
prevEvent := r.timeToAct.Add(r.limit.durationFromTokens(float64(-r.tokens)))
|
||||
if !prevEvent.Before(now) {
|
||||
r.lim.lastEvent = prevEvent
|
||||
}
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// Reserve is shorthand for ReserveN(time.Now(), 1).
|
||||
func (lim *Limiter) Reserve() *Reservation {
|
||||
return lim.ReserveN(time.Now(), 1)
|
||||
}
|
||||
|
||||
// ReserveN returns a Reservation that indicates how long the caller must wait before n events happen.
|
||||
// The Limiter takes this Reservation into account when allowing future events.
|
||||
// ReserveN returns false if n exceeds the Limiter's burst size.
|
||||
// Usage example:
|
||||
// r := lim.ReserveN(time.Now(), 1)
|
||||
// if !r.OK() {
|
||||
// // Not allowed to act! Did you remember to set lim.burst to be > 0 ?
|
||||
// return
|
||||
// }
|
||||
// time.Sleep(r.Delay())
|
||||
// Act()
|
||||
// Use this method if you wish to wait and slow down in accordance with the rate limit without dropping events.
|
||||
// If you need to respect a deadline or cancel the delay, use Wait instead.
|
||||
// To drop or skip events exceeding rate limit, use Allow instead.
|
||||
func (lim *Limiter) ReserveN(now time.Time, n int) *Reservation {
|
||||
r := lim.reserveN(now, n, InfDuration)
|
||||
return &r
|
||||
}
|
||||
|
||||
// contextContext is a temporary(?) copy of the context.Context type
|
||||
// to support both Go 1.6 using golang.org/x/net/context and Go 1.7+
|
||||
// with the built-in context package. If people ever stop using Go 1.6
|
||||
// we can remove this.
|
||||
type contextContext interface {
|
||||
Deadline() (deadline time.Time, ok bool)
|
||||
Done() <-chan struct{}
|
||||
Err() error
|
||||
Value(key interface{}) interface{}
|
||||
}
|
||||
|
||||
// Wait is shorthand for WaitN(ctx, 1).
|
||||
func (lim *Limiter) wait(ctx contextContext) (err error) {
|
||||
return lim.WaitN(ctx, 1)
|
||||
}
|
||||
|
||||
// WaitN blocks until lim permits n events to happen.
|
||||
// It returns an error if n exceeds the Limiter's burst size, the Context is
|
||||
// canceled, or the expected wait time exceeds the Context's Deadline.
|
||||
// The burst limit is ignored if the rate limit is Inf.
|
||||
func (lim *Limiter) waitN(ctx contextContext, n int) (err error) {
|
||||
if n > lim.burst && lim.limit != Inf {
|
||||
return fmt.Errorf("rate: Wait(n=%d) exceeds limiter's burst %d", n, lim.burst)
|
||||
}
|
||||
// Check if ctx is already cancelled
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
default:
|
||||
}
|
||||
// Determine wait limit
|
||||
now := time.Now()
|
||||
waitLimit := InfDuration
|
||||
if deadline, ok := ctx.Deadline(); ok {
|
||||
waitLimit = deadline.Sub(now)
|
||||
}
|
||||
// Reserve
|
||||
r := lim.reserveN(now, n, waitLimit)
|
||||
if !r.ok {
|
||||
return fmt.Errorf("rate: Wait(n=%d) would exceed context deadline", n)
|
||||
}
|
||||
// Wait
|
||||
t := time.NewTimer(r.DelayFrom(now))
|
||||
defer t.Stop()
|
||||
select {
|
||||
case <-t.C:
|
||||
// We can proceed.
|
||||
return nil
|
||||
case <-ctx.Done():
|
||||
// Context was canceled before we could proceed. Cancel the
|
||||
// reservation, which may permit other events to proceed sooner.
|
||||
r.Cancel()
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
// SetLimit is shorthand for SetLimitAt(time.Now(), newLimit).
|
||||
func (lim *Limiter) SetLimit(newLimit Limit) {
|
||||
lim.SetLimitAt(time.Now(), newLimit)
|
||||
}
|
||||
|
||||
// SetLimitAt sets a new Limit for the limiter. The new Limit, and Burst, may be violated
|
||||
// or underutilized by those which reserved (using Reserve or Wait) but did not yet act
|
||||
// before SetLimitAt was called.
|
||||
func (lim *Limiter) SetLimitAt(now time.Time, newLimit Limit) {
|
||||
lim.mu.Lock()
|
||||
defer lim.mu.Unlock()
|
||||
|
||||
now, _, tokens := lim.advance(now)
|
||||
|
||||
lim.last = now
|
||||
lim.tokens = tokens
|
||||
lim.limit = newLimit
|
||||
}
|
||||
|
||||
// reserveN is a helper method for AllowN, ReserveN, and WaitN.
|
||||
// maxFutureReserve specifies the maximum reservation wait duration allowed.
|
||||
// reserveN returns Reservation, not *Reservation, to avoid allocation in AllowN and WaitN.
|
||||
func (lim *Limiter) reserveN(now time.Time, n int, maxFutureReserve time.Duration) Reservation {
|
||||
lim.mu.Lock()
|
||||
|
||||
if lim.limit == Inf {
|
||||
lim.mu.Unlock()
|
||||
return Reservation{
|
||||
ok: true,
|
||||
lim: lim,
|
||||
tokens: n,
|
||||
timeToAct: now,
|
||||
}
|
||||
}
|
||||
|
||||
now, last, tokens := lim.advance(now)
|
||||
|
||||
// Calculate the remaining number of tokens resulting from the request.
|
||||
tokens -= float64(n)
|
||||
|
||||
// Calculate the wait duration
|
||||
var waitDuration time.Duration
|
||||
if tokens < 0 {
|
||||
waitDuration = lim.limit.durationFromTokens(-tokens)
|
||||
}
|
||||
|
||||
// Decide result
|
||||
ok := n <= lim.burst && waitDuration <= maxFutureReserve
|
||||
|
||||
// Prepare reservation
|
||||
r := Reservation{
|
||||
ok: ok,
|
||||
lim: lim,
|
||||
limit: lim.limit,
|
||||
}
|
||||
if ok {
|
||||
r.tokens = n
|
||||
r.timeToAct = now.Add(waitDuration)
|
||||
}
|
||||
|
||||
// Update state
|
||||
if ok {
|
||||
lim.last = now
|
||||
lim.tokens = tokens
|
||||
lim.lastEvent = r.timeToAct
|
||||
} else {
|
||||
lim.last = last
|
||||
}
|
||||
|
||||
lim.mu.Unlock()
|
||||
return r
|
||||
}
|
||||
|
||||
// advance calculates and returns an updated state for lim resulting from the passage of time.
|
||||
// lim is not changed.
|
||||
func (lim *Limiter) advance(now time.Time) (newNow time.Time, newLast time.Time, newTokens float64) {
|
||||
last := lim.last
|
||||
if now.Before(last) {
|
||||
last = now
|
||||
}
|
||||
|
||||
// Avoid making delta overflow below when last is very old.
|
||||
maxElapsed := lim.limit.durationFromTokens(float64(lim.burst) - lim.tokens)
|
||||
elapsed := now.Sub(last)
|
||||
if elapsed > maxElapsed {
|
||||
elapsed = maxElapsed
|
||||
}
|
||||
|
||||
// Calculate the new number of tokens, due to time that passed.
|
||||
delta := lim.limit.tokensFromDuration(elapsed)
|
||||
tokens := lim.tokens + delta
|
||||
if burst := float64(lim.burst); tokens > burst {
|
||||
tokens = burst
|
||||
}
|
||||
|
||||
return now, last, tokens
|
||||
}
|
||||
|
||||
// durationFromTokens is a unit conversion function from the number of tokens to the duration
|
||||
// of time it takes to accumulate them at a rate of limit tokens per second.
|
||||
func (limit Limit) durationFromTokens(tokens float64) time.Duration {
|
||||
seconds := tokens / float64(limit)
|
||||
return time.Nanosecond * time.Duration(1e9*seconds)
|
||||
}
|
||||
|
||||
// tokensFromDuration is a unit conversion function from a time duration to the number of tokens
|
||||
// which could be accumulated during that duration at a rate of limit tokens per second.
|
||||
func (limit Limit) tokensFromDuration(d time.Duration) float64 {
|
||||
return d.Seconds() * float64(limit)
|
||||
}
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build !go1.7
|
||||
|
||||
package rate
|
||||
|
||||
import "golang.org/x/net/context"
|
||||
|
||||
// Wait is shorthand for WaitN(ctx, 1).
|
||||
func (lim *Limiter) Wait(ctx context.Context) (err error) {
|
||||
return lim.waitN(ctx, 1)
|
||||
}
|
||||
|
||||
// WaitN blocks until lim permits n events to happen.
|
||||
// It returns an error if n exceeds the Limiter's burst size, the Context is
|
||||
// canceled, or the expected wait time exceeds the Context's Deadline.
|
||||
func (lim *Limiter) WaitN(ctx context.Context, n int) (err error) {
|
||||
return lim.waitN(ctx, n)
|
||||
}
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build go1.7
|
||||
|
||||
package rate
|
||||
|
||||
import "context"
|
||||
|
||||
// Wait is shorthand for WaitN(ctx, 1).
|
||||
func (lim *Limiter) Wait(ctx context.Context) (err error) {
|
||||
return lim.waitN(ctx, 1)
|
||||
}
|
||||
|
||||
// WaitN blocks until lim permits n events to happen.
|
||||
// It returns an error if n exceeds the Limiter's burst size, the Context is
|
||||
// canceled, or the expected wait time exceeds the Context's Deadline.
|
||||
func (lim *Limiter) WaitN(ctx context.Context, n int) (err error) {
|
||||
return lim.waitN(ctx, n)
|
||||
}
|
||||
|
|
@ -0,0 +1,449 @@
|
|||
// Copyright 2015 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build go1.7
|
||||
|
||||
package rate
|
||||
|
||||
import (
|
||||
"context"
|
||||
"math"
|
||||
"runtime"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestLimit(t *testing.T) {
|
||||
if Limit(10) == Inf {
|
||||
t.Errorf("Limit(10) == Inf should be false")
|
||||
}
|
||||
}
|
||||
|
||||
func closeEnough(a, b Limit) bool {
|
||||
return (math.Abs(float64(a)/float64(b)) - 1.0) < 1e-9
|
||||
}
|
||||
|
||||
func TestEvery(t *testing.T) {
|
||||
cases := []struct {
|
||||
interval time.Duration
|
||||
lim Limit
|
||||
}{
|
||||
{0, Inf},
|
||||
{-1, Inf},
|
||||
{1 * time.Nanosecond, Limit(1e9)},
|
||||
{1 * time.Microsecond, Limit(1e6)},
|
||||
{1 * time.Millisecond, Limit(1e3)},
|
||||
{10 * time.Millisecond, Limit(100)},
|
||||
{100 * time.Millisecond, Limit(10)},
|
||||
{1 * time.Second, Limit(1)},
|
||||
{2 * time.Second, Limit(0.5)},
|
||||
{time.Duration(2.5 * float64(time.Second)), Limit(0.4)},
|
||||
{4 * time.Second, Limit(0.25)},
|
||||
{10 * time.Second, Limit(0.1)},
|
||||
{time.Duration(math.MaxInt64), Limit(1e9 / float64(math.MaxInt64))},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
lim := Every(tc.interval)
|
||||
if !closeEnough(lim, tc.lim) {
|
||||
t.Errorf("Every(%v) = %v want %v", tc.interval, lim, tc.lim)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const (
|
||||
d = 100 * time.Millisecond
|
||||
)
|
||||
|
||||
var (
|
||||
t0 = time.Now()
|
||||
t1 = t0.Add(time.Duration(1) * d)
|
||||
t2 = t0.Add(time.Duration(2) * d)
|
||||
t3 = t0.Add(time.Duration(3) * d)
|
||||
t4 = t0.Add(time.Duration(4) * d)
|
||||
t5 = t0.Add(time.Duration(5) * d)
|
||||
t9 = t0.Add(time.Duration(9) * d)
|
||||
)
|
||||
|
||||
type allow struct {
|
||||
t time.Time
|
||||
n int
|
||||
ok bool
|
||||
}
|
||||
|
||||
func run(t *testing.T, lim *Limiter, allows []allow) {
|
||||
for i, allow := range allows {
|
||||
ok := lim.AllowN(allow.t, allow.n)
|
||||
if ok != allow.ok {
|
||||
t.Errorf("step %d: lim.AllowN(%v, %v) = %v want %v",
|
||||
i, allow.t, allow.n, ok, allow.ok)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLimiterBurst1(t *testing.T) {
|
||||
run(t, NewLimiter(10, 1), []allow{
|
||||
{t0, 1, true},
|
||||
{t0, 1, false},
|
||||
{t0, 1, false},
|
||||
{t1, 1, true},
|
||||
{t1, 1, false},
|
||||
{t1, 1, false},
|
||||
{t2, 2, false}, // burst size is 1, so n=2 always fails
|
||||
{t2, 1, true},
|
||||
{t2, 1, false},
|
||||
})
|
||||
}
|
||||
|
||||
func TestLimiterBurst3(t *testing.T) {
|
||||
run(t, NewLimiter(10, 3), []allow{
|
||||
{t0, 2, true},
|
||||
{t0, 2, false},
|
||||
{t0, 1, true},
|
||||
{t0, 1, false},
|
||||
{t1, 4, false},
|
||||
{t2, 1, true},
|
||||
{t3, 1, true},
|
||||
{t4, 1, true},
|
||||
{t4, 1, true},
|
||||
{t4, 1, false},
|
||||
{t4, 1, false},
|
||||
{t9, 3, true},
|
||||
{t9, 0, true},
|
||||
})
|
||||
}
|
||||
|
||||
func TestLimiterJumpBackwards(t *testing.T) {
|
||||
run(t, NewLimiter(10, 3), []allow{
|
||||
{t1, 1, true}, // start at t1
|
||||
{t0, 1, true}, // jump back to t0, two tokens remain
|
||||
{t0, 1, true},
|
||||
{t0, 1, false},
|
||||
{t0, 1, false},
|
||||
{t1, 1, true}, // got a token
|
||||
{t1, 1, false},
|
||||
{t1, 1, false},
|
||||
{t2, 1, true}, // got another token
|
||||
{t2, 1, false},
|
||||
{t2, 1, false},
|
||||
})
|
||||
}
|
||||
|
||||
func TestSimultaneousRequests(t *testing.T) {
|
||||
const (
|
||||
limit = 1
|
||||
burst = 5
|
||||
numRequests = 15
|
||||
)
|
||||
var (
|
||||
wg sync.WaitGroup
|
||||
numOK = uint32(0)
|
||||
)
|
||||
|
||||
// Very slow replenishing bucket.
|
||||
lim := NewLimiter(limit, burst)
|
||||
|
||||
// Tries to take a token, atomically updates the counter and decreases the wait
|
||||
// group counter.
|
||||
f := func() {
|
||||
defer wg.Done()
|
||||
if ok := lim.Allow(); ok {
|
||||
atomic.AddUint32(&numOK, 1)
|
||||
}
|
||||
}
|
||||
|
||||
wg.Add(numRequests)
|
||||
for i := 0; i < numRequests; i++ {
|
||||
go f()
|
||||
}
|
||||
wg.Wait()
|
||||
if numOK != burst {
|
||||
t.Errorf("numOK = %d, want %d", numOK, burst)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLongRunningQPS(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping in short mode")
|
||||
}
|
||||
if runtime.GOOS == "openbsd" {
|
||||
t.Skip("low resolution time.Sleep invalidates test (golang.org/issue/14183)")
|
||||
return
|
||||
}
|
||||
|
||||
// The test runs for a few seconds executing many requests and then checks
|
||||
// that overall number of requests is reasonable.
|
||||
const (
|
||||
limit = 100
|
||||
burst = 100
|
||||
)
|
||||
var numOK = int32(0)
|
||||
|
||||
lim := NewLimiter(limit, burst)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
f := func() {
|
||||
if ok := lim.Allow(); ok {
|
||||
atomic.AddInt32(&numOK, 1)
|
||||
}
|
||||
wg.Done()
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
end := start.Add(5 * time.Second)
|
||||
for time.Now().Before(end) {
|
||||
wg.Add(1)
|
||||
go f()
|
||||
|
||||
// This will still offer ~500 requests per second, but won't consume
|
||||
// outrageous amount of CPU.
|
||||
time.Sleep(2 * time.Millisecond)
|
||||
}
|
||||
wg.Wait()
|
||||
elapsed := time.Since(start)
|
||||
ideal := burst + (limit * float64(elapsed) / float64(time.Second))
|
||||
|
||||
// We should never get more requests than allowed.
|
||||
if want := int32(ideal + 1); numOK > want {
|
||||
t.Errorf("numOK = %d, want %d (ideal %f)", numOK, want, ideal)
|
||||
}
|
||||
// We should get very close to the number of requests allowed.
|
||||
if want := int32(0.999 * ideal); numOK < want {
|
||||
t.Errorf("numOK = %d, want %d (ideal %f)", numOK, want, ideal)
|
||||
}
|
||||
}
|
||||
|
||||
type request struct {
|
||||
t time.Time
|
||||
n int
|
||||
act time.Time
|
||||
ok bool
|
||||
}
|
||||
|
||||
// dFromDuration converts a duration to a multiple of the global constant d
|
||||
func dFromDuration(dur time.Duration) int {
|
||||
// Adding a millisecond to be swallowed by the integer division
|
||||
// because we don't care about small inaccuracies
|
||||
return int((dur + time.Millisecond) / d)
|
||||
}
|
||||
|
||||
// dSince returns multiples of d since t0
|
||||
func dSince(t time.Time) int {
|
||||
return dFromDuration(t.Sub(t0))
|
||||
}
|
||||
|
||||
func runReserve(t *testing.T, lim *Limiter, req request) *Reservation {
|
||||
return runReserveMax(t, lim, req, InfDuration)
|
||||
}
|
||||
|
||||
func runReserveMax(t *testing.T, lim *Limiter, req request, maxReserve time.Duration) *Reservation {
|
||||
r := lim.reserveN(req.t, req.n, maxReserve)
|
||||
if r.ok && (dSince(r.timeToAct) != dSince(req.act)) || r.ok != req.ok {
|
||||
t.Errorf("lim.reserveN(t%d, %v, %v) = (t%d, %v) want (t%d, %v)",
|
||||
dSince(req.t), req.n, maxReserve, dSince(r.timeToAct), r.ok, dSince(req.act), req.ok)
|
||||
}
|
||||
return &r
|
||||
}
|
||||
|
||||
func TestSimpleReserve(t *testing.T) {
|
||||
lim := NewLimiter(10, 2)
|
||||
|
||||
runReserve(t, lim, request{t0, 2, t0, true})
|
||||
runReserve(t, lim, request{t0, 2, t2, true})
|
||||
runReserve(t, lim, request{t3, 2, t4, true})
|
||||
}
|
||||
|
||||
func TestMix(t *testing.T) {
|
||||
lim := NewLimiter(10, 2)
|
||||
|
||||
runReserve(t, lim, request{t0, 3, t1, false}) // should return false because n > Burst
|
||||
runReserve(t, lim, request{t0, 2, t0, true})
|
||||
run(t, lim, []allow{{t1, 2, false}}) // not enought tokens - don't allow
|
||||
runReserve(t, lim, request{t1, 2, t2, true})
|
||||
run(t, lim, []allow{{t1, 1, false}}) // negative tokens - don't allow
|
||||
run(t, lim, []allow{{t3, 1, true}})
|
||||
}
|
||||
|
||||
func TestCancelInvalid(t *testing.T) {
|
||||
lim := NewLimiter(10, 2)
|
||||
|
||||
runReserve(t, lim, request{t0, 2, t0, true})
|
||||
r := runReserve(t, lim, request{t0, 3, t3, false})
|
||||
r.CancelAt(t0) // should have no effect
|
||||
runReserve(t, lim, request{t0, 2, t2, true}) // did not get extra tokens
|
||||
}
|
||||
|
||||
func TestCancelLast(t *testing.T) {
|
||||
lim := NewLimiter(10, 2)
|
||||
|
||||
runReserve(t, lim, request{t0, 2, t0, true})
|
||||
r := runReserve(t, lim, request{t0, 2, t2, true})
|
||||
r.CancelAt(t1) // got 2 tokens back
|
||||
runReserve(t, lim, request{t1, 2, t2, true})
|
||||
}
|
||||
|
||||
func TestCancelTooLate(t *testing.T) {
|
||||
lim := NewLimiter(10, 2)
|
||||
|
||||
runReserve(t, lim, request{t0, 2, t0, true})
|
||||
r := runReserve(t, lim, request{t0, 2, t2, true})
|
||||
r.CancelAt(t3) // too late to cancel - should have no effect
|
||||
runReserve(t, lim, request{t3, 2, t4, true})
|
||||
}
|
||||
|
||||
func TestCancel0Tokens(t *testing.T) {
|
||||
lim := NewLimiter(10, 2)
|
||||
|
||||
runReserve(t, lim, request{t0, 2, t0, true})
|
||||
r := runReserve(t, lim, request{t0, 1, t1, true})
|
||||
runReserve(t, lim, request{t0, 1, t2, true})
|
||||
r.CancelAt(t0) // got 0 tokens back
|
||||
runReserve(t, lim, request{t0, 1, t3, true})
|
||||
}
|
||||
|
||||
func TestCancel1Token(t *testing.T) {
|
||||
lim := NewLimiter(10, 2)
|
||||
|
||||
runReserve(t, lim, request{t0, 2, t0, true})
|
||||
r := runReserve(t, lim, request{t0, 2, t2, true})
|
||||
runReserve(t, lim, request{t0, 1, t3, true})
|
||||
r.CancelAt(t2) // got 1 token back
|
||||
runReserve(t, lim, request{t2, 2, t4, true})
|
||||
}
|
||||
|
||||
func TestCancelMulti(t *testing.T) {
|
||||
lim := NewLimiter(10, 4)
|
||||
|
||||
runReserve(t, lim, request{t0, 4, t0, true})
|
||||
rA := runReserve(t, lim, request{t0, 3, t3, true})
|
||||
runReserve(t, lim, request{t0, 1, t4, true})
|
||||
rC := runReserve(t, lim, request{t0, 1, t5, true})
|
||||
rC.CancelAt(t1) // get 1 token back
|
||||
rA.CancelAt(t1) // get 2 tokens back, as if C was never reserved
|
||||
runReserve(t, lim, request{t1, 3, t5, true})
|
||||
}
|
||||
|
||||
func TestReserveJumpBack(t *testing.T) {
|
||||
lim := NewLimiter(10, 2)
|
||||
|
||||
runReserve(t, lim, request{t1, 2, t1, true}) // start at t1
|
||||
runReserve(t, lim, request{t0, 1, t1, true}) // should violate Limit,Burst
|
||||
runReserve(t, lim, request{t2, 2, t3, true})
|
||||
}
|
||||
|
||||
func TestReserveJumpBackCancel(t *testing.T) {
|
||||
lim := NewLimiter(10, 2)
|
||||
|
||||
runReserve(t, lim, request{t1, 2, t1, true}) // start at t1
|
||||
r := runReserve(t, lim, request{t1, 2, t3, true})
|
||||
runReserve(t, lim, request{t1, 1, t4, true})
|
||||
r.CancelAt(t0) // cancel at t0, get 1 token back
|
||||
runReserve(t, lim, request{t1, 2, t4, true}) // should violate Limit,Burst
|
||||
}
|
||||
|
||||
func TestReserveSetLimit(t *testing.T) {
|
||||
lim := NewLimiter(5, 2)
|
||||
|
||||
runReserve(t, lim, request{t0, 2, t0, true})
|
||||
runReserve(t, lim, request{t0, 2, t4, true})
|
||||
lim.SetLimitAt(t2, 10)
|
||||
runReserve(t, lim, request{t2, 1, t4, true}) // violates Limit and Burst
|
||||
}
|
||||
|
||||
func TestReserveSetLimitCancel(t *testing.T) {
|
||||
lim := NewLimiter(5, 2)
|
||||
|
||||
runReserve(t, lim, request{t0, 2, t0, true})
|
||||
r := runReserve(t, lim, request{t0, 2, t4, true})
|
||||
lim.SetLimitAt(t2, 10)
|
||||
r.CancelAt(t2) // 2 tokens back
|
||||
runReserve(t, lim, request{t2, 2, t3, true})
|
||||
}
|
||||
|
||||
func TestReserveMax(t *testing.T) {
|
||||
lim := NewLimiter(10, 2)
|
||||
maxT := d
|
||||
|
||||
runReserveMax(t, lim, request{t0, 2, t0, true}, maxT)
|
||||
runReserveMax(t, lim, request{t0, 1, t1, true}, maxT) // reserve for close future
|
||||
runReserveMax(t, lim, request{t0, 1, t2, false}, maxT) // time to act too far in the future
|
||||
}
|
||||
|
||||
type wait struct {
|
||||
name string
|
||||
ctx context.Context
|
||||
n int
|
||||
delay int // in multiples of d
|
||||
nilErr bool
|
||||
}
|
||||
|
||||
func runWait(t *testing.T, lim *Limiter, w wait) {
|
||||
start := time.Now()
|
||||
err := lim.WaitN(w.ctx, w.n)
|
||||
delay := time.Now().Sub(start)
|
||||
if (w.nilErr && err != nil) || (!w.nilErr && err == nil) || w.delay != dFromDuration(delay) {
|
||||
errString := "<nil>"
|
||||
if !w.nilErr {
|
||||
errString = "<non-nil error>"
|
||||
}
|
||||
t.Errorf("lim.WaitN(%v, lim, %v) = %v with delay %v ; want %v with delay %v",
|
||||
w.name, w.n, err, delay, errString, d*time.Duration(w.delay))
|
||||
}
|
||||
}
|
||||
|
||||
func TestWaitSimple(t *testing.T) {
|
||||
lim := NewLimiter(10, 3)
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
runWait(t, lim, wait{"already-cancelled", ctx, 1, 0, false})
|
||||
|
||||
runWait(t, lim, wait{"exceed-burst-error", context.Background(), 4, 0, false})
|
||||
|
||||
runWait(t, lim, wait{"act-now", context.Background(), 2, 0, true})
|
||||
runWait(t, lim, wait{"act-later", context.Background(), 3, 2, true})
|
||||
}
|
||||
|
||||
func TestWaitCancel(t *testing.T) {
|
||||
lim := NewLimiter(10, 3)
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
runWait(t, lim, wait{"act-now", ctx, 2, 0, true}) // after this lim.tokens = 1
|
||||
go func() {
|
||||
time.Sleep(d)
|
||||
cancel()
|
||||
}()
|
||||
runWait(t, lim, wait{"will-cancel", ctx, 3, 1, false})
|
||||
// should get 3 tokens back, and have lim.tokens = 2
|
||||
t.Logf("tokens:%v last:%v lastEvent:%v", lim.tokens, lim.last, lim.lastEvent)
|
||||
runWait(t, lim, wait{"act-now-after-cancel", context.Background(), 2, 0, true})
|
||||
}
|
||||
|
||||
func TestWaitTimeout(t *testing.T) {
|
||||
lim := NewLimiter(10, 3)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), d)
|
||||
defer cancel()
|
||||
runWait(t, lim, wait{"act-now", ctx, 2, 0, true})
|
||||
runWait(t, lim, wait{"w-timeout-err", ctx, 3, 0, false})
|
||||
}
|
||||
|
||||
func TestWaitInf(t *testing.T) {
|
||||
lim := NewLimiter(Inf, 0)
|
||||
|
||||
runWait(t, lim, wait{"exceed-burst-no-error", context.Background(), 3, 0, true})
|
||||
}
|
||||
|
||||
func BenchmarkAllowN(b *testing.B) {
|
||||
lim := NewLimiter(Every(1*time.Second), 1)
|
||||
now := time.Now()
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
b.RunParallel(func(pb *testing.PB) {
|
||||
for pb.Next() {
|
||||
lim.AllowN(now, 1)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
Sorry, we do not accept changes directly against this repository. Please see
|
||||
CONTRIBUTING.md for information on where and how to contribute instead.
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
# Contributing guidelines
|
||||
|
||||
Do not open pull requests directly against this repository, they will be ignored. Instead, please open pull requests against [kubernetes/kubernetes](https://git.k8s.io/kubernetes/). Please follow the same [contributing guide](https://git.k8s.io/kubernetes/CONTRIBUTING.md) you would follow for any other pull request made to kubernetes/kubernetes.
|
||||
|
||||
This repository is published from [kubernetes/kubernetes/staging/src/k8s.io/api](https://git.k8s.io/kubernetes/staging/src/k8s.io/api) by the [kubernetes publishing-bot](https://git.k8s.io/publishing-bot).
|
||||
|
||||
Please see [Staging Directory and Publishing](https://git.k8s.io/community/contributors/devel/staging.md) for more information
|
||||
|
|
@ -6,38 +6,6 @@
|
|||
"./..."
|
||||
],
|
||||
"Deps": [
|
||||
{
|
||||
"ImportPath": "github.com/PuerkitoBio/purell",
|
||||
"Rev": "8a290539e2e8629dbc4e6bad948158f790ec31f4"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/PuerkitoBio/urlesc",
|
||||
"Rev": "5bd2802263f21d8788851d5305584c82a5c75d7e"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/emicklei/go-restful",
|
||||
"Rev": "ff4f55a206334ef123e4f79bbf348980da81ca46"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/emicklei/go-restful/log",
|
||||
"Rev": "ff4f55a206334ef123e4f79bbf348980da81ca46"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/go-openapi/jsonpointer",
|
||||
"Rev": "46af16f9f7b149af66e5d1bd010e3574dc06de98"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/go-openapi/jsonreference",
|
||||
"Rev": "13c6e3589ad90f49bd3e3bbe2c2cb3d7a4142272"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/go-openapi/spec",
|
||||
"Rev": "7abd5745472fff5eb3685386d5fb8bf38683154d"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/go-openapi/swag",
|
||||
"Rev": "f3f9494671f93fcff853e3c6e9e948b3eb71e590"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/gogo/protobuf/proto",
|
||||
"Rev": "c0656edd0d9eab7c66d1eb0c568f9039345796f7"
|
||||
|
|
@ -54,21 +22,9 @@
|
|||
"ImportPath": "github.com/google/gofuzz",
|
||||
"Rev": "44d81051d367757e1c7c6a5a86423ece9afcf63c"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/mailru/easyjson/buffer",
|
||||
"Rev": "2f5df55504ebc322e4d52d34df6a1f5b503bf26d"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/mailru/easyjson/jlexer",
|
||||
"Rev": "2f5df55504ebc322e4d52d34df6a1f5b503bf26d"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/mailru/easyjson/jwriter",
|
||||
"Rev": "2f5df55504ebc322e4d52d34df6a1f5b503bf26d"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/spf13/pflag",
|
||||
"Rev": "9ff6c6923cfffbcd502984b8e0c80539a94968b7"
|
||||
"Rev": "4c012f6dcd9546820e378d0bdda4d8fc772cdfea"
|
||||
},
|
||||
{
|
||||
"ImportPath": "golang.org/x/net/http2",
|
||||
|
|
@ -86,34 +42,10 @@
|
|||
"ImportPath": "golang.org/x/net/lex/httplex",
|
||||
"Rev": "1c05540f6879653db88113bc4a2b70aec4bd491f"
|
||||
},
|
||||
{
|
||||
"ImportPath": "golang.org/x/text/cases",
|
||||
"Rev": "b19bf474d317b857955b12035d2c5acb57ce8b01"
|
||||
},
|
||||
{
|
||||
"ImportPath": "golang.org/x/text/internal",
|
||||
"Rev": "b19bf474d317b857955b12035d2c5acb57ce8b01"
|
||||
},
|
||||
{
|
||||
"ImportPath": "golang.org/x/text/internal/tag",
|
||||
"Rev": "b19bf474d317b857955b12035d2c5acb57ce8b01"
|
||||
},
|
||||
{
|
||||
"ImportPath": "golang.org/x/text/language",
|
||||
"Rev": "b19bf474d317b857955b12035d2c5acb57ce8b01"
|
||||
},
|
||||
{
|
||||
"ImportPath": "golang.org/x/text/runes",
|
||||
"Rev": "b19bf474d317b857955b12035d2c5acb57ce8b01"
|
||||
},
|
||||
{
|
||||
"ImportPath": "golang.org/x/text/secure/bidirule",
|
||||
"Rev": "b19bf474d317b857955b12035d2c5acb57ce8b01"
|
||||
},
|
||||
{
|
||||
"ImportPath": "golang.org/x/text/secure/precis",
|
||||
"Rev": "b19bf474d317b857955b12035d2c5acb57ce8b01"
|
||||
},
|
||||
{
|
||||
"ImportPath": "golang.org/x/text/transform",
|
||||
"Rev": "b19bf474d317b857955b12035d2c5acb57ce8b01"
|
||||
|
|
@ -126,105 +58,93 @@
|
|||
"ImportPath": "golang.org/x/text/unicode/norm",
|
||||
"Rev": "b19bf474d317b857955b12035d2c5acb57ce8b01"
|
||||
},
|
||||
{
|
||||
"ImportPath": "golang.org/x/text/width",
|
||||
"Rev": "b19bf474d317b857955b12035d2c5acb57ce8b01"
|
||||
},
|
||||
{
|
||||
"ImportPath": "gopkg.in/inf.v0",
|
||||
"Rev": "3887ee99ecf07df5b447e9b00d9c0b2adaa9f3e4"
|
||||
},
|
||||
{
|
||||
"ImportPath": "gopkg.in/yaml.v2",
|
||||
"Rev": "53feefa2559fb8dfa8d81baad31be332c97d6c77"
|
||||
},
|
||||
{
|
||||
"ImportPath": "k8s.io/apimachinery/pkg/api/resource",
|
||||
"Rev": "23bc0b9defba312e3b5938fa0d0581f3e882f862"
|
||||
"Rev": "5d4f0da8e5fde7cbadf8ab3ce5cfb76f86dd854e"
|
||||
},
|
||||
{
|
||||
"ImportPath": "k8s.io/apimachinery/pkg/apis/meta/v1",
|
||||
"Rev": "23bc0b9defba312e3b5938fa0d0581f3e882f862"
|
||||
"Rev": "5d4f0da8e5fde7cbadf8ab3ce5cfb76f86dd854e"
|
||||
},
|
||||
{
|
||||
"ImportPath": "k8s.io/apimachinery/pkg/conversion",
|
||||
"Rev": "23bc0b9defba312e3b5938fa0d0581f3e882f862"
|
||||
"Rev": "5d4f0da8e5fde7cbadf8ab3ce5cfb76f86dd854e"
|
||||
},
|
||||
{
|
||||
"ImportPath": "k8s.io/apimachinery/pkg/conversion/queryparams",
|
||||
"Rev": "23bc0b9defba312e3b5938fa0d0581f3e882f862"
|
||||
"Rev": "5d4f0da8e5fde7cbadf8ab3ce5cfb76f86dd854e"
|
||||
},
|
||||
{
|
||||
"ImportPath": "k8s.io/apimachinery/pkg/fields",
|
||||
"Rev": "23bc0b9defba312e3b5938fa0d0581f3e882f862"
|
||||
"Rev": "5d4f0da8e5fde7cbadf8ab3ce5cfb76f86dd854e"
|
||||
},
|
||||
{
|
||||
"ImportPath": "k8s.io/apimachinery/pkg/labels",
|
||||
"Rev": "23bc0b9defba312e3b5938fa0d0581f3e882f862"
|
||||
"Rev": "5d4f0da8e5fde7cbadf8ab3ce5cfb76f86dd854e"
|
||||
},
|
||||
{
|
||||
"ImportPath": "k8s.io/apimachinery/pkg/runtime",
|
||||
"Rev": "23bc0b9defba312e3b5938fa0d0581f3e882f862"
|
||||
"Rev": "5d4f0da8e5fde7cbadf8ab3ce5cfb76f86dd854e"
|
||||
},
|
||||
{
|
||||
"ImportPath": "k8s.io/apimachinery/pkg/runtime/schema",
|
||||
"Rev": "23bc0b9defba312e3b5938fa0d0581f3e882f862"
|
||||
"Rev": "5d4f0da8e5fde7cbadf8ab3ce5cfb76f86dd854e"
|
||||
},
|
||||
{
|
||||
"ImportPath": "k8s.io/apimachinery/pkg/selection",
|
||||
"Rev": "23bc0b9defba312e3b5938fa0d0581f3e882f862"
|
||||
"Rev": "5d4f0da8e5fde7cbadf8ab3ce5cfb76f86dd854e"
|
||||
},
|
||||
{
|
||||
"ImportPath": "k8s.io/apimachinery/pkg/types",
|
||||
"Rev": "23bc0b9defba312e3b5938fa0d0581f3e882f862"
|
||||
"Rev": "5d4f0da8e5fde7cbadf8ab3ce5cfb76f86dd854e"
|
||||
},
|
||||
{
|
||||
"ImportPath": "k8s.io/apimachinery/pkg/util/errors",
|
||||
"Rev": "23bc0b9defba312e3b5938fa0d0581f3e882f862"
|
||||
"Rev": "5d4f0da8e5fde7cbadf8ab3ce5cfb76f86dd854e"
|
||||
},
|
||||
{
|
||||
"ImportPath": "k8s.io/apimachinery/pkg/util/intstr",
|
||||
"Rev": "23bc0b9defba312e3b5938fa0d0581f3e882f862"
|
||||
"Rev": "5d4f0da8e5fde7cbadf8ab3ce5cfb76f86dd854e"
|
||||
},
|
||||
{
|
||||
"ImportPath": "k8s.io/apimachinery/pkg/util/json",
|
||||
"Rev": "23bc0b9defba312e3b5938fa0d0581f3e882f862"
|
||||
"Rev": "5d4f0da8e5fde7cbadf8ab3ce5cfb76f86dd854e"
|
||||
},
|
||||
{
|
||||
"ImportPath": "k8s.io/apimachinery/pkg/util/net",
|
||||
"Rev": "23bc0b9defba312e3b5938fa0d0581f3e882f862"
|
||||
"Rev": "5d4f0da8e5fde7cbadf8ab3ce5cfb76f86dd854e"
|
||||
},
|
||||
{
|
||||
"ImportPath": "k8s.io/apimachinery/pkg/util/runtime",
|
||||
"Rev": "23bc0b9defba312e3b5938fa0d0581f3e882f862"
|
||||
"Rev": "5d4f0da8e5fde7cbadf8ab3ce5cfb76f86dd854e"
|
||||
},
|
||||
{
|
||||
"ImportPath": "k8s.io/apimachinery/pkg/util/sets",
|
||||
"Rev": "23bc0b9defba312e3b5938fa0d0581f3e882f862"
|
||||
"Rev": "5d4f0da8e5fde7cbadf8ab3ce5cfb76f86dd854e"
|
||||
},
|
||||
{
|
||||
"ImportPath": "k8s.io/apimachinery/pkg/util/validation",
|
||||
"Rev": "23bc0b9defba312e3b5938fa0d0581f3e882f862"
|
||||
"Rev": "5d4f0da8e5fde7cbadf8ab3ce5cfb76f86dd854e"
|
||||
},
|
||||
{
|
||||
"ImportPath": "k8s.io/apimachinery/pkg/util/validation/field",
|
||||
"Rev": "23bc0b9defba312e3b5938fa0d0581f3e882f862"
|
||||
"Rev": "5d4f0da8e5fde7cbadf8ab3ce5cfb76f86dd854e"
|
||||
},
|
||||
{
|
||||
"ImportPath": "k8s.io/apimachinery/pkg/util/wait",
|
||||
"Rev": "23bc0b9defba312e3b5938fa0d0581f3e882f862"
|
||||
"Rev": "5d4f0da8e5fde7cbadf8ab3ce5cfb76f86dd854e"
|
||||
},
|
||||
{
|
||||
"ImportPath": "k8s.io/apimachinery/pkg/watch",
|
||||
"Rev": "23bc0b9defba312e3b5938fa0d0581f3e882f862"
|
||||
"Rev": "5d4f0da8e5fde7cbadf8ab3ce5cfb76f86dd854e"
|
||||
},
|
||||
{
|
||||
"ImportPath": "k8s.io/apimachinery/third_party/forked/golang/reflect",
|
||||
"Rev": "23bc0b9defba312e3b5938fa0d0581f3e882f862"
|
||||
},
|
||||
{
|
||||
"ImportPath": "k8s.io/kube-openapi/pkg/common",
|
||||
"Rev": "39a7bf85c140f972372c2a0d1ee40adbf0c8bfe1"
|
||||
"Rev": "5d4f0da8e5fde7cbadf8ab3ce5cfb76f86dd854e"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,2 @@
|
|||
approvers:
|
||||
- dep-approvers
|
||||
|
|
@ -43,7 +43,6 @@ reviewers:
|
|||
- sttts
|
||||
- tallclair
|
||||
- thockin
|
||||
- timothysc
|
||||
- vishh
|
||||
- wojtek-t
|
||||
- yifan-gu
|
||||
|
|
|
|||
|
|
@ -1,43 +0,0 @@
|
|||
load("@io_bazel_rules_go//go:def.bzl", "go_library")
|
||||
|
||||
go_library(
|
||||
name = "go_default_library",
|
||||
srcs = [
|
||||
"doc.go",
|
||||
"generated.pb.go",
|
||||
"register.go",
|
||||
"types.go",
|
||||
"types_swagger_doc_generated.go",
|
||||
"zz_generated.deepcopy.go",
|
||||
],
|
||||
importpath = "k8s.io/api/admission/v1beta1",
|
||||
visibility = ["//visibility:public"],
|
||||
deps = [
|
||||
"//vendor/github.com/gogo/protobuf/proto:go_default_library",
|
||||
"//vendor/k8s.io/api/authentication/v1:go_default_library",
|
||||
"//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library",
|
||||
"//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library",
|
||||
"//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library",
|
||||
"//vendor/k8s.io/apimachinery/pkg/types:go_default_library",
|
||||
],
|
||||
)
|
||||
|
||||
filegroup(
|
||||
name = "go_default_library_protos",
|
||||
srcs = ["generated.proto"],
|
||||
visibility = ["//visibility:public"],
|
||||
)
|
||||
|
||||
filegroup(
|
||||
name = "package-srcs",
|
||||
srcs = glob(["**"]),
|
||||
tags = ["automanaged"],
|
||||
visibility = ["//visibility:private"],
|
||||
)
|
||||
|
||||
filegroup(
|
||||
name = "all-srcs",
|
||||
srcs = [":package-srcs"],
|
||||
tags = ["automanaged"],
|
||||
visibility = ["//visibility:public"],
|
||||
)
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
/*
|
||||
Copyright 2017 The Kubernetes Authors.
|
||||
Copyright The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
/*
|
||||
Copyright 2017 The Kubernetes Authors.
|
||||
Copyright The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
/*
|
||||
Copyright 2016 The Kubernetes Authors.
|
||||
Copyright The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
|
|
@ -26,7 +26,7 @@ package v1beta1
|
|||
//
|
||||
// Those methods can be generated by using hack/update-generated-swagger-docs.sh
|
||||
|
||||
// AUTO-GENERATED FUNCTIONS START HERE
|
||||
// AUTO-GENERATED FUNCTIONS START HERE. DO NOT EDIT.
|
||||
var map_AdmissionRequest = map[string]string{
|
||||
"": "AdmissionRequest describes the admission.Attributes for the admission request.",
|
||||
"uid": "UID is an identifier for the individual request/response. It allows us to distinguish instances of requests which are otherwise identical (parallel requests, requests when earlier requests did not modify etc) The UID is meant to track the round trip (request/response) between the KAS and the WebHook, not the user request. It is suitable for correlating log entries between the webhook and apiserver, for either auditing or debugging.",
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
// +build !ignore_autogenerated
|
||||
|
||||
/*
|
||||
Copyright 2017 The Kubernetes Authors.
|
||||
Copyright The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
|
|
@ -16,7 +16,7 @@ See the License for the specific language governing permissions and
|
|||
limitations under the License.
|
||||
*/
|
||||
|
||||
// This file was autogenerated by deepcopy-gen. Do not edit it manually!
|
||||
// Code generated by deepcopy-gen. DO NOT EDIT.
|
||||
|
||||
package v1beta1
|
||||
|
||||
|
|
@ -124,7 +124,6 @@ func (in *AdmissionReview) DeepCopy() *AdmissionReview {
|
|||
func (in *AdmissionReview) DeepCopyObject() runtime.Object {
|
||||
if c := in.DeepCopy(); c != nil {
|
||||
return c
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,44 +0,0 @@
|
|||
package(default_visibility = ["//visibility:public"])
|
||||
|
||||
load(
|
||||
"@io_bazel_rules_go//go:def.bzl",
|
||||
"go_library",
|
||||
)
|
||||
|
||||
go_library(
|
||||
name = "go_default_library",
|
||||
srcs = [
|
||||
"doc.go",
|
||||
"generated.pb.go",
|
||||
"register.go",
|
||||
"types.go",
|
||||
"types_swagger_doc_generated.go",
|
||||
"zz_generated.deepcopy.go",
|
||||
],
|
||||
importpath = "k8s.io/api/admissionregistration/v1alpha1",
|
||||
deps = [
|
||||
"//vendor/github.com/gogo/protobuf/proto:go_default_library",
|
||||
"//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library",
|
||||
"//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library",
|
||||
"//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library",
|
||||
],
|
||||
)
|
||||
|
||||
filegroup(
|
||||
name = "package-srcs",
|
||||
srcs = glob(["**"]),
|
||||
tags = ["automanaged"],
|
||||
visibility = ["//visibility:private"],
|
||||
)
|
||||
|
||||
filegroup(
|
||||
name = "all-srcs",
|
||||
srcs = [":package-srcs"],
|
||||
tags = ["automanaged"],
|
||||
)
|
||||
|
||||
filegroup(
|
||||
name = "go_default_library_protos",
|
||||
srcs = ["generated.proto"],
|
||||
visibility = ["//visibility:public"],
|
||||
)
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
/*
|
||||
Copyright 2017 The Kubernetes Authors.
|
||||
Copyright The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
/*
|
||||
Copyright 2017 The Kubernetes Authors.
|
||||
Copyright The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
|
|
|
|||
4
vendor/k8s.io/api/admissionregistration/v1alpha1/types_swagger_doc_generated.go
generated
vendored
4
vendor/k8s.io/api/admissionregistration/v1alpha1/types_swagger_doc_generated.go
generated
vendored
|
|
@ -1,5 +1,5 @@
|
|||
/*
|
||||
Copyright 2016 The Kubernetes Authors.
|
||||
Copyright The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
|
|
@ -26,7 +26,7 @@ package v1alpha1
|
|||
//
|
||||
// Those methods can be generated by using hack/update-generated-swagger-docs.sh
|
||||
|
||||
// AUTO-GENERATED FUNCTIONS START HERE
|
||||
// AUTO-GENERATED FUNCTIONS START HERE. DO NOT EDIT.
|
||||
var map_Initializer = map[string]string{
|
||||
"": "Initializer describes the name and the failure policy of an initializer, and what resources it applies to.",
|
||||
"name": "Name is the identifier of the initializer. It will be added to the object that needs to be initialized. Name should be fully qualified, e.g., alwayspullimages.kubernetes.io, where \"alwayspullimages\" is the name of the webhook, and kubernetes.io is the name of the organization. Required",
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
// +build !ignore_autogenerated
|
||||
|
||||
/*
|
||||
Copyright 2017 The Kubernetes Authors.
|
||||
Copyright The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
|
|
@ -16,7 +16,7 @@ See the License for the specific language governing permissions and
|
|||
limitations under the License.
|
||||
*/
|
||||
|
||||
// This file was autogenerated by deepcopy-gen. Do not edit it manually!
|
||||
// Code generated by deepcopy-gen. DO NOT EDIT.
|
||||
|
||||
package v1alpha1
|
||||
|
||||
|
|
@ -76,9 +76,8 @@ func (in *InitializerConfiguration) DeepCopy() *InitializerConfiguration {
|
|||
func (in *InitializerConfiguration) DeepCopyObject() runtime.Object {
|
||||
if c := in.DeepCopy(); c != nil {
|
||||
return c
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
|
||||
|
|
@ -110,9 +109,8 @@ func (in *InitializerConfigurationList) DeepCopy() *InitializerConfigurationList
|
|||
func (in *InitializerConfigurationList) DeepCopyObject() runtime.Object {
|
||||
if c := in.DeepCopy(); c != nil {
|
||||
return c
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
|
||||
|
|
|
|||
|
|
@ -1,44 +0,0 @@
|
|||
package(default_visibility = ["//visibility:public"])
|
||||
|
||||
load(
|
||||
"@io_bazel_rules_go//go:def.bzl",
|
||||
"go_library",
|
||||
)
|
||||
|
||||
go_library(
|
||||
name = "go_default_library",
|
||||
srcs = [
|
||||
"doc.go",
|
||||
"generated.pb.go",
|
||||
"register.go",
|
||||
"types.go",
|
||||
"types_swagger_doc_generated.go",
|
||||
"zz_generated.deepcopy.go",
|
||||
],
|
||||
importpath = "k8s.io/api/admissionregistration/v1beta1",
|
||||
deps = [
|
||||
"//vendor/github.com/gogo/protobuf/proto:go_default_library",
|
||||
"//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library",
|
||||
"//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library",
|
||||
"//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library",
|
||||
],
|
||||
)
|
||||
|
||||
filegroup(
|
||||
name = "package-srcs",
|
||||
srcs = glob(["**"]),
|
||||
tags = ["automanaged"],
|
||||
visibility = ["//visibility:private"],
|
||||
)
|
||||
|
||||
filegroup(
|
||||
name = "all-srcs",
|
||||
srcs = [":package-srcs"],
|
||||
tags = ["automanaged"],
|
||||
)
|
||||
|
||||
filegroup(
|
||||
name = "go_default_library_protos",
|
||||
srcs = ["generated.proto"],
|
||||
visibility = ["//visibility:public"],
|
||||
)
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
/*
|
||||
Copyright 2017 The Kubernetes Authors.
|
||||
Copyright The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
/*
|
||||
Copyright 2017 The Kubernetes Authors.
|
||||
Copyright The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
|
|
@ -155,6 +155,10 @@ message Webhook {
|
|||
|
||||
// Rules describes what operations on what resources/subresources the webhook cares about.
|
||||
// The webhook cares about an operation if it matches _any_ Rule.
|
||||
// However, in order to prevent ValidatingAdmissionWebhooks and MutatingAdmissionWebhooks
|
||||
// from putting the cluster in a state which cannot be recovered from without completely
|
||||
// disabling the plugin, ValidatingAdmissionWebhooks and MutatingAdmissionWebhooks are never called
|
||||
// on admission requests for ValidatingWebhookConfiguration and MutatingWebhookConfiguration objects.
|
||||
repeated RuleWithOperations rules = 3;
|
||||
|
||||
// FailurePolicy defines how unrecognized errors from the admission endpoint are handled -
|
||||
|
|
@ -165,8 +169,8 @@ message Webhook {
|
|||
// NamespaceSelector decides whether to run the webhook on an object based
|
||||
// on whether the namespace for that object matches the selector. If the
|
||||
// object itself is a namespace, the matching is performed on
|
||||
// object.metadata.labels. If the object is other cluster scoped resource,
|
||||
// it is not subjected to the webhook.
|
||||
// object.metadata.labels. If the object is another cluster scoped resource,
|
||||
// it never skips the webhook.
|
||||
//
|
||||
// For example, to run the webhook on any objects whose namespace is not
|
||||
// associated with "runlevel" of "0" or "1"; you will set the selector as
|
||||
|
|
|
|||
|
|
@ -54,11 +54,9 @@ type Rule struct {
|
|||
type FailurePolicyType string
|
||||
|
||||
const (
|
||||
// Ignore means the initializer is removed from the initializers list of an
|
||||
// object if the initializer is timed out.
|
||||
// Ignore means that an error calling the webhook is ignored.
|
||||
Ignore FailurePolicyType = "Ignore"
|
||||
// For 1.7, only "Ignore" is allowed. "Fail" will be allowed when the
|
||||
// extensible admission feature is beta.
|
||||
// Fail means that an error calling the webhook causes the admission to fail.
|
||||
Fail FailurePolicyType = "Fail"
|
||||
)
|
||||
|
||||
|
|
@ -137,6 +135,10 @@ type Webhook struct {
|
|||
|
||||
// Rules describes what operations on what resources/subresources the webhook cares about.
|
||||
// The webhook cares about an operation if it matches _any_ Rule.
|
||||
// However, in order to prevent ValidatingAdmissionWebhooks and MutatingAdmissionWebhooks
|
||||
// from putting the cluster in a state which cannot be recovered from without completely
|
||||
// disabling the plugin, ValidatingAdmissionWebhooks and MutatingAdmissionWebhooks are never called
|
||||
// on admission requests for ValidatingWebhookConfiguration and MutatingWebhookConfiguration objects.
|
||||
Rules []RuleWithOperations `json:"rules,omitempty" protobuf:"bytes,3,rep,name=rules"`
|
||||
|
||||
// FailurePolicy defines how unrecognized errors from the admission endpoint are handled -
|
||||
|
|
@ -147,8 +149,8 @@ type Webhook struct {
|
|||
// NamespaceSelector decides whether to run the webhook on an object based
|
||||
// on whether the namespace for that object matches the selector. If the
|
||||
// object itself is a namespace, the matching is performed on
|
||||
// object.metadata.labels. If the object is other cluster scoped resource,
|
||||
// it is not subjected to the webhook.
|
||||
// object.metadata.labels. If the object is another cluster scoped resource,
|
||||
// it never skips the webhook.
|
||||
//
|
||||
// For example, to run the webhook on any objects whose namespace is not
|
||||
// associated with "runlevel" of "0" or "1"; you will set the selector as
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
/*
|
||||
Copyright 2016 The Kubernetes Authors.
|
||||
Copyright The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
|
|
@ -26,7 +26,7 @@ package v1beta1
|
|||
//
|
||||
// Those methods can be generated by using hack/update-generated-swagger-docs.sh
|
||||
|
||||
// AUTO-GENERATED FUNCTIONS START HERE
|
||||
// AUTO-GENERATED FUNCTIONS START HERE. DO NOT EDIT.
|
||||
var map_MutatingWebhookConfiguration = map[string]string{
|
||||
"": "MutatingWebhookConfiguration describes the configuration of and admission webhook that accept or reject and may change the object.",
|
||||
"metadata": "Standard object metadata; More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata.",
|
||||
|
|
@ -102,9 +102,9 @@ var map_Webhook = map[string]string{
|
|||
"": "Webhook describes an admission webhook and the resources and operations it applies to.",
|
||||
"name": "The name of the admission webhook. Name should be fully qualified, e.g., imagepolicy.kubernetes.io, where \"imagepolicy\" is the name of the webhook, and kubernetes.io is the name of the organization. Required.",
|
||||
"clientConfig": "ClientConfig defines how to communicate with the hook. Required",
|
||||
"rules": "Rules describes what operations on what resources/subresources the webhook cares about. The webhook cares about an operation if it matches _any_ Rule.",
|
||||
"rules": "Rules describes what operations on what resources/subresources the webhook cares about. The webhook cares about an operation if it matches _any_ Rule. However, in order to prevent ValidatingAdmissionWebhooks and MutatingAdmissionWebhooks from putting the cluster in a state which cannot be recovered from without completely disabling the plugin, ValidatingAdmissionWebhooks and MutatingAdmissionWebhooks are never called on admission requests for ValidatingWebhookConfiguration and MutatingWebhookConfiguration objects.",
|
||||
"failurePolicy": "FailurePolicy defines how unrecognized errors from the admission endpoint are handled - allowed values are Ignore or Fail. Defaults to Ignore.",
|
||||
"namespaceSelector": "NamespaceSelector decides whether to run the webhook on an object based on whether the namespace for that object matches the selector. If the object itself is a namespace, the matching is performed on object.metadata.labels. If the object is other cluster scoped resource, it is not subjected to the webhook.\n\nFor example, to run the webhook on any objects whose namespace is not associated with \"runlevel\" of \"0\" or \"1\"; you will set the selector as follows: \"namespaceSelector\": {\n \"matchExpressions\": [\n {\n \"key\": \"runlevel\",\n \"operator\": \"NotIn\",\n \"values\": [\n \"0\",\n \"1\"\n ]\n }\n ]\n}\n\nIf instead you want to only run the webhook on any objects whose namespace is associated with the \"environment\" of \"prod\" or \"staging\"; you will set the selector as follows: \"namespaceSelector\": {\n \"matchExpressions\": [\n {\n \"key\": \"environment\",\n \"operator\": \"In\",\n \"values\": [\n \"prod\",\n \"staging\"\n ]\n }\n ]\n}\n\nSee https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/ for more examples of label selectors.\n\nDefault to the empty LabelSelector, which matches everything.",
|
||||
"namespaceSelector": "NamespaceSelector decides whether to run the webhook on an object based on whether the namespace for that object matches the selector. If the object itself is a namespace, the matching is performed on object.metadata.labels. If the object is another cluster scoped resource, it never skips the webhook.\n\nFor example, to run the webhook on any objects whose namespace is not associated with \"runlevel\" of \"0\" or \"1\"; you will set the selector as follows: \"namespaceSelector\": {\n \"matchExpressions\": [\n {\n \"key\": \"runlevel\",\n \"operator\": \"NotIn\",\n \"values\": [\n \"0\",\n \"1\"\n ]\n }\n ]\n}\n\nIf instead you want to only run the webhook on any objects whose namespace is associated with the \"environment\" of \"prod\" or \"staging\"; you will set the selector as follows: \"namespaceSelector\": {\n \"matchExpressions\": [\n {\n \"key\": \"environment\",\n \"operator\": \"In\",\n \"values\": [\n \"prod\",\n \"staging\"\n ]\n }\n ]\n}\n\nSee https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/ for more examples of label selectors.\n\nDefault to the empty LabelSelector, which matches everything.",
|
||||
}
|
||||
|
||||
func (Webhook) SwaggerDoc() map[string]string {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
// +build !ignore_autogenerated
|
||||
|
||||
/*
|
||||
Copyright 2017 The Kubernetes Authors.
|
||||
Copyright The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
|
|
@ -16,7 +16,7 @@ See the License for the specific language governing permissions and
|
|||
limitations under the License.
|
||||
*/
|
||||
|
||||
// This file was autogenerated by deepcopy-gen. Do not edit it manually!
|
||||
// Code generated by deepcopy-gen. DO NOT EDIT.
|
||||
|
||||
package v1beta1
|
||||
|
||||
|
|
@ -54,9 +54,8 @@ func (in *MutatingWebhookConfiguration) DeepCopy() *MutatingWebhookConfiguration
|
|||
func (in *MutatingWebhookConfiguration) DeepCopyObject() runtime.Object {
|
||||
if c := in.DeepCopy(); c != nil {
|
||||
return c
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
|
||||
|
|
@ -88,9 +87,8 @@ func (in *MutatingWebhookConfigurationList) DeepCopy() *MutatingWebhookConfigura
|
|||
func (in *MutatingWebhookConfigurationList) DeepCopyObject() runtime.Object {
|
||||
if c := in.DeepCopy(); c != nil {
|
||||
return c
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
|
||||
|
|
@ -200,9 +198,8 @@ func (in *ValidatingWebhookConfiguration) DeepCopy() *ValidatingWebhookConfigura
|
|||
func (in *ValidatingWebhookConfiguration) DeepCopyObject() runtime.Object {
|
||||
if c := in.DeepCopy(); c != nil {
|
||||
return c
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
|
||||
|
|
@ -234,9 +231,8 @@ func (in *ValidatingWebhookConfigurationList) DeepCopy() *ValidatingWebhookConfi
|
|||
func (in *ValidatingWebhookConfigurationList) DeepCopyObject() runtime.Object {
|
||||
if c := in.DeepCopy(); c != nil {
|
||||
return c
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
|
||||
|
|
|
|||
|
|
@ -9,7 +9,6 @@ reviewers:
|
|||
- saad-ali
|
||||
- ncdc
|
||||
- tallclair
|
||||
- timothysc
|
||||
- dims
|
||||
- errordeveloper
|
||||
- mml
|
||||
|
|
|
|||
|
|
@ -1,43 +0,0 @@
|
|||
load("@io_bazel_rules_go//go:def.bzl", "go_library")
|
||||
|
||||
go_library(
|
||||
name = "go_default_library",
|
||||
srcs = [
|
||||
"doc.go",
|
||||
"generated.pb.go",
|
||||
"register.go",
|
||||
"types.go",
|
||||
"types_swagger_doc_generated.go",
|
||||
"zz_generated.deepcopy.go",
|
||||
],
|
||||
importpath = "k8s.io/api/apps/v1",
|
||||
visibility = ["//visibility:public"],
|
||||
deps = [
|
||||
"//vendor/github.com/gogo/protobuf/proto:go_default_library",
|
||||
"//vendor/k8s.io/api/core/v1:go_default_library",
|
||||
"//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library",
|
||||
"//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library",
|
||||
"//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library",
|
||||
"//vendor/k8s.io/apimachinery/pkg/util/intstr:go_default_library",
|
||||
],
|
||||
)
|
||||
|
||||
filegroup(
|
||||
name = "go_default_library_protos",
|
||||
srcs = ["generated.proto"],
|
||||
visibility = ["//visibility:public"],
|
||||
)
|
||||
|
||||
filegroup(
|
||||
name = "package-srcs",
|
||||
srcs = glob(["**"]),
|
||||
tags = ["automanaged"],
|
||||
visibility = ["//visibility:private"],
|
||||
)
|
||||
|
||||
filegroup(
|
||||
name = "all-srcs",
|
||||
srcs = [":package-srcs"],
|
||||
tags = ["automanaged"],
|
||||
visibility = ["//visibility:public"],
|
||||
)
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
/*
|
||||
Copyright 2017 The Kubernetes Authors.
|
||||
Copyright The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
/*
|
||||
Copyright 2017 The Kubernetes Authors.
|
||||
Copyright The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
|
|
@ -501,9 +501,9 @@ message RollingUpdateDeployment {
|
|||
// Absolute number is calculated from percentage by rounding down.
|
||||
// This can not be 0 if MaxSurge is 0.
|
||||
// Defaults to 25%.
|
||||
// Example: when this is set to 30%, the old RC can be scaled down to 70% of desired pods
|
||||
// immediately when the rolling update starts. Once new pods are ready, old RC
|
||||
// can be scaled down further, followed by scaling up the new RC, ensuring
|
||||
// Example: when this is set to 30%, the old ReplicaSet can be scaled down to 70% of desired pods
|
||||
// immediately when the rolling update starts. Once new pods are ready, old ReplicaSet
|
||||
// can be scaled down further, followed by scaling up the new ReplicaSet, ensuring
|
||||
// that the total number of pods available at all times during the update is at
|
||||
// least 70% of desired pods.
|
||||
// +optional
|
||||
|
|
@ -515,11 +515,11 @@ message RollingUpdateDeployment {
|
|||
// This can not be 0 if MaxUnavailable is 0.
|
||||
// Absolute number is calculated from percentage by rounding up.
|
||||
// Defaults to 25%.
|
||||
// Example: when this is set to 30%, the new RC can be scaled up immediately when
|
||||
// Example: when this is set to 30%, the new ReplicaSet can be scaled up immediately when
|
||||
// the rolling update starts, such that the total number of old and new pods do not exceed
|
||||
// 130% of desired pods. Once old pods have been killed,
|
||||
// new RC can be scaled up further, ensuring that total number of pods running
|
||||
// at any time during the update is atmost 130% of desired pods.
|
||||
// new ReplicaSet can be scaled up further, ensuring that total number of pods running
|
||||
// at any time during the update is at most 130% of desired pods.
|
||||
// +optional
|
||||
optional k8s.io.apimachinery.pkg.util.intstr.IntOrString maxSurge = 2;
|
||||
}
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue