pax_global_header00006660000000000000000000000064143624206400014513gustar00rootroot0000000000000052 comment=18a29fa28e18e8882c3df1c78db27e2eedc94d61 clock-1.0.3/000077500000000000000000000000001436242064000126075ustar00rootroot00000000000000clock-1.0.3/.gitignore000066400000000000000000000000111436242064000145670ustar00rootroot00000000000000.vscode/ clock-1.0.3/LICENSE000066400000000000000000000215011436242064000136130ustar00rootroot00000000000000All 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. 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. clock-1.0.3/Makefile000066400000000000000000000011401436242064000142430ustar00rootroot00000000000000PROJECT := github.com/juju/clock .PHONY: check-licence check-go check check: check-licence check-go go test $(PROJECT)/... check-licence: @(fgrep -rl "Licensed under the LGPLv3" --exclude *.s .;\ fgrep -rl "MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT" --exclude *.s .;\ find . -name "*.go") | sed -e 's,\./,,' | sort | uniq -u | \ xargs -I {} echo FAIL: licence missed: {} check-go: $(eval GOFMT := $(strip $(shell gofmt -l .| sed -e "s/^/ /g"))) @(if [ x$(GOFMT) != x"" ]; then \ echo go fmt is sad: $(GOFMT); \ exit 1; \ fi ) @(go vet -all -composites=false -copylocks=false .) clock-1.0.3/README.md000066400000000000000000000002251436242064000140650ustar00rootroot00000000000000# clock An interface definition for a fully defined clock. An WallClock implementation of that interface using the time package. A testing clock. clock-1.0.3/clock.go000066400000000000000000000034301436242064000142310ustar00rootroot00000000000000// Copyright 2015 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package clock import "time" // Clock provides an interface for dealing with clocks. type Clock interface { // Now returns the current clock time. Now() time.Time // After waits for the duration to elapse and then sends the // current time on the returned channel. After(time.Duration) <-chan time.Time // AfterFunc waits for the duration to elapse and then calls f in its own goroutine. // It returns a Timer that can be used to cancel the call using its Stop method. AfterFunc(d time.Duration, f func()) Timer // NewTimer creates a new Timer that will send the current time // on its channel after at least duration d. NewTimer(d time.Duration) Timer } // Alarm returns a channel that will have the time sent on it at some point // after the supplied time occurs. // // This is short for c.After(t.Sub(c.Now())). func Alarm(c Clock, t time.Time) <-chan time.Time { return c.After(t.Sub(c.Now())) } // The Timer type represents a single event. // A Timer must be created with AfterFunc. // This interface follows time.Timer's methods but provides easier mocking. type Timer interface { // When the Timer expires, the current time will be sent on the // channel returned from Chan, unless the Timer was created by // AfterFunc. Chan() <-chan time.Time // Reset changes the timer to expire after duration d. // It returns true if the timer had been active, false if // the timer had expired or been stopped. Reset(time.Duration) bool // Stop prevents the Timer from firing. It returns true if // the call stops the timer, false if the timer has already expired or been stopped. // Stop does not close the channel, to prevent a read // from the channel succeeding incorrectly. Stop() bool } clock-1.0.3/go.mod000066400000000000000000000016161436242064000137210ustar00rootroot00000000000000module github.com/juju/clock go 1.18 require ( github.com/juju/errors v0.0.0-20220203013757-bd733f3c86b9 github.com/juju/loggo v0.0.0-20210728185423-eebad3a902c4 github.com/juju/testing v0.0.0-20220203020004-a0ff61f03494 gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c ) require ( github.com/juju/collections v0.0.0-20200605021417-0d0ec82b7271 // indirect github.com/juju/mgo/v2 v2.0.0-20210302023703-70d5d206e208 // indirect github.com/juju/retry v0.0.0-20180821225755-9058e192b216 // indirect github.com/juju/utils/v3 v3.0.0-20220130232349-cd7ecef0e94a // indirect github.com/juju/version/v2 v2.0.0-20211007103408-2e8da085dc23 // indirect github.com/kr/pretty v0.2.1 // indirect github.com/kr/text v0.2.0 // indirect golang.org/x/crypto v0.0.0-20200820211705-5c72a883971a // indirect golang.org/x/net v0.0.0-20210226172049-e18ecbb05110 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect ) clock-1.0.3/go.sum000066400000000000000000000220661436242064000137500ustar00rootroot00000000000000github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/juju/ansiterm v0.0.0-20160907234532-b99631de12cf/go.mod h1:UJSiEoRfvx3hP73CvoARgeLjaIOjybY9vj8PUPPFGeU= github.com/juju/ansiterm v0.0.0-20180109212912-720a0952cc2a/go.mod h1:UJSiEoRfvx3hP73CvoARgeLjaIOjybY9vj8PUPPFGeU= github.com/juju/clock v0.0.0-20190205081909-9c5c9712527c/go.mod h1:nD0vlnrUjcjJhqN5WuCWZyzfd5AHZAC9/ajvbSx69xA= github.com/juju/cmd v0.0.0-20171107070456-e74f39857ca0/go.mod h1:yWJQHl73rdSX4DHVKGqkAip+huBslxRwS8m9CrOLq18= github.com/juju/collections v0.0.0-20200605021417-0d0ec82b7271 h1:4R626WTwa7pRYQFiIRLVPepMhm05eZMEx+wIurRnMLc= github.com/juju/collections v0.0.0-20200605021417-0d0ec82b7271/go.mod h1:5XgO71dV1JClcOJE+4dzdn4HrI5LiyKd7PlVG6eZYhY= github.com/juju/errors v0.0.0-20150916125642-1b5e39b83d18/go.mod h1:W54LbzXuIE0boCoNJfwqpmkKJ1O4TCTZMetAt6jGk7Q= github.com/juju/errors v0.0.0-20200330140219-3fe23663418f/go.mod h1:W54LbzXuIE0boCoNJfwqpmkKJ1O4TCTZMetAt6jGk7Q= github.com/juju/errors v0.0.0-20220203013757-bd733f3c86b9 h1:EJHbsNpQyupmMeWTq7inn+5L/WZ7JfzCVPJ+DP9McCQ= github.com/juju/errors v0.0.0-20220203013757-bd733f3c86b9/go.mod h1:TRm7EVGA3mQOqSVcBySRY7a9Y1/gyVhh/WTCnc5sD4U= github.com/juju/gnuflag v0.0.0-20171113085948-2ce1bb71843d/go.mod h1:2PavIy+JPciBPrBUjwbNvtwB6RQlve+hkpll6QSNmOE= github.com/juju/httpprof v0.0.0-20141217160036-14bf14c30767/go.mod h1:+MaLYz4PumRkkyHYeXJ2G5g5cIW0sli2bOfpmbaMV/g= github.com/juju/loggo v0.0.0-20170605014607-8232ab8918d9/go.mod h1:vgyd7OREkbtVEN/8IXZe5Ooef3LQePvuBm9UWj6ZL8U= github.com/juju/loggo v0.0.0-20200526014432-9ce3a2e09b5e/go.mod h1:vgyd7OREkbtVEN/8IXZe5Ooef3LQePvuBm9UWj6ZL8U= github.com/juju/loggo v0.0.0-20210728185423-eebad3a902c4 h1:NO5tuyw++EGLnz56Q8KMyDZRwJwWO8jQnj285J3FOmY= github.com/juju/loggo v0.0.0-20210728185423-eebad3a902c4/go.mod h1:NIXFioti1SmKAlKNuUwbMenNdef59IF52+ZzuOmHYkg= github.com/juju/mgo/v2 v2.0.0-20210302023703-70d5d206e208 h1:/WiCm+Vpj87e4QWuWwPD/bNE9kDrWCLvPBHOQNcG2+A= github.com/juju/mgo/v2 v2.0.0-20210302023703-70d5d206e208/go.mod h1:0OChplkvPTZ174D2FYZXg4IB9hbEwyHkD+zT+/eK+Fg= github.com/juju/mutex v0.0.0-20171110020013-1fe2a4bf0a3a/go.mod h1:Y3oOzHH8CQ0Ppt0oCKJ2JFO81/EsWenH5AEqigLH+yY= github.com/juju/retry v0.0.0-20151029024821-62c620325291/go.mod h1:OohPQGsr4pnxwD5YljhQ+TZnuVRYpa5irjugL1Yuif4= github.com/juju/retry v0.0.0-20180821225755-9058e192b216 h1:/eQL7EJQKFHByJe3DeE8Z36yqManj9UY5zppDoQi4FU= github.com/juju/retry v0.0.0-20180821225755-9058e192b216/go.mod h1:OohPQGsr4pnxwD5YljhQ+TZnuVRYpa5irjugL1Yuif4= github.com/juju/testing v0.0.0-20180402130637-44801989f0f7/go.mod h1:63prj8cnj0tU0S9OHjGJn+b1h0ZghCndfnbQolrYTwA= github.com/juju/testing v0.0.0-20190723135506-ce30eb24acd2/go.mod h1:63prj8cnj0tU0S9OHjGJn+b1h0ZghCndfnbQolrYTwA= github.com/juju/testing v0.0.0-20210302031854-2c7ee8570c07/go.mod h1:7lxZW0B50+xdGFkvhAb8bwAGt6IU87JB1H9w4t8MNVM= github.com/juju/testing v0.0.0-20220203020004-a0ff61f03494 h1:XEDzpuZb8Ma7vLja3+5hzUqVTvAqm5Y+ygvnDs5iTMM= github.com/juju/testing v0.0.0-20220203020004-a0ff61f03494/go.mod h1:rUquetT0ALL48LHZhyRGvjjBH8xZaZ8dFClulKK5wK4= github.com/juju/utils v0.0.0-20180424094159-2000ea4ff043/go.mod h1:6/KLg8Wz/y2KVGWEpkK9vMNGkOnu4k/cqs8Z1fKjTOk= github.com/juju/utils v0.0.0-20200116185830-d40c2fe10647/go.mod h1:6/KLg8Wz/y2KVGWEpkK9vMNGkOnu4k/cqs8Z1fKjTOk= github.com/juju/utils/v2 v2.0.0-20200923005554-4646bfea2ef1/go.mod h1:fdlDtQlzundleLLz/ggoYinEt/LmnrpNKcNTABQATNI= github.com/juju/utils/v3 v3.0.0-20220130232349-cd7ecef0e94a h1:5ZWDCeCF0RaITrZGemzmDFIhjR/MVSvBUqgSyaeTMbE= github.com/juju/utils/v3 v3.0.0-20220130232349-cd7ecef0e94a/go.mod h1:LzwbbEN7buYjySp4nqnti6c6olSqRXUk6RkbSUUP1n8= github.com/juju/version v0.0.0-20161031051906-1f41e27e54f2/go.mod h1:kE8gK5X0CImdr7qpSKl3xB2PmpySSmfj7zVbkZFs81U= github.com/juju/version v0.0.0-20180108022336-b64dbd566305/go.mod h1:kE8gK5X0CImdr7qpSKl3xB2PmpySSmfj7zVbkZFs81U= github.com/juju/version v0.0.0-20191219164919-81c1be00b9a6/go.mod h1:kE8gK5X0CImdr7qpSKl3xB2PmpySSmfj7zVbkZFs81U= github.com/juju/version/v2 v2.0.0-20211007103408-2e8da085dc23 h1:wtEPbidt1VyHlb8RSztU6ySQj29FLsOQiI9XiJhXDM4= github.com/juju/version/v2 v2.0.0-20211007103408-2e8da085dc23/go.mod h1:Ljlbryh9sYaUSGXucslAEDf0A2XUSGvDbHJgW8ps6nc= github.com/julienschmidt/httprouter v1.1.1-0.20151013225520-77a895ad01eb/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= github.com/kr/pretty v0.2.1 h1:Fmg33tUaq4/8ym9TJN1x7sLJnHVwhP33CNkpYV/7rwI= github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/lunixbochs/vtclean v0.0.0-20160125035106-4fbf7632a2c6/go.mod h1:pHhQNgMf3btfWnGBVipUOjRYhoOsdGqdm/+2c2E2WMI= github.com/masterzen/azure-sdk-for-go v3.2.0-beta.0.20161014135628-ee4f0065d00c+incompatible/go.mod h1:mf8fjOu33zCqxUjuiU3I8S1lJMyEAlH+0F2+M5xl3hE= github.com/masterzen/simplexml v0.0.0-20160608183007-4572e39b1ab9/go.mod h1:kCEbxUJlNDEBNbdQMkPSp6yaKcRXVI6f4ddk8Riv4bc= github.com/masterzen/winrm v0.0.0-20161014151040-7a535cd943fc/go.mod h1:CfZSN7zwz5gJiFhZJz49Uzk7mEBHIceWmbFmYx7Hf7E= github.com/masterzen/xmlpath v0.0.0-20140218185901-13f4951698ad/go.mod h1:A0zPC53iKKKcXYxr4ROjpQRQ5FgJXtelNdSmHHuq/tY= github.com/mattn/go-colorable v0.0.6/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= github.com/mattn/go-isatty v0.0.0-20160806122752-66b8e73f3f5c/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= github.com/nu7hatch/gouuid v0.0.0-20131221200532-179d4d0c4d8d/go.mod h1:YUTz3bUH2ZwIWBy3CJBeOBEugqcmXREj14T+iG/4k4U= golang.org/x/crypto v0.0.0-20180214000028-650f4a345ab4/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200820211705-5c72a883971a h1:vclmkQCjlDX5OydZ9wv8rBCcS0QyQY66Mpf/7BZbInM= golang.org/x/crypto v0.0.0-20200820211705-5c72a883971a/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/net v0.0.0-20180406214816-61147c48b25b/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20200904194848-62affa334b73/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110 h1:qWPm9rbaAMKs8Bq/9LRpbMqxWRVUAQwMI9fVrssnTfw= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20160105164936-4f90aeace3a2/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/errgo.v1 v1.0.0-20161222125816-442357a80af5/go.mod h1:u0ALmqvLRxLI95fkdCEWrE6mhWYZW1aMOJHp5YXLHTg= gopkg.in/httprequest.v1 v1.1.1/go.mod h1:/CkavNL+g3qLOrpFHVrEx4NKepeqR4XTZWNj4sGGjz0= gopkg.in/mgo.v2 v2.0.0-20160818015218-f2b6f6c918c4/go.mod h1:yeKp02qBN3iKW1OzL3MGk2IdtZzaj7SFntXj72NppTA= gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22/go.mod h1:yeKp02qBN3iKW1OzL3MGk2IdtZzaj7SFntXj72NppTA= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= gopkg.in/tomb.v2 v2.0.0-20161208151619-d5d1b5820637/go.mod h1:BHsqpu/nsuzkT5BpiH1EMZPLyqSMM8JbIavyFACoFNk= gopkg.in/yaml.v2 v2.0.0-20170712054546-1be3d31502d6/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74= gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= launchpad.net/gocheck v0.0.0-20140225173054-000000000087/go.mod h1:hj7XX3B/0A+80Vse0e+BUHsHMTEhd0O4cpUHr/e/BUM= launchpad.net/xmlpath v0.0.0-20130614043138-000000000004/go.mod h1:vqyExLOM3qBx7mvYRkoxjSCF945s0mbe7YynlKYXtsA= clock-1.0.3/monotonic/000077500000000000000000000000001436242064000146145ustar00rootroot00000000000000clock-1.0.3/monotonic/monotonic.go000066400000000000000000000010641436242064000171510ustar00rootroot00000000000000// Copyright 2017 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package monotonic import ( "time" _ "unsafe" ) //go:noescape //go:linkname nanotime runtime.nanotime func nanotime() int64 // Now returns the current time in nanoseconds from a monotonic clock. // // The result is guaranteed to not jump due to NTP or other changes to // system time, which may jump forward or backwards. Instead, in response to // such changes, the clock frequency is adjusted slowly. func Now() time.Duration { return time.Duration(nanotime()) } clock-1.0.3/monotonic/monotonic.s000066400000000000000000000002441436242064000170050ustar00rootroot00000000000000// Copyright 2017 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. // Deliberately empty - see https://github.com/golang/go/issues/15006 clock-1.0.3/monotonic/monotonic_test.go000066400000000000000000000010331436242064000202040ustar00rootroot00000000000000// Copyright 2017 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package monotonic_test import ( "testing" "time" gc "gopkg.in/check.v1" "github.com/juju/clock/monotonic" ) func TestPackage(t *testing.T) { gc.TestingT(t) } type MonotonicSuite struct { } var _ = gc.Suite(&MonotonicSuite{}) func (s *MonotonicSuite) TestNow(c *gc.C) { var prev time.Duration for i := 0; i < 1000; i++ { val := monotonic.Now() if val < prev { c.Fatal("now is less than previous value") } prev = val } } clock-1.0.3/testclock/000077500000000000000000000000001436242064000146025ustar00rootroot00000000000000clock-1.0.3/testclock/clock.go000066400000000000000000000162151436242064000162310ustar00rootroot00000000000000// Copyright 2015-2018 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package testclock import ( "fmt" "runtime/debug" "sort" "sync" "time" "github.com/juju/clock" "github.com/juju/errors" "github.com/juju/loggo" ) // timer implements a mock clock.Timer for testing purposes. type timer struct { deadline time.Time clock *Clock c chan time.Time // trigger is called when the timer expires. It is // called with the clock mutex held and will not block. trigger func() stack []byte } // Reset is part of the clock.Timer interface. func (t *timer) Reset(d time.Duration) bool { return t.clock.reset(t, d) } // Stop is part of the clock.Timer interface. func (t *timer) Stop() bool { return t.clock.stop(t) } // Chan is part of the clock.Timer interface. func (t *timer) Chan() <-chan time.Time { return t.c } // Clock implements a mock clock.Clock for testing purposes. type Clock struct { mu sync.Mutex now time.Time waiting []*timer // timers waiting to fire, sorted by deadline. notifyAlarms chan struct{} } var _ AdvanceableClock = (*Clock)(nil) // NewClock returns a new clock set to the supplied time. If your SUT needs to // call After, AfterFunc, NewTimer or Timer.Reset more than 10000 times: (1) // you have probably written a bad test; and (2) you'll need to read from the // Alarms chan to keep the buffer clear. func NewClock(now time.Time) *Clock { return &Clock{ now: now, notifyAlarms: make(chan struct{}, 10000), } } // Now is part of the clock.Clock interface. func (clock *Clock) Now() time.Time { clock.mu.Lock() defer clock.mu.Unlock() return clock.now } // After is part of the clock.Clock interface. func (clock *Clock) After(d time.Duration) <-chan time.Time { return clock.NewTimer(d).Chan() } func (clock *Clock) NewTimer(d time.Duration) clock.Timer { c := make(chan time.Time, 1) return clock.addAlarm(d, c, func() { c <- clock.now }) } // AfterFunc is part of the clock.Clock interface. func (clock *Clock) AfterFunc(d time.Duration, f func()) clock.Timer { return clock.addAlarm(d, nil, func() { go f() }) } func (clock *Clock) addAlarm(d time.Duration, c chan time.Time, trigger func()) *timer { defer clock.notifyAlarm() clock.mu.Lock() defer clock.mu.Unlock() t := &timer{ c: c, deadline: clock.now.Add(d), clock: clock, trigger: trigger, stack: debug.Stack(), } clock.addTimer(t) clock.triggerAll() return t } // Advance advances the result of Now by the supplied duration, and sends // the "current" time on all alarms which are no longer "in the future". func (clock *Clock) Advance(d time.Duration) { clock.mu.Lock() defer clock.mu.Unlock() clock.now = clock.now.Add(d) if len(clock.waiting) == 0 { loggo.GetLogger("juju.clock").Debugf("advancing a clock that has nothing waiting: cf. https://github.com/juju/juju/wiki/Intermittent-failures") } clock.triggerAll() } // WaitAdvance functions the same as Advance, but only if there is n timers in // clock.waiting. This came about while fixing lp:1607044 intermittent // failures. It turns out that testing.Clock.Advance might advance the time // and trigger notifications before triggers are set. So we wait a limited time // 'w' for 'n' timers to show up in clock.waiting, and if they do we advance // 'd'. func (clock *Clock) WaitAdvance(d, w time.Duration, n int) error { pause := w / 10 if pause > 10*time.Millisecond { pause = 10 * time.Millisecond } finalTimeout := time.After(w) next := time.After(0) for { select { case <-finalTimeout: if clock.hasNWaiters(n) { clock.Advance(d) return nil } clock.mu.Lock() got := len(clock.waiting) var stacks string for _, t := range clock.waiting { stacks += fmt.Sprintf("timer deadline: %v\n%s", t.deadline, string(t.stack)) } clock.mu.Unlock() return errors.Errorf( "got %d timers added after waiting %s: wanted %d, stacks:\n%s", got, w.String(), n, stacks) case <-next: if clock.hasNWaiters(n) { clock.Advance(d) return nil } next = time.After(pause) } } } // hasNWaiters checks if the clock currently has 'n' timers waiting to fire. func (clock *Clock) hasNWaiters(n int) bool { clock.mu.Lock() hasWaiters := len(clock.waiting) == n clock.mu.Unlock() return hasWaiters } // Alarms returns a channel on which you can read one value for every call to // After and AfterFunc; and for every successful Timer.Reset backed by this // Clock. It might not be elegant but it's necessary when testing time logic // that runs on a goroutine other than that of the test. func (clock *Clock) Alarms() <-chan struct{} { return clock.notifyAlarms } // triggerAll triggers any alarms that are currently due and removes them // from clock.waiting. func (clock *Clock) triggerAll() { triggered := 0 for _, t := range clock.waiting { if clock.now.Before(t.deadline) { break } t.trigger() triggered++ } clock.waiting = clock.waiting[triggered:] } // reset is the underlying implementation of clock.Timer.Reset, which may be // called by any Timer backed by this Clock. func (clock *Clock) reset(t *timer, d time.Duration) bool { defer clock.notifyAlarm() clock.mu.Lock() defer clock.mu.Unlock() found := false for _, wt := range clock.waiting { if wt == t { found = true } } if !found { clock.waiting = append(clock.waiting, t) } t.deadline = clock.now.Add(d) sort.Sort(byDeadline(clock.waiting)) if d <= 0 { // If duration is <= 0, that means we should be triggering the // Timer right away, as "now" has already occured. clock.triggerAll() } return found } // stop is the underlying implementation of clock.Timer.Reset, which may be // called by any Timer backed by this Clock. func (clock *Clock) stop(t *timer) bool { clock.mu.Lock() defer clock.mu.Unlock() for i, wt := range clock.waiting { if wt == t { clock.waiting = removeFromSlice(clock.waiting, i) return true } } return false } // addTimer adds an alarm at time t. func (clock *Clock) addTimer(t *timer) { clock.waiting = append(clock.waiting, t) sort.Sort(byDeadline(clock.waiting)) } // notifyAlarm sends a value on the channel exposed by Alarms(). func (clock *Clock) notifyAlarm() { select { case clock.notifyAlarms <- struct{}{}: default: panic("alarm notification buffer full") } } // byDeadline is used to sort alarms by time. type byDeadline []*timer func (a byDeadline) Len() int { return len(a) } func (a byDeadline) Less(i, j int) bool { return a[i].deadline.Before(a[j].deadline) } func (a byDeadline) Swap(i, j int) { a[i], a[j] = a[j], a[i] } // removeFromSlice removes item at the specified index from the slice. func removeFromSlice(sl []*timer, index int) []*timer { return append(sl[:index], sl[index+1:]...) } // AutoAdvancingClock wraps a clock.Clock, calling the Advance // function whenever After or AfterFunc are called. type AutoAdvancingClock struct { clock.Clock Advance func(time.Duration) } func (c *AutoAdvancingClock) After(d time.Duration) <-chan time.Time { ch := c.Clock.After(d) c.Advance(d) return ch } func (c *AutoAdvancingClock) AfterFunc(d time.Duration, f func()) clock.Timer { t := c.Clock.AfterFunc(d, f) c.Advance(d) return t } clock-1.0.3/testclock/clock_test.go000066400000000000000000000167101436242064000172700ustar00rootroot00000000000000// Copyright 2016 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package testclock_test import ( "sync" "time" "github.com/juju/loggo" "github.com/juju/testing" jc "github.com/juju/testing/checkers" gc "gopkg.in/check.v1" "github.com/juju/clock/testclock" ) type clockSuite struct { testing.LoggingSuite } var _ = gc.Suite(&clockSuite{}) func (*clockSuite) TestNow(c *gc.C) { t0 := time.Now() cl := testclock.NewClock(t0) c.Assert(cl.Now(), gc.Equals, t0) } func (*clockSuite) TestAdvanceLogs(c *gc.C) { loggo.GetLogger("juju.clock").SetLogLevel(loggo.DEBUG) t0 := time.Now() cl := testclock.NewClock(t0) // Shouldn't log anything. t := cl.After(time.Second) cl.Advance(time.Minute) <-t c.Check(c.GetTestLog(), jc.DeepEquals, "") // Should log since nothing's waiting. cl.Advance(time.Hour) c.Check(c.GetTestLog(), jc.Contains, "advancing a clock that has nothing waiting: cf. https://github.com/juju/juju/wiki/Intermittent-failures") } func (*clockSuite) TestWaitAdvance(c *gc.C) { t0 := time.Now() cl := testclock.NewClock(t0) // It is legal to just say 'nothing is waiting' err := cl.WaitAdvance(0, 0, 0) c.Check(err, jc.ErrorIsNil) // Test that no timers errors out. err = cl.WaitAdvance(time.Millisecond, 10*time.Millisecond, 1) c.Check(err, gc.ErrorMatches, "got 0 timers added after waiting 10ms: wanted 1, stacks:\n") // Test that a timer doesn't error. _ = cl.After(time.Nanosecond) err = cl.WaitAdvance(time.Millisecond, 10*time.Millisecond, 1) c.Check(err, jc.ErrorIsNil) } func (*clockSuite) TestAdvanceWithAfter(c *gc.C) { t0 := time.Now() cl := testclock.NewClock(t0) ch := cl.After(time.Second) select { case <-ch: c.Fatalf("received unexpected event") case <-time.After(shortWait): } cl.Advance(time.Second - 1) select { case <-ch: c.Fatalf("received unexpected event") case <-time.After(shortWait): } cl.Advance(1) select { case <-ch: case <-time.After(longWait): c.Fatalf("expected event to be triggered") } cl.Advance(time.Second) select { case <-ch: c.Fatalf("received unexpected event") case <-time.After(shortWait): } // Test that we can do it again ch = cl.After(time.Second) cl.Advance(2 * time.Second) select { case <-ch: case <-time.After(longWait): c.Fatalf("expected event to be triggered") } c.Assert(cl.Now().UTC(), gc.Equals, t0.Add(4*time.Second).UTC()) } func (*clockSuite) TestAdvanceWithAfterFunc(c *gc.C) { // Most of the details have been checked in TestAdvanceWithAfter, // so just check that AfterFunc is wired up correctly. t0 := time.Now() cl := testclock.NewClock(t0) fired := make(chan struct{}) cl.AfterFunc(time.Second, func() { close(fired) }) cl.Advance(2 * time.Second) select { case <-fired: case <-time.After(longWait): c.Fatalf("expected event to be triggered") } } func (*clockSuite) TestAfterFuncStop(c *gc.C) { t0 := time.Now() cl := testclock.NewClock(t0) fired := make(chan struct{}) timer := cl.AfterFunc(time.Second, func() { close(fired) }) cl.Advance(50 * time.Millisecond) timer.Stop() select { case <-fired: c.Fatalf("received unexpected event") case <-time.After(shortWait): } } func (*clockSuite) TestNewTimerReset(c *gc.C) { t0 := time.Now() cl := testclock.NewClock(t0) timer := cl.NewTimer(time.Second) cl.Advance(time.Second) select { case t := <-timer.Chan(): c.Assert(t.UTC(), gc.Equals, t0.Add(time.Second).UTC()) case <-time.After(longWait): c.Fatalf("expected event to be triggered") } timer.Reset(50 * time.Millisecond) cl.Advance(100 * time.Millisecond) select { case t := <-timer.Chan(): c.Assert(t.UTC(), gc.Equals, t0.Add(time.Second+100*time.Millisecond).UTC()) case <-time.After(longWait): c.Fatalf("expected event to be triggered") } } func (*clockSuite) TestNewTimerAsyncReset(c *gc.C) { t0 := time.Now() clock := testclock.NewClock(t0) timer := clock.NewTimer(time.Hour) stop := make(chan struct{}) stopped := make(chan struct{}) var wg sync.WaitGroup wg.Add(1) go func() { defer wg.Done() select { case <-stop: case t := <-timer.Chan(): c.Errorf("timer accidentally ticked at: %v", t) case <-time.After(longWait): c.Errorf("test took too long") } close(stopped) }() // Just our goroutine, but we don't go so far as to trigger the wakeup. clock.WaitAdvance(1*time.Minute, 10*time.Millisecond, 1) // Reset shouldn't trigger a wakeup, just move when it thinks it will wake up. timer.Reset(time.Hour) clock.WaitAdvance(1*time.Minute, 10*time.Millisecond, 1) timer.Reset(time.Minute) clock.WaitAdvance(30*time.Second, 10*time.Millisecond, 1) // Now tell the goroutine to stop and start another one that *does* want to // wake up close(stop) select { case <-stopped: case <-time.After(longWait): c.Errorf("goroutine failed to stop") } wg.Add(1) go func() { defer wg.Done() select { case t := <-timer.Chan(): c.Logf("timer successfully ticked: %v", t) case <-time.After(longWait): c.Errorf("timer took too long") } }() // And advance the clock long enough to cause it to notice clock.WaitAdvance(30*time.Second, 10*time.Millisecond, 1) wg.Wait() } func (*clockSuite) TestNewTimerResetCausesWakeup(c *gc.C) { t0 := time.Now() clock := testclock.NewClock(t0) timer1 := clock.NewTimer(time.Hour) timer2 := clock.NewTimer(time.Hour) timer3 := clock.NewTimer(time.Hour) var wg sync.WaitGroup wg.Add(1) go func() { defer wg.Done() select { case t := <-timer1.Chan(): c.Check(t0, gc.Equals, t) case <-time.After(longWait): c.Errorf("timer1 took too long to wake up") } }() wg.Add(1) go func() { defer wg.Done() select { case <-timer2.Chan(): c.Errorf("timer2 should not wake up") case <-time.After(shortWait): c.Logf("timer2 succesfully slept for 50ms") } }() wg.Add(1) go func() { defer wg.Done() select { case t := <-timer3.Chan(): // Even though the reset was negative, it triggers at 'now' c.Check(t0, gc.Equals, t) case <-time.After(longWait): c.Errorf("timer3 took too long to wake up") } }() // Reseting the timer to a time <= 0 should cause it to wake up on its // own, without needing an Advance or WaitAdvance to be done timer1.Reset(0) timer3.Reset(-1 * time.Second) wg.Wait() } func (*clockSuite) TestMultipleWaiters(c *gc.C) { var wg sync.WaitGroup t0 := time.Date(2000, 01, 01, 01, 0, 0, 0, time.UTC) cl := testclock.NewClock(t0) total := 0 start := func(f func()) { total++ wg.Add(1) go func() { defer wg.Done() f() }() } start(func() { <-cl.After(50 * time.Millisecond) }) start(func() { ch := make(chan struct{}) cl.AfterFunc(100*time.Millisecond, func() { close(ch) }) <-ch }) start(func() { timer := cl.NewTimer(150 * time.Millisecond) <-timer.Chan() timer.Reset(50 * time.Millisecond) <-timer.Chan() }) done := make(chan struct{}) go func() { wg.Wait() close(done) }() // Wait for all the alarms to be waited on. for i := 0; i < total; i++ { select { case <-cl.Alarms(): case <-time.After(longWait): c.Fatalf("expected a notification on the alarms channel") } } select { case <-cl.Alarms(): c.Fatalf("unexpected extra notification on alarms channel") case <-time.After(shortWait): } cl.Advance(150 * time.Millisecond) // Wait for the extra notification after reset. select { case <-cl.Alarms(): case <-time.After(longWait): c.Fatalf("expected a notification on the alarms channel") } cl.Advance(50 * time.Millisecond) select { case <-done: case <-time.After(longWait): c.Fatalf("expected all waits to complete") } } clock-1.0.3/testclock/dilated.go000066400000000000000000000132601436242064000165410ustar00rootroot00000000000000// Copyright 2022 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package testclock import ( "sync" "sync/atomic" "time" "github.com/juju/clock" ) // NewDilatedWallClock returns a clock that can be sped up or slowed down. // realSecondDuration is the real duration of a second. func NewDilatedWallClock(realSecondDuration time.Duration) AdvanceableClock { dc := &dilationClock{ epoch: time.Now(), realSecondDuration: realSecondDuration, offsetChanged: make(chan any), } dc.offsetChangedCond = sync.NewCond(dc.offsetChangedMutex.RLocker()) return dc } type dilationClock struct { epoch time.Time realSecondDuration time.Duration // offsetAtomic is the current dilated offset to allow for time jumps/advances. offsetAtomic int64 // offsetChanged is a channel that is closed when timers need to be signaled // that there is a offset change coming. offsetChanged chan any // offsetChangedMutex is a mutex protecting the offsetChanged and is used by // the offsetChangedCond. offsetChangedMutex sync.RWMutex // offsetChangedCond is used to signal timers that they may try to pull the new // offset. offsetChangedCond *sync.Cond } // Now is part of the Clock interface. func (dc *dilationClock) Now() time.Time { dt, _ := dc.nowWithOffset() return dt } func (dc *dilationClock) nowWithOffset() (time.Time, time.Duration) { offset := time.Duration(atomic.LoadInt64(&dc.offsetAtomic)) realNow := time.Now() dt := dilateTime(dc.epoch, realNow, dc.realSecondDuration, offset) return dt, offset } // After implements Clock.After func (dc *dilationClock) After(d time.Duration) <-chan time.Time { t := newDilatedWallTimer(dc, d, nil) return t.c } // AfterFunc implements Clock.AfterFunc func (dc *dilationClock) AfterFunc(d time.Duration, f func()) clock.Timer { return newDilatedWallTimer(dc, d, f) } // NewTimer implements Clock.NewTimer func (dc *dilationClock) NewTimer(d time.Duration) clock.Timer { return newDilatedWallTimer(dc, d, nil) } // Advance implements AdvanceableClock.Advance func (dc *dilationClock) Advance(d time.Duration) { close(dc.offsetChanged) dc.offsetChangedMutex.Lock() dc.offsetChanged = make(chan any) atomic.AddInt64(&dc.offsetAtomic, int64(d)) dc.offsetChangedCond.Broadcast() dc.offsetChangedMutex.Unlock() } // dilatedWallTimer implements the Timer interface. type dilatedWallTimer struct { timer *time.Timer dc *dilationClock c chan time.Time target time.Time offset time.Duration after func() done chan any resetChan chan resetReq resetMutex sync.Mutex stopChan chan chan bool } type resetReq struct { d time.Duration r chan bool } func newDilatedWallTimer(dc *dilationClock, d time.Duration, after func()) *dilatedWallTimer { t := &dilatedWallTimer{ dc: dc, c: make(chan time.Time), resetChan: make(chan resetReq), stopChan: make(chan chan bool), } t.start(d, after) return t } func (t *dilatedWallTimer) start(d time.Duration, after func()) { t.dc.offsetChangedMutex.RLock() dialatedNow, offset := t.dc.nowWithOffset() realDuration := time.Duration(float64(d) * t.dc.realSecondDuration.Seconds()) t.target = dialatedNow.Add(d) t.timer = time.NewTimer(realDuration) t.offset = offset t.after = after t.done = make(chan any) go t.run() } func (t *dilatedWallTimer) run() { defer t.dc.offsetChangedMutex.RUnlock() defer close(t.done) var sendChan chan time.Time var sendTime time.Time for { select { case reset := <-t.resetChan: realNow := time.Now() dialatedNow := dilateTime(t.dc.epoch, realNow, t.dc.realSecondDuration, t.offset) realDuration := time.Duration(float64(reset.d) * t.dc.realSecondDuration.Seconds()) t.target = dialatedNow.Add(reset.d) sendChan = nil sendTime = time.Time{} reset.r <- t.timer.Reset(realDuration) case stop := <-t.stopChan: stop <- t.timer.Stop() return case tt := <-t.timer.C: if t.after != nil { t.after() return } if sendChan != nil { panic("reset should have been called") } sendChan = t.c sendTime = dilateTime(t.dc.epoch, tt, t.dc.realSecondDuration, t.offset) case sendChan <- sendTime: sendChan = nil sendTime = time.Time{} return case <-t.dc.offsetChanged: t.dc.offsetChangedCond.Wait() newOffset := time.Duration(atomic.LoadInt64(&t.dc.offsetAtomic)) if newOffset == t.offset { continue } t.offset = newOffset stopped := t.timer.Stop() if !stopped { continue } realNow := time.Now() dialatedNow := dilateTime(t.dc.epoch, realNow, t.dc.realSecondDuration, t.offset) dialatedDuration := t.target.Sub(dialatedNow) if dialatedDuration <= 0 { sendChan = t.c sendTime = dialatedNow continue } realDuration := time.Duration(float64(dialatedDuration) * t.dc.realSecondDuration.Seconds()) t.timer.Reset(realDuration) } } } // Chan implements Timer.Chan func (t *dilatedWallTimer) Chan() <-chan time.Time { return t.c } // Chan implements Timer.Reset func (t *dilatedWallTimer) Reset(d time.Duration) bool { t.resetMutex.Lock() defer t.resetMutex.Unlock() reset := resetReq{ d: d, r: make(chan bool), } select { case <-t.done: t.start(d, nil) return true case t.resetChan <- reset: return <-reset.r } } // Chan implements Timer.Stop func (t *dilatedWallTimer) Stop() bool { stop := make(chan bool) select { case <-t.done: return false case t.stopChan <- stop: return <-stop } } func dilateTime(epoch, realNow time.Time, realSecondDuration, dilatedOffset time.Duration) time.Time { delta := realNow.Sub(epoch) if delta < 0 { delta = time.Duration(0) } return epoch.Add(dilatedOffset).Add(time.Duration(float64(delta) / realSecondDuration.Seconds())) } clock-1.0.3/testclock/dilated_test.go000066400000000000000000000165051436242064000176050ustar00rootroot00000000000000// Copyright 2022 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package testclock_test import ( "math/rand" "runtime" "sync" "time" "github.com/juju/clock" "github.com/juju/testing" jc "github.com/juju/testing/checkers" gc "gopkg.in/check.v1" "github.com/juju/clock/testclock" ) const ( halfSecond = 500 * time.Millisecond doubleSecond = 2 * time.Second ) type dilatedClockSuite struct { testing.LoggingSuite } var _ = gc.Suite(&dilatedClockSuite{}) func (*dilatedClockSuite) TestSlowedAfter(c *gc.C) { cl := testclock.NewDilatedWallClock(doubleSecond) t0 := time.Now() d0 := cl.Now() d1 := <-cl.After(time.Second) t1 := time.Now() c.Assert(t1.Sub(t0).Seconds(), jc.GreaterThan, 1.9) c.Assert(d1.Sub(d0).Seconds(), jc.GreaterThan, 0.9) c.Assert(d1.Sub(d0).Seconds(), jc.LessThan, 1.1) } func (*dilatedClockSuite) TestFastAfter(c *gc.C) { cl := testclock.NewDilatedWallClock(halfSecond) t0 := time.Now() d0 := cl.Now() d1 := <-cl.After(time.Second) t1 := time.Now() c.Assert(t1.Sub(t0).Milliseconds(), jc.LessThan, 600) c.Assert(d1.Sub(d0).Milliseconds(), jc.GreaterThan, 990) c.Assert(d1.Sub(d0).Milliseconds(), jc.LessThan, 1010) } func (*dilatedClockSuite) TestSlowedAfterFunc(c *gc.C) { t0 := time.Now() cl := testclock.NewDilatedWallClock(doubleSecond) mut := sync.Mutex{} mut.Lock() cl.AfterFunc(time.Second, func() { defer mut.Unlock() c.Check(time.Since(t0).Seconds(), jc.GreaterThan, 1.9) }) mut.Lock() } func (*dilatedClockSuite) TestFastAfterFunc(c *gc.C) { t0 := time.Now() cl := testclock.NewDilatedWallClock(halfSecond) mut := sync.Mutex{} mut.Lock() cl.AfterFunc(time.Second, func() { defer mut.Unlock() c.Check(time.Since(t0).Milliseconds(), jc.LessThan, 600) }) mut.Lock() } func (*dilatedClockSuite) TestSlowedNow(c *gc.C) { t0 := time.Now() cl := testclock.NewDilatedWallClock(doubleSecond) <-time.After(time.Second) t2 := cl.Now() c.Assert(t2.Sub(t0).Milliseconds(), jc.GreaterThan, 400) c.Assert(t2.Sub(t0).Milliseconds(), jc.LessThan, 600) <-time.After(time.Second) t3 := cl.Now() c.Assert(t3.Sub(t0).Milliseconds(), jc.GreaterThan, 900) c.Assert(t3.Sub(t0).Milliseconds(), jc.LessThan, 1100) } func (*dilatedClockSuite) TestFastNow(c *gc.C) { t0 := time.Now() cl := testclock.NewDilatedWallClock(halfSecond) <-time.After(time.Second) t2 := cl.Now() c.Assert(t2.Sub(t0).Milliseconds(), jc.GreaterThan, 1900) c.Assert(t2.Sub(t0).Milliseconds(), jc.LessThan, 2100) <-time.After(time.Second) t3 := cl.Now() c.Assert(t3.Sub(t0).Milliseconds(), jc.GreaterThan, 3900) c.Assert(t3.Sub(t0).Milliseconds(), jc.LessThan, 4100) } func (*dilatedClockSuite) TestAdvance(c *gc.C) { t0 := time.Now() cl := testclock.NewDilatedWallClock(halfSecond) first := cl.After(time.Second) cl.Advance(halfSecond) <-time.After(250 * time.Millisecond) select { case t := <-first: c.Assert(t.Sub(t0).Milliseconds(), jc.GreaterThan, 249) case <-time.After(shortWait): c.Fatal("timer failed to trigger early") } } func (*dilatedClockSuite) TestAdvanceMulti(c *gc.C) { cl := testclock.NewDilatedWallClock(halfSecond) first := cl.After(time.Second) second := cl.After(2 * time.Second) third := cl.After(1 * time.Hour) done := time.After(longWait) fourth := cl.After(12*time.Hour + longWait*2 + time.Second) cl.Advance(12 * time.Hour) n := 0 out: for { select { case <-first: n++ case <-second: n++ case <-third: n++ case <-fourth: c.Fatal("timer that fired that should not have") case <-done: break out } } c.Assert(n, gc.Equals, 3) } func (*dilatedClockSuite) TestStop(c *gc.C) { numGo := runtime.NumGoroutine() cl := testclock.NewDilatedWallClock(halfSecond) a := cl.NewTimer(time.Second) time.Sleep(shortWait) ok := a.Stop() c.Assert(ok, jc.IsTrue) ok = a.Stop() c.Assert(ok, jc.IsFalse) select { case <-a.Chan(): c.Fatal("stopped clock fired") case <-time.After(time.Second): } for i := 0; i < 3; i++ { if runtime.NumGoroutine() == numGo { break } time.Sleep(shortWait) } c.Assert(runtime.NumGoroutine(), gc.Equals, numGo, gc.Commentf("clock goroutine still running")) } func (*dilatedClockSuite) TestReset(c *gc.C) { numGo := runtime.NumGoroutine() cl := testclock.NewDilatedWallClock(halfSecond) a := cl.NewTimer(time.Second) time.Sleep(250 * time.Millisecond) ok := a.Reset(time.Second) c.Assert(ok, jc.IsTrue) <-time.After(halfSecond) select { case <-a.Chan(): case <-time.After(shortWait): c.Fatal("timer did not fire") } for i := 0; i < 3; i++ { if runtime.NumGoroutine() == numGo { break } time.Sleep(shortWait) } c.Assert(runtime.NumGoroutine(), gc.Equals, numGo, gc.Commentf("clock goroutine still running")) } func (*dilatedClockSuite) TestStopReset(c *gc.C) { numGo := runtime.NumGoroutine() cl := testclock.NewDilatedWallClock(halfSecond) a := cl.NewTimer(time.Second) time.Sleep(250 * time.Millisecond) ok := a.Stop() c.Assert(ok, jc.IsTrue) ok = a.Reset(time.Second) c.Assert(ok, jc.IsTrue) <-time.After(halfSecond) select { case <-a.Chan(): case <-time.After(shortWait): c.Fatal("timer did not fire") } for i := 0; i < 3; i++ { if runtime.NumGoroutine() == numGo { break } time.Sleep(shortWait) } c.Assert(runtime.NumGoroutine(), gc.Equals, numGo, gc.Commentf("clock goroutine still running")) } func (*dilatedClockSuite) TestAdvanceAlreadyFired(c *gc.C) { numGo := runtime.NumGoroutine() cl := testclock.NewDilatedWallClock(time.Second) t := cl.NewTimer(time.Millisecond) time.Sleep(shortWait) cl.Advance(time.Second) select { case <-t.Chan(): case <-time.After(shortWait): c.Fatal("timer did not fire") } for i := 0; i < 3; i++ { if runtime.NumGoroutine() == numGo { break } time.Sleep(shortWait) } c.Assert(runtime.NumGoroutine(), gc.Equals, numGo, gc.Commentf("clock goroutine still running")) } func (*dilatedClockSuite) TestAdvanceFast(c *gc.C) { cl := testclock.NewDilatedWallClock(time.Minute) timers := make([]clock.Timer, 0, 1000) for i := time.Millisecond; i <= time.Second; i += time.Millisecond { timers = append(timers, cl.NewTimer(i)) } for i := 0; i < 10000; i++ { cl.Advance(100 * time.Microsecond) } deadline := time.After(10 * time.Second) for _, timer := range timers { select { case <-timer.Chan(): case <-deadline: c.Fatal("timer did not fire by deadline") } } } func (*dilatedClockSuite) TestAdvanceReset(c *gc.C) { cl := testclock.NewDilatedWallClock(time.Minute) timers := make([]clock.Timer, 0, 10) for i := 0; i < 10; i++ { timers = append(timers, cl.NewTimer(time.Millisecond)) } deadline := time.After(10 * time.Second) for i := 0; i < 1000; i++ { cl.Advance(time.Millisecond) for _, timer := range timers { select { case <-timer.Chan(): case <-deadline: c.Fatal("timer did not fire by deadline") } timer.Reset(time.Millisecond) } } } func (*dilatedClockSuite) TestAdvanceResetRacey(c *gc.C) { cl := testclock.NewDilatedWallClock(time.Second) timers := make([]clock.Timer, 0, 10) for i := 0; i < 10; i++ { timers = append(timers, cl.NewTimer(time.Millisecond)) } deadline := time.After(2 * time.Second) for i := 0; i < 1000; i++ { time.Sleep(999 * time.Microsecond) cl.Advance(time.Microsecond * time.Duration(rand.Intn(2))) for _, timer := range timers { select { case <-timer.Chan(): case <-deadline: c.Fatal("timer did not fire by deadline") } timer.Reset(time.Millisecond) } } } clock-1.0.3/testclock/interfaces.go000066400000000000000000000005431436242064000172560ustar00rootroot00000000000000// Copyright 2022 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package testclock import ( "time" "github.com/juju/clock" ) // AdvanceableClock is a clock that can be advanced to trigger timers/trigger timers earlier // than they would otherwise. type AdvanceableClock interface { clock.Clock Advance(time.Duration) } clock-1.0.3/testclock/package_test.go000066400000000000000000000004601436242064000175630ustar00rootroot00000000000000// Copyright 2022 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package testclock_test import ( gotesting "testing" "time" gc "gopkg.in/check.v1" ) func TestAll(t *gotesting.T) { gc.TestingT(t) } const ( shortWait = 50 * time.Millisecond longWait = time.Second ) clock-1.0.3/wall.go000066400000000000000000000020451436242064000140760ustar00rootroot00000000000000// Copyright 2015 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package clock import ( "time" ) // WallClock exposes wall-clock time via the Clock interface. var WallClock wallClock // ensure that WallClock does actually implement the Clock interface. var _ Clock = WallClock // WallClock exposes wall-clock time as returned by time.Now. type wallClock struct{} // Now is part of the Clock interface. func (wallClock) Now() time.Time { return time.Now() } // After implements Clock.After. func (wallClock) After(d time.Duration) <-chan time.Time { return time.After(d) } // AfterFunc implements Clock.AfterFunc. func (wallClock) AfterFunc(d time.Duration, f func()) Timer { return wallTimer{time.AfterFunc(d, f)} } // NewTimer implements Clock.NewTimer. func (wallClock) NewTimer(d time.Duration) Timer { return wallTimer{time.NewTimer(d)} } // wallTimer implements the Timer interface. type wallTimer struct { *time.Timer } // Chan implements Timer.Chan. func (t wallTimer) Chan() <-chan time.Time { return t.C }