jenkins-bot has submitted this change and it was merged.
Change subject: Add wikimedia/wait-condition-loop v1.0.1
......................................................................
Add wikimedia/wait-condition-loop v1.0.1
Bug: T146256
Change-Id: Ia84774d83da79fea1e167fe065c69549981f753b
---
M composer.json
M composer.lock
M composer/autoload_classmap.php
M composer/installed.json
A wikimedia/wait-condition-loop/COPYING
A wikimedia/wait-condition-loop/README.md
A wikimedia/wait-condition-loop/src/WaitConditionLoop.php
7 files changed, 678 insertions(+), 2 deletions(-)
Approvals:
Reedy: Looks good to me, approved
jenkins-bot: Verified
diff --git a/composer.json b/composer.json
index 62a5d31..34f1ffa 100644
--- a/composer.json
+++ b/composer.json
@@ -45,6 +45,7 @@
"wikimedia/scoped-callback": "1.0.0",
"wikimedia/textcat": "1.1.3",
"wikimedia/utfnormal": "1.0.3",
+ "wikimedia/wait-condition-loop": "1.0.1",
"wikimedia/wrappedstring": "2.2.0",
"zordius/lightncandy": "0.23"
}
diff --git a/composer.lock b/composer.lock
index fc3258b..05d57b9 100644
--- a/composer.lock
+++ b/composer.lock
@@ -4,8 +4,8 @@
"Read more about it at
https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
"This file is @generated automatically"
],
- "hash": "8c8277395b9ae35379e68a698fd79f14",
- "content-hash": "6a30e5373c319d134704ebae9e2c7236",
+ "hash": "eb48dbe45827add41f49b7253513f912",
+ "content-hash": "d685c97157a41f98d586a2fd7df50044",
"packages": [
{
"name": "composer/semver",
@@ -1770,6 +1770,48 @@
"time": "2015-08-29 14:13:27"
},
{
+ "name": "wikimedia/wait-condition-loop",
+ "version": "v1.0.1",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/wikimedia/WaitConditionLoop.git",
+ "reference": "0321b8ca6a0f701f96e04e5e8e6d3e244ab05338"
+ },
+ "dist": {
+ "type": "zip",
+ "url":
"https://api.github.com/repos/wikimedia/WaitConditionLoop/zipball/0321b8ca6a0f701f96e04e5e8e6d3e244ab05338",
+ "reference": "0321b8ca6a0f701f96e04e5e8e6d3e244ab05338",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=5.5.9"
+ },
+ "require-dev": {
+ "jakub-onderka/php-parallel-lint": "0.9.2",
+ "mediawiki/mediawiki-codesniffer": "0.7.2",
+ "phpunit/phpunit": "4.8.24"
+ },
+ "type": "library",
+ "autoload": {
+ "classmap": [
+ "src/"
+ ]
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "GPL-2.0+"
+ ],
+ "authors": [
+ {
+ "name": "Aaron Schulz",
+ "email": "[email protected]"
+ }
+ ],
+ "description": "Wait loop that reaches a condition or times out",
+ "homepage": "https://www.mediawiki.org/wiki/WaitConditionLoop",
+ "time": "2016-10-01 06:58:30"
+ },
+ {
"name": "wikimedia/wrappedstring",
"version": "v2.2.0",
"source": {
diff --git a/composer/autoload_classmap.php b/composer/autoload_classmap.php
index b834147..c279cff 100644
--- a/composer/autoload_classmap.php
+++ b/composer/autoload_classmap.php
@@ -632,6 +632,7 @@
'Wikimedia\\Composer\\Merge\\StabilityFlags' => $vendorDir .
'/wikimedia/composer-merge-plugin/src/Merge/StabilityFlags.php',
'Wikimedia\\PhpSessionSerializer' => $vendorDir .
'/wikimedia/php-session-serializer/src/Wikimedia/PhpSessionSerializer.php',
'Wikimedia\\ScopedCallback' => $vendorDir .
'/wikimedia/scoped-callback/src/ScopedCallback.php',
+ 'Wikimedia\\WaitConditionLoop' => $vendorDir .
'/wikimedia/wait-condition-loop/src/WaitConditionLoop.php',
'WrappedString\\WrappedString' => $vendorDir .
'/wikimedia/wrappedstring/src/WrappedString.php',
'WrappedString\\WrappedStringList' => $vendorDir .
'/wikimedia/wrappedstring/src/WrappedStringList.php',
'lessc' => $vendorDir . '/oyejorge/less.php/lessc.inc.php',
diff --git a/composer/installed.json b/composer/installed.json
index a05c19e..d565246 100644
--- a/composer/installed.json
+++ b/composer/installed.json
@@ -1923,5 +1923,49 @@
],
"description": "Class for asserting that a callback happens when a
dummy object leaves scope",
"homepage": "https://www.mediawiki.org/wiki/ScopedCallback"
+ },
+ {
+ "name": "wikimedia/wait-condition-loop",
+ "version": "v1.0.1",
+ "version_normalized": "1.0.1.0",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/wikimedia/WaitConditionLoop.git",
+ "reference": "0321b8ca6a0f701f96e04e5e8e6d3e244ab05338"
+ },
+ "dist": {
+ "type": "zip",
+ "url":
"https://api.github.com/repos/wikimedia/WaitConditionLoop/zipball/0321b8ca6a0f701f96e04e5e8e6d3e244ab05338",
+ "reference": "0321b8ca6a0f701f96e04e5e8e6d3e244ab05338",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=5.5.9"
+ },
+ "require-dev": {
+ "jakub-onderka/php-parallel-lint": "0.9.2",
+ "mediawiki/mediawiki-codesniffer": "0.7.2",
+ "phpunit/phpunit": "4.8.24"
+ },
+ "time": "2016-10-01 06:58:30",
+ "type": "library",
+ "installation-source": "dist",
+ "autoload": {
+ "classmap": [
+ "src/"
+ ]
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "GPL-2.0+"
+ ],
+ "authors": [
+ {
+ "name": "Aaron Schulz",
+ "email": "[email protected]"
+ }
+ ],
+ "description": "Wait loop that reaches a condition or times out",
+ "homepage": "https://www.mediawiki.org/wiki/WaitConditionLoop"
}
]
diff --git a/wikimedia/wait-condition-loop/COPYING
b/wikimedia/wait-condition-loop/COPYING
new file mode 100644
index 0000000..d159169
--- /dev/null
+++ b/wikimedia/wait-condition-loop/COPYING
@@ -0,0 +1,339 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users. This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it. (Some other Free Software Foundation software is covered by
+the GNU Lesser General Public License instead.) You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+ To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have. You must make sure that they, too, receive or can get the
+source code. And you must show them these terms so they know their
+rights.
+
+ We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+ Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software. If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+ Finally, any free program is threatened constantly by software
+patents. We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary. To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ GNU GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License. The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language. (Hereinafter, translation is included without limitation in
+the term "modification".) Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+ 1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+ 2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) You must cause the modified files to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ b) You must cause any work that you distribute or publish, that in
+ whole or in part contains or is derived from the Program or any
+ part thereof, to be licensed as a whole at no charge to all third
+ parties under the terms of this License.
+
+ c) If the modified program normally reads commands interactively
+ when run, you must cause it, when started running for such
+ interactive use in the most ordinary way, to print or display an
+ announcement including an appropriate copyright notice and a
+ notice that there is no warranty (or else, saying that you provide
+ a warranty) and that users may redistribute the program under
+ these conditions, and telling the user how to view a copy of this
+ License. (Exception: if the Program itself is interactive but
+ does not normally print such an announcement, your work based on
+ the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+ a) Accompany it with the complete corresponding machine-readable
+ source code, which must be distributed under the terms of Sections
+ 1 and 2 above on a medium customarily used for software interchange; or,
+
+ b) Accompany it with a written offer, valid for at least three
+ years, to give any third party, for a charge no more than your
+ cost of physically performing source distribution, a complete
+ machine-readable copy of the corresponding source code, to be
+ distributed under the terms of Sections 1 and 2 above on a medium
+ customarily used for software interchange; or,
+
+ c) Accompany it with the information you received as to the offer
+ to distribute corresponding source code. (This alternative is
+ allowed only for noncommercial distribution and only if you
+ received the program in object code or executable form with such
+ an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it. For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable. However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License. Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+ 5. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Program or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+ 6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+ 7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all. For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded. In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+ 9. The Free Software Foundation may publish revised and/or new versions
+of the 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 Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation. If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+ 10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission. For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this. Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+ NO WARRANTY
+
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License along
+ with this program; if not, write to the Free Software Foundation, Inc.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+ Gnomovision version 69, Copyright (C) year name of author
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+ `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+ <signature of Ty Coon>, 1 April 1989
+ Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs. If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.
diff --git a/wikimedia/wait-condition-loop/README.md
b/wikimedia/wait-condition-loop/README.md
new file mode 100644
index 0000000..0c05686
--- /dev/null
+++ b/wikimedia/wait-condition-loop/README.md
@@ -0,0 +1,60 @@
+[![Latest Stable
Version]](https://packagist.org/packages/wikimedia/wait-condition-loop)
[![License]](https://packagist.org/packages/wikimedia/wait-condition-loop)
+
+Wait Condition Loop for PHP
+===========================
+
+This class is used for waiting on a condition to be reached, with the ability
+to specify a timeout. The condition is considered reached when the condition
callback
+returns CONDITION_REACHED or true. CONDITION_ABORTED can also be used to stop
the loop.
+
+Additionally, "work" callbacks can be injected to prepare useful work instead
of simply
+having the current thread sleep or block on I/O. The loop will run one of
these callbacks
+on each iteration of checking the condition callback, as long as there are any
left to run.
+
+The loop class will automatically either retry the condition or usleep()
before retrying it,
+depending on CPU usage. Low CPU usage and significant real-time passage is
used to detect
+whether the condition callback appears to use blocking I/O. Use of usleep()
will not occur
+until all of the "work" callbacks have run. This means that the condition
callback can
+either be an "instant" CPU-bound check or a blocking I/O call with a small
timeout. Both
+cases should automatically work without CPU intensive spin loops.
+
+Additional documentation about the library can be found on
+[MediaWiki.org](https://www.mediawiki.org/wiki/WaitConditionLoop).
+
+
+Usage
+-----
+ // Pre-compute some value that will be needed later
+ $result = null;
+ $workCallback = function () use ( &$result ) {
+ $result = ( $result !== null ) ? $result : $this->doWork();
+
+ return $result
+ }
+
+ $loop = new WaitConditionLoop(
+ function () use ( ... ) {
+ if ( ... ) {
+ // Condition reached; stop loop
+ return WaitConditionLoop::CONDITION_REACHED;
+ }
+ // Condition not reached; keep checking
+ return WaitConditionLoop::CONDITION_CONTINUE;
+ },
+ 3.0, // timeout in seconds
+ [ $workCallback ]
+ );
+ $status = $loop->invoke(); // CONDITION_* constant
+
+ // Call $workCallback as needed later
+
+Running tests
+-------------
+
+ composer install --prefer-dist
+ composer test
+
+
+---
+[Latest Stable Version]:
https://poser.pugx.org/wikimedia/wait-condition-loop/v/stable.svg
+[License]: https://poser.pugx.org/wikimedia/wait-condition-loop/license.svg
diff --git a/wikimedia/wait-condition-loop/src/WaitConditionLoop.php
b/wikimedia/wait-condition-loop/src/WaitConditionLoop.php
new file mode 100644
index 0000000..583ebb3
--- /dev/null
+++ b/wikimedia/wait-condition-loop/src/WaitConditionLoop.php
@@ -0,0 +1,189 @@
+<?php
+/**
+ * Wait loop that reaches a condition or times out.
+ *
+ * Copyright (C) 2016 Aaron Schulz <[email protected]>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * http://www.gnu.org/copyleft/gpl.html
+ *
+ * @file
+ * @author Aaron Schulz
+ */
+
+namespace Wikimedia;
+
+/**
+ * Wait loop that reaches a condition or times out
+ */
+class WaitConditionLoop {
+ /** @var callable */
+ private $condition;
+ /** @var callable[] */
+ private $busyCallbacks = [];
+ /** @var float Seconds */
+ private $timeout;
+ /** @var float Seconds */
+ private $lastWaitTime;
+ /** @var integer|null */
+ private $rusageMode;
+
+ const CONDITION_REACHED = 1;
+ const CONDITION_CONTINUE = 0; // evaluates as falsey
+ const CONDITION_FAILED = -1;
+ const CONDITION_TIMED_OUT = -2;
+ const CONDITION_ABORTED = -3;
+
+ /**
+ * @param callable $condition Callback that returns a
WaitConditionLoop::CONDITION_ constant
+ * @param float $timeout Timeout in seconds
+ * @param array &$busyCallbacks List of callbacks to do useful work (by
reference)
+ */
+ public function __construct( callable $condition, $timeout = 5.0,
&$busyCallbacks = [] ) {
+ $this->condition = $condition;
+ $this->timeout = $timeout;
+ $this->busyCallbacks =& $busyCallbacks;
+
+ if ( defined( 'HHVM_VERSION' ) && PHP_OS === 'Linux' ) {
+ $this->rusageMode = 2; // RUSAGE_THREAD
+ } elseif ( function_exists( 'getrusage' ) ) {
+ $this->rusageMode = 0; // RUSAGE_SELF
+ }
+ }
+
+ /**
+ * Invoke the loop and continue until either:
+ * - a) The condition callback returns neither CONDITION_CONTINUE nor
false
+ * - b) The timeout is reached
+ * This a condition callback can return true (stop) or false (continue)
for convenience.
+ * In such cases, the halting result of "true" will be converted to
CONDITION_REACHED.
+ *
+ * If $timeout is 0, then only the condition callback will be called
(no busy callbacks),
+ * and this will immediately return CONDITION_FAILED if the condition
was not met.
+ *
+ * Exceptions in callbacks will be caught and the callback will be
swapped with
+ * one that simply rethrows that exception back to the caller when
invoked.
+ *
+ * @return integer WaitConditionLoop::CONDITION_* constant
+ * @throws \Exception Any error from the condition callback
+ */
+ public function invoke() {
+ $elapsed = 0.0; // seconds
+ $sleepUs = 0; // microseconds to sleep each time
+ $lastCheck = false;
+ $finalResult = self::CONDITION_TIMED_OUT;
+ do {
+ $checkStartTime = $this->getWallTime();
+ // Check if the condition is met yet
+ $realStart = $this->getWallTime();
+ $cpuStart = $this->getCpuTime();
+ $checkResult = call_user_func( $this->condition );
+ $cpu = $this->getCpuTime() - $cpuStart;
+ $real = $this->getWallTime() - $realStart;
+ // Exit if the condition is reached, an error occurs,
or this is non-blocking
+ if ( $this->timeout <= 0 ) {
+ $finalResult = $checkResult ?
self::CONDITION_REACHED : self::CONDITION_FAILED;
+ break;
+ } elseif ( (int)$checkResult !==
self::CONDITION_CONTINUE ) {
+ if ( is_int( $checkResult ) ) {
+ $finalResult = $checkResult;
+ } else {
+ $finalResult = self::CONDITION_REACHED;
+ }
+ break;
+ } elseif ( $lastCheck ) {
+ break; // timeout reached
+ }
+ // Detect if condition callback seems to block or if
justs burns CPU
+ $conditionUsesInterrupts = ( $real > 0.100 && $cpu <=
$real * .03 );
+ if ( !$this->popAndRunBusyCallback() &&
!$conditionUsesInterrupts ) {
+ // 10 queries = 10(10+100)/2 ms = 550ms, 14
queries = 1050ms
+ $sleepUs = min( $sleepUs + 10 * 1e3, 1e6 ); //
stop incrementing at ~1s
+ $this->usleep( $sleepUs );
+ }
+ $checkEndTime = $this->getWallTime();
+ // The max() protects against the clock getting set back
+ $elapsed += max( $checkEndTime - $checkStartTime, 0.010
);
+ // Do not let slow callbacks timeout without checking
the condition one more time
+ $lastCheck = ( $elapsed >= $this->timeout );
+ } while ( true );
+
+ $this->lastWaitTime = $elapsed;
+
+ return $finalResult;
+ }
+
+ /**
+ * @return float Seconds
+ */
+ public function getLastWaitTime() {
+ return $this->lastWaitTime;
+ }
+
+ /**
+ * @param integer $microseconds
+ */
+ protected function usleep( $microseconds ) {
+ usleep( $microseconds );
+ }
+
+ /**
+ * @return float
+ */
+ protected function getWallTime() {
+ return microtime( true );
+ }
+
+ /**
+ * @return float Returns 0.0 if not supported (Windows on PHP < 7)
+ */
+ protected function getCpuTime() {
+ if ( $this->rusageMode === null ) {
+ return microtime( true ); // assume worst case (all
time is CPU)
+ }
+
+ $ru = getrusage( $this->rusageMode );
+ $time = $ru['ru_utime.tv_sec'] + $ru['ru_utime.tv_usec'] / 1e6;
+ $time += $ru['ru_stime.tv_sec'] + $ru['ru_stime.tv_usec'] / 1e6;
+
+ return $time;
+ }
+
+ /**
+ * Run one of the callbacks that does work ahead of time for another
caller
+ *
+ * @return bool Whether a callback was executed
+ */
+ private function popAndRunBusyCallback() {
+ if ( $this->busyCallbacks ) {
+ reset( $this->busyCallbacks );
+ $key = key( $this->busyCallbacks );
+ /** @var callable $workCallback */
+ $workCallback =& $this->busyCallbacks[$key];
+ try {
+ $workCallback();
+ } catch ( \Exception $e ) {
+ $workCallback = function () use ( $e ) {
+ throw $e;
+ };
+ }
+ unset( $this->busyCallbacks[$key] ); // consume
+
+ return true;
+ }
+
+ return false;
+ }
+}
--
To view, visit https://gerrit.wikimedia.org/r/313646
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: merged
Gerrit-Change-Id: Ia84774d83da79fea1e167fe065c69549981f753b
Gerrit-PatchSet: 1
Gerrit-Project: mediawiki/vendor
Gerrit-Branch: master
Gerrit-Owner: Legoktm <[email protected]>
Gerrit-Reviewer: Aaron Schulz <[email protected]>
Gerrit-Reviewer: Reedy <[email protected]>
Gerrit-Reviewer: jenkins-bot <>
_______________________________________________
MediaWiki-commits mailing list
[email protected]
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits