Best Python code snippet using fMBT_python
reconnect.py
Source:reconnect.py
...226 self.backoff = 0227 def is_enabled(self):228 """Returns true if this FSM has been enabled with self.enable().229 Calling another function that indicates a change in connection state,230 such as self.disconnected() or self.force_reconnect(), will also enable231 a reconnect FSM."""232 return self.state != Reconnect.Void233 def enable(self, now):234 """If this FSM is disabled (the default for newly created FSMs),235 enables it, so that the next call to reconnect_run() for 'fsm' will236 return ovs.reconnect.CONNECT.237 If this FSM is not disabled, this function has no effect."""238 if self.state == Reconnect.Void and self.__may_retry():239 self._transition(now, Reconnect.Backoff)240 self.backoff = 0241 def disable(self, now):242 """Disables this FSM. Until 'fsm' is enabled again, self.run() will243 always return 0."""244 if self.state != Reconnect.Void:245 self._transition(now, Reconnect.Void)246 def force_reconnect(self, now):247 """If this FSM is enabled and currently connected (or attempting to248 connect), forces self.run() to return ovs.reconnect.DISCONNECT the next249 time it is called, which should cause the client to drop the connection250 (or attempt), back off, and then reconnect."""251 if self.state in (Reconnect.ConnectInProgress,252 Reconnect.Active,253 Reconnect.Idle):254 self._transition(now, Reconnect.Reconnect)255 def disconnected(self, now, error):256 """Tell this FSM that the connection dropped or that a connection257 attempt failed. 'error' specifies the reason: a positive value258 represents an errno value, EOF indicates that the connection was closed259 by the peer (e.g. read() returned 0), and 0 indicates no specific260 error....
websocket.js
Source:websocket.js
1// Copyright 2011 The Closure Library Authors. All Rights Reserved.2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7// http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS-IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.14/**15 * @fileoverview Definition of the WebSocket class. A WebSocket provides a16 * bi-directional, full-duplex communications channel, over a single TCP socket.17 *18 * See http://dev.w3.org/html5/websockets/19 * for the full HTML5 WebSocket API.20 *21 * Typical usage will look like this:22 *23 * var ws = new goog.net.WebSocket();24 *25 * var handler = new goog.events.EventHandler();26 * handler.listen(ws, goog.net.WebSocket.EventType.OPENED, onOpen);27 * handler.listen(ws, goog.net.WebSocket.EventType.MESSAGE, onMessage);28 *29 * try {30 * ws.open('ws://127.0.0.1:4200');31 * } catch (e) {32 * ...33 * }34 *35 */36goog.provide('goog.net.WebSocket');37goog.provide('goog.net.WebSocket.ErrorEvent');38goog.provide('goog.net.WebSocket.EventType');39goog.provide('goog.net.WebSocket.MessageEvent');40goog.require('goog.Timer');41goog.require('goog.asserts');42goog.require('goog.debug.Logger');43goog.require('goog.debug.entryPointRegistry');44goog.require('goog.events');45goog.require('goog.events.Event');46goog.require('goog.events.EventTarget');47/**48 * Class encapsulating the logic for using a WebSocket.49 *50 * @param {boolean=} opt_autoReconnect True if the web socket should51 * automatically reconnect or not. This is true by default.52 * @param {function(number):number=} opt_getNextReconnect A function for53 * obtaining the time until the next reconnect attempt. Given the reconnect54 * attempt count (which is a positive integer), the function should return a55 * positive integer representing the milliseconds to the next reconnect56 * attempt. The default function used is an exponential back-off. Note that57 * this function is never called if auto reconnect is disabled.58 * @constructor59 * @extends {goog.events.EventTarget}60 */61goog.net.WebSocket = function(opt_autoReconnect, opt_getNextReconnect) {62 goog.base(this);63 /**64 * True if the web socket should automatically reconnect or not.65 * @type {boolean}66 * @private67 */68 this.autoReconnect_ = goog.isDef(opt_autoReconnect) ?69 opt_autoReconnect : true;70 /**71 * A function for obtaining the time until the next reconnect attempt.72 * Given the reconnect attempt count (which is a positive integer), the73 * function should return a positive integer representing the milliseconds to74 * the next reconnect attempt.75 * @type {function(number):number}76 * @private77 */78 this.getNextReconnect_ = opt_getNextReconnect ||79 goog.net.WebSocket.EXPONENTIAL_BACKOFF_;80 /**81 * The time, in milliseconds, that must elapse before the next attempt to82 * reconnect.83 * @type {number}84 * @private85 */86 this.nextReconnect_ = this.getNextReconnect_(this.reconnectAttempt_);87};88goog.inherits(goog.net.WebSocket, goog.events.EventTarget);89/**90 * The actual web socket that will be used to send/receive messages.91 * @type {WebSocket}92 * @private93 */94goog.net.WebSocket.prototype.webSocket_ = null;95/**96 * The URL to which the web socket will connect.97 * @type {?string}98 * @private99 */100goog.net.WebSocket.prototype.url_ = null;101/**102 * The subprotocol name used when establishing the web socket connection.103 * @type {string|undefined}104 * @private105 */106goog.net.WebSocket.prototype.protocol_ = undefined;107/**108 * True if a call to the close callback is expected or not.109 * @type {boolean}110 * @private111 */112goog.net.WebSocket.prototype.closeExpected_ = false;113/**114 * Keeps track of the number of reconnect attempts made since the last115 * successful connection.116 * @type {number}117 * @private118 */119goog.net.WebSocket.prototype.reconnectAttempt_ = 0;120/**121 * The logger for this class.122 * @type {goog.debug.Logger}123 * @private124 */125goog.net.WebSocket.prototype.logger_ = goog.debug.Logger.getLogger(126 'goog.net.WebSocket');127/**128 * The events fired by the web socket.129 * @enum {string} The event types for the web socket.130 */131goog.net.WebSocket.EventType = {132 /**133 * Fired when an attempt to open the WebSocket fails or there is a connection134 * failure after a successful connection has been established.135 */136 CLOSED: goog.events.getUniqueId('closed'),137 /**138 * Fired when the WebSocket encounters an error.139 */140 ERROR: goog.events.getUniqueId('error'),141 /**142 * Fired when a new message arrives from the WebSocket.143 */144 MESSAGE: goog.events.getUniqueId('message'),145 /**146 * Fired when the WebSocket connection has been established.147 */148 OPENED: goog.events.getUniqueId('opened')149};150/**151 * The various states of the web socket.152 * @enum {number} The states of the web socket.153 * @private154 */155goog.net.WebSocket.ReadyState_ = {156 // This is the initial state during construction.157 CONNECTING: 0,158 // This is when the socket is actually open and ready for data.159 OPEN: 1,160 // This is when the socket is in the middle of a close handshake.161 // Note that this is a valid state even if the OPEN state was never achieved.162 CLOSING: 2,163 // This is when the socket is actually closed.164 CLOSED: 3165};166/**167 * The maximum amount of time between reconnect attempts for the exponential168 * back-off in milliseconds.169 * @type {number}170 * @private171 */172goog.net.WebSocket.EXPONENTIAL_BACKOFF_CEILING_ = 60 * 1000;173/**174 * Computes the next reconnect time given the number of reconnect attempts since175 * the last successful connection.176 *177 * @param {number} attempt The number of reconnect attempts since the last178 * connection.179 * @return {number} The time, in milliseconds, until the next reconnect attempt.180 * @const181 * @private182 */183goog.net.WebSocket.EXPONENTIAL_BACKOFF_ = function(attempt) {184 var time = Math.pow(2, attempt) * 1000;185 return Math.min(time, goog.net.WebSocket.EXPONENTIAL_BACKOFF_CEILING_);186};187/**188 * Installs exception protection for all entry points introduced by189 * goog.net.WebSocket instances which are not protected by190 * {@link goog.debug.ErrorHandler#protectWindowSetTimeout},191 * {@link goog.debug.ErrorHandler#protectWindowSetInterval}, or192 * {@link goog.events.protectBrowserEventEntryPoint}.193 *194 * @param {!goog.debug.ErrorHandler} errorHandler Error handler with which to195 * protect the entry points.196 */197goog.net.WebSocket.protectEntryPoints = function(errorHandler) {198 goog.net.WebSocket.prototype.onOpen_ = errorHandler.protectEntryPoint(199 goog.net.WebSocket.prototype.onOpen_);200 goog.net.WebSocket.prototype.onClose_ = errorHandler.protectEntryPoint(201 goog.net.WebSocket.prototype.onClose_);202 goog.net.WebSocket.prototype.onMessage_ = errorHandler.protectEntryPoint(203 goog.net.WebSocket.prototype.onMessage_);204 goog.net.WebSocket.prototype.onError_ = errorHandler.protectEntryPoint(205 goog.net.WebSocket.prototype.onError_);206};207/**208 * Creates and opens the actual WebSocket. Only call this after attaching the209 * appropriate listeners to this object. If listeners aren't registered, then210 * the {@code goog.net.WebSocket.EventType.OPENED} event might be missed.211 *212 * @param {string} url The URL to which to connect.213 * @param {string=} opt_protocol The subprotocol to use. The connection will214 * only be established if the server reports that it has selected this215 * subprotocol. The subprotocol name must all be a non-empty ASCII string216 * with no control characters and no spaces in them (i.e. only characters217 * in the range U+0021 to U+007E).218 */219goog.net.WebSocket.prototype.open = function(url, opt_protocol) {220 // Sanity check. This works only in modern browsers.221 goog.asserts.assert(goog.global['WebSocket'],222 'This browser does not support WebSocket');223 // Don't do anything if the web socket is already open.224 goog.asserts.assert(!this.isOpen(), 'The WebSocket is already open');225 // Clear any pending attempts to reconnect.226 this.clearReconnectTimer_();227 // Construct the web socket.228 this.url_ = url;229 this.protocol_ = opt_protocol;230 // This check has to be made otherwise you get protocol mismatch exceptions231 // for passing undefined, null, '', or [].232 if (this.protocol_) {233 this.logger_.info('Opening the WebSocket on ' + this.url_ +234 ' with protocol ' + this.protocol_);235 this.webSocket_ = new WebSocket(this.url_, this.protocol_);236 } else {237 this.logger_.info('Opening the WebSocket on ' + this.url_);238 this.webSocket_ = new WebSocket(this.url_);239 }240 // Register the event handlers. Note that it is not possible for these241 // callbacks to be missed because it is registered after the web socket is242 // instantiated. Because of the synchronous nature of JavaScript, this code243 // will execute before the browser creates the resource and makes any calls244 // to these callbacks.245 this.webSocket_.onopen = goog.bind(this.onOpen_, this);246 this.webSocket_.onclose = goog.bind(this.onClose_, this);247 this.webSocket_.onmessage = goog.bind(this.onMessage_, this);248 this.webSocket_.onerror = goog.bind(this.onError_, this);249};250/**251 * Closes the web socket connection.252 */253goog.net.WebSocket.prototype.close = function() {254 // Clear any pending attempts to reconnect.255 this.clearReconnectTimer_();256 // Attempt to close only if the web socket was created.257 if (this.webSocket_) {258 this.logger_.info('Closing the WebSocket.');259 // Close is expected here since it was a direct call. Close is considered260 // unexpected when opening the connection fails or there is some other form261 // of connection loss after being connected.262 this.closeExpected_ = true;263 this.webSocket_.close();264 this.webSocket_ = null;265 }266};267/**268 * Sends the message over the web socket.269 *270 * @param {string} message The message to send.271 */272goog.net.WebSocket.prototype.send = function(message) {273 // Make sure the socket is ready to go before sending a message.274 goog.asserts.assert(this.isOpen(), 'Cannot send without an open socket');275 // Send the message and let onError_ be called if it fails thereafter.276 this.webSocket_.send(message);277};278/**279 * Checks to see if the web socket is open or not.280 *281 * @return {boolean} True if the web socket is open, false otherwise.282 */283goog.net.WebSocket.prototype.isOpen = function() {284 return !!this.webSocket_ &&285 this.webSocket_.readyState == goog.net.WebSocket.ReadyState_.OPEN;286};287/**288 * Called when the web socket has connected.289 *290 * @private291 */292goog.net.WebSocket.prototype.onOpen_ = function() {293 this.logger_.info('WebSocket opened on ' + this.url_);294 this.dispatchEvent(goog.net.WebSocket.EventType.OPENED);295 // Set the next reconnect interval.296 this.reconnectAttempt_ = 0;297 this.nextReconnect_ = this.getNextReconnect_(this.reconnectAttempt_);298};299/**300 * Called when the web socket has closed.301 *302 * @param {!Event} event The close event.303 * @private304 */305goog.net.WebSocket.prototype.onClose_ = function(event) {306 this.logger_.info('The WebSocket on ' + this.url_ + ' closed.');307 // Firing this event allows handlers to query the URL.308 this.dispatchEvent(goog.net.WebSocket.EventType.CLOSED);309 // Always clear out the web socket on a close event.310 this.webSocket_ = null;311 // See if this is an expected call to onClose_.312 if (this.closeExpected_) {313 this.logger_.info('The WebSocket closed normally.');314 // Only clear out the URL if this is a normal close.315 this.url_ = null;316 this.protocol_ = undefined;317 } else {318 // Unexpected, so try to reconnect.319 this.logger_.severe('The WebSocket disconnected unexpectedly: ' +320 event.data);321 // Only try to reconnect if it is enabled.322 if (this.autoReconnect_) {323 // Log the reconnect attempt.324 var seconds = Math.floor(this.nextReconnect_ / 1000);325 this.logger_.info('Seconds until next reconnect attempt: ' + seconds);326 // Actually schedule the timer.327 this.reconnectTimer_ = goog.Timer.callOnce(328 goog.bind(this.open, this, this.url_, this.protocol_),329 this.nextReconnect_, this);330 // Set the next reconnect interval.331 this.reconnectAttempt_++;332 this.nextReconnect_ = this.getNextReconnect_(this.reconnectAttempt_);333 }334 }335 this.closeExpected_ = false;336};337/**338 * Called when a new message arrives from the server.339 *340 * @param {MessageEvent} event The web socket message event.341 * @private342 */343goog.net.WebSocket.prototype.onMessage_ = function(event) {344 var message = /** @type {string} */ (event.data);345 this.dispatchEvent(new goog.net.WebSocket.MessageEvent(message));346};347/**348 * Called when there is any error in communication.349 *350 * @param {Event} event The error event containing the error data.351 * @private352 */353goog.net.WebSocket.prototype.onError_ = function(event) {354 var data = /** @type {string} */ (event.data);355 this.logger_.severe('An error occurred: ' + data);356 this.dispatchEvent(new goog.net.WebSocket.ErrorEvent(data));357};358/**359 * Clears the reconnect timer.360 *361 * @private362 */363goog.net.WebSocket.prototype.clearReconnectTimer_ = function() {364 if (goog.isDefAndNotNull(this.reconnectTimer_)) {365 goog.Timer.clear(this.reconnectTimer_);366 }367 this.reconnectTimer_ = null;368};369/** @override */370goog.net.WebSocket.prototype.disposeInternal = function() {371 goog.base(this, 'disposeInternal');372 this.close();373};374/**375 * Object representing a new incoming message event.376 *377 * @param {string} message The raw message coming from the web socket.378 * @extends {goog.events.Event}379 * @constructor380 */381goog.net.WebSocket.MessageEvent = function(message) {382 goog.base(this, goog.net.WebSocket.EventType.MESSAGE);383 /**384 * The new message from the web socket.385 * @type {string}386 */387 this.message = message;388};389goog.inherits(goog.net.WebSocket.MessageEvent, goog.events.Event);390/**391 * Object representing an error event. This is fired whenever an error occurs392 * on the web socket.393 *394 * @param {string} data The error data.395 * @extends {goog.events.Event}396 * @constructor397 */398goog.net.WebSocket.ErrorEvent = function(data) {399 goog.base(this, goog.net.WebSocket.EventType.ERROR);400 /**401 * The error data coming from the web socket.402 * @type {string}403 */404 this.data = data;405};406goog.inherits(goog.net.WebSocket.ErrorEvent, goog.events.Event);407// Register the WebSocket as an entry point, so that it can be monitored for408// exception handling, etc.409goog.debug.entryPointRegistry.register(410 /**411 * @param {function(!Function): !Function} transformer The transforming412 * function.413 */414 function(transformer) {415 goog.net.WebSocket.prototype.onOpen_ =416 transformer(goog.net.WebSocket.prototype.onOpen_);417 goog.net.WebSocket.prototype.onClose_ =418 transformer(goog.net.WebSocket.prototype.onClose_);419 goog.net.WebSocket.prototype.onMessage_ =420 transformer(goog.net.WebSocket.prototype.onMessage_);421 goog.net.WebSocket.prototype.onError_ =422 transformer(goog.net.WebSocket.prototype.onError_);...
progressiveBackoffCore.py
Source:progressiveBackoffCore.py
1# /*2# * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.3# *4# * Licensed under the Apache License, Version 2.0 (the "License").5# * You may not use this file except in compliance with the License.6# * A copy of the License is located at7# *8# * http://aws.amazon.com/apache2.09# *10# * or in the "license" file accompanying this file. This file is distributed11# * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either12# * express or implied. See the License for the specific language governing13# * permissions and limitations under the License.14# */15 # This class implements the progressive backoff logic for auto-reconnect.16 # It manages the reconnect wait time for the current reconnect, controling17 # when to increase it and when to reset it.18import time19import threading20import logging21class progressiveBackoffCore:22 23 # Logger24 _logger = logging.getLogger(__name__)25 def __init__(self, srcBaseReconnectTimeSecond=1, srcMaximumReconnectTimeSecond=32, srcMinimumConnectTimeSecond=20):26 # The base reconnection time in seconds, default 127 self._baseReconnectTimeSecond = srcBaseReconnectTimeSecond28 # The maximum reconnection time in seconds, default 3229 self._maximumReconnectTimeSecond = srcMaximumReconnectTimeSecond30 # The minimum time in milliseconds that a connection must be maintained in order to be considered stable31 # Default 2032 self._minimumConnectTimeSecond = srcMinimumConnectTimeSecond33 # Current backOff time in seconds, init to equal to 034 self._currentBackoffTimeSecond = 135 # Handler for timer36 self._resetBackoffTimer = None37 # For custom progressiveBackoff timing configuration38 def configTime(self, srcBaseReconnectTimeSecond, srcMaximumReconnectTimeSecond, srcMinimumConnectTimeSecond):39 if srcBaseReconnectTimeSecond < 0 or srcMaximumReconnectTimeSecond < 0 or srcMinimumConnectTimeSecond < 0:40 self._logger.error("init: Negative time configuration detected.")41 raise ValueError("Negative time configuration detected.")42 if srcBaseReconnectTimeSecond >= srcMinimumConnectTimeSecond:43 self._logger.error("init: Min connect time should be bigger than base reconnect time.")44 raise ValueError("Min connect time should be bigger than base reconnect time.")45 self._baseReconnectTimeSecond = srcBaseReconnectTimeSecond46 self._maximumReconnectTimeSecond = srcMaximumReconnectTimeSecond47 self._minimumConnectTimeSecond = srcMinimumConnectTimeSecond48 self._currentBackoffTimeSecond = 149 # Block the reconnect logic for _currentBackoffTimeSecond50 # Update the currentBackoffTimeSecond for the next reconnect51 # Cancel the in-waiting timer for resetting backOff time52 # This should get called only when a disconnect/reconnect happens53 def backOff(self):54 self._logger.debug("backOff: current backoff time is: " + str(self._currentBackoffTimeSecond) + " sec.")55 if self._resetBackoffTimer is not None:56 # Cancel the timer57 self._resetBackoffTimer.cancel()58 # Block the reconnect logic59 time.sleep(self._currentBackoffTimeSecond)60 # Update the backoff time61 if self._currentBackoffTimeSecond == 0:62 # This is the first attempt to connect, set it to base63 self._currentBackoffTimeSecond = self._baseReconnectTimeSecond64 else:65 # r_cur = min(2^n*r_base, r_max)66 self._currentBackoffTimeSecond = min(self._maximumReconnectTimeSecond, self._currentBackoffTimeSecond * 2)67 # Start the timer for resetting _currentBackoffTimeSecond68 # Will be cancelled upon calling backOff69 def startStableConnectionTimer(self):70 self._resetBackoffTimer = threading.Timer(self._minimumConnectTimeSecond, self._connectionStableThenResetBackoffTime)71 self._resetBackoffTimer.start()72 # Timer callback to reset _currentBackoffTimeSecond73 # If the connection is stable for longer than _minimumConnectTimeSecond,74 # reset the currentBackoffTimeSecond to _baseReconnectTimeSecond75 def _connectionStableThenResetBackoffTime(self):76 self._logger.debug("stableConnection: Resetting the backoff time to: " + str(self._baseReconnectTimeSecond) + " sec.")...
Reconnect.js.uncompressed.js
Source:Reconnect.js.uncompressed.js
...21 var connectHandle = dojo.connect(socket, "onclose", function(event){22 clearTimeout(checkForOpen);23 if(!event.wasClean){24 socket.disconnected(function(){25 dojox.socket.replace(socket, newSocket = socket.reconnect());26 });27 }28 });29 var checkForOpen, newSocket;30 if(!socket.disconnected){31 // add a default impl if it doesn't exist32 socket.disconnected = function(reconnect){33 setTimeout(function(){34 reconnect();35 checkForOpen = setTimeout(function(){36 //reset the backoff37 if(newSocket.readyState < 2){38 reconnectTime = options.reconnectTime || 10000;39 }40 }, 10000);41 }, reconnectTime);42 // backoff each time43 reconnectTime *= options.backoffRate || 2;44 };45 }46 if(!socket.reconnect){47 // add a default impl if it doesn't exist48 socket.reconnect = function(){...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!