id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
233,100
prompt-toolkit/pymux
pymux/commands/commands.py
list_panes
def list_panes(pymux, variables): """ Display a list of all the panes. """ w = pymux.arrangement.get_active_window() active_pane = w.active_pane result = [] for i, p in enumerate(w.panes): process = p.process result.append('%i: [%sx%s] [history %s/%s] %s' % ( i, process.sx, process.sy, min(pymux.history_limit, process.screen.line_offset + process.sy), pymux.history_limit, ('(active)' if p == active_pane else ''))) # Display help in pane. result = '\n'.join(sorted(result)) pymux.get_client_state().layout_manager.display_popup('list-keys', result)
python
def list_panes(pymux, variables): w = pymux.arrangement.get_active_window() active_pane = w.active_pane result = [] for i, p in enumerate(w.panes): process = p.process result.append('%i: [%sx%s] [history %s/%s] %s' % ( i, process.sx, process.sy, min(pymux.history_limit, process.screen.line_offset + process.sy), pymux.history_limit, ('(active)' if p == active_pane else ''))) # Display help in pane. result = '\n'.join(sorted(result)) pymux.get_client_state().layout_manager.display_popup('list-keys', result)
[ "def", "list_panes", "(", "pymux", ",", "variables", ")", ":", "w", "=", "pymux", ".", "arrangement", ".", "get_active_window", "(", ")", "active_pane", "=", "w", ".", "active_pane", "result", "=", "[", "]", "for", "i", ",", "p", "in", "enumerate", "("...
Display a list of all the panes.
[ "Display", "a", "list", "of", "all", "the", "panes", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/commands/commands.py#L634-L654
233,101
prompt-toolkit/pymux
pymux/commands/commands.py
show_buffer
def show_buffer(pymux, variables): """ Display the clipboard content. """ text = get_app().clipboard.get_data().text pymux.get_client_state().layout_manager.display_popup('show-buffer', text)
python
def show_buffer(pymux, variables): text = get_app().clipboard.get_data().text pymux.get_client_state().layout_manager.display_popup('show-buffer', text)
[ "def", "show_buffer", "(", "pymux", ",", "variables", ")", ":", "text", "=", "get_app", "(", ")", ".", "clipboard", ".", "get_data", "(", ")", ".", "text", "pymux", ".", "get_client_state", "(", ")", ".", "layout_manager", ".", "display_popup", "(", "'sh...
Display the clipboard content.
[ "Display", "the", "clipboard", "content", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/commands/commands.py#L658-L663
233,102
prompt-toolkit/pymux
pymux/arrangement.py
Pane.name
def name(self): """ The name for the window as displayed in the title bar and status bar. """ # Name, explicitely set for the pane. if self.chosen_name: return self.chosen_name else: # Name from the process running inside the pane. name = self.process.get_name() if name: return os.path.basename(name) return ''
python
def name(self): # Name, explicitely set for the pane. if self.chosen_name: return self.chosen_name else: # Name from the process running inside the pane. name = self.process.get_name() if name: return os.path.basename(name) return ''
[ "def", "name", "(", "self", ")", ":", "# Name, explicitely set for the pane.", "if", "self", ".", "chosen_name", ":", "return", "self", ".", "chosen_name", "else", ":", "# Name from the process running inside the pane.", "name", "=", "self", ".", "process", ".", "ge...
The name for the window as displayed in the title bar and status bar.
[ "The", "name", "for", "the", "window", "as", "displayed", "in", "the", "title", "bar", "and", "status", "bar", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/arrangement.py#L78-L91
233,103
prompt-toolkit/pymux
pymux/arrangement.py
Window.name
def name(self): """ The name for this window as it should be displayed in the status bar. """ # Name, explicitely set for the window. if self.chosen_name: return self.chosen_name else: pane = self.active_pane if pane: return pane.name return ''
python
def name(self): # Name, explicitely set for the window. if self.chosen_name: return self.chosen_name else: pane = self.active_pane if pane: return pane.name return ''
[ "def", "name", "(", "self", ")", ":", "# Name, explicitely set for the window.", "if", "self", ".", "chosen_name", ":", "return", "self", ".", "chosen_name", "else", ":", "pane", "=", "self", ".", "active_pane", "if", "pane", ":", "return", "pane", ".", "nam...
The name for this window as it should be displayed in the status bar.
[ "The", "name", "for", "this", "window", "as", "it", "should", "be", "displayed", "in", "the", "status", "bar", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/arrangement.py#L231-L243
233,104
prompt-toolkit/pymux
pymux/arrangement.py
Window.add_pane
def add_pane(self, pane, vsplit=False): """ Add another pane to this Window. """ assert isinstance(pane, Pane) assert isinstance(vsplit, bool) split_cls = VSplit if vsplit else HSplit if self.active_pane is None: self.root.append(pane) else: parent = self._get_parent(self.active_pane) same_direction = isinstance(parent, split_cls) index = parent.index(self.active_pane) if same_direction: parent.insert(index + 1, pane) else: new_split = split_cls([self.active_pane, pane]) parent[index] = new_split # Give the newly created split the same weight as the original # pane that was at this position. parent.weights[new_split] = parent.weights[self.active_pane] self.active_pane = pane self.zoom = False
python
def add_pane(self, pane, vsplit=False): assert isinstance(pane, Pane) assert isinstance(vsplit, bool) split_cls = VSplit if vsplit else HSplit if self.active_pane is None: self.root.append(pane) else: parent = self._get_parent(self.active_pane) same_direction = isinstance(parent, split_cls) index = parent.index(self.active_pane) if same_direction: parent.insert(index + 1, pane) else: new_split = split_cls([self.active_pane, pane]) parent[index] = new_split # Give the newly created split the same weight as the original # pane that was at this position. parent.weights[new_split] = parent.weights[self.active_pane] self.active_pane = pane self.zoom = False
[ "def", "add_pane", "(", "self", ",", "pane", ",", "vsplit", "=", "False", ")", ":", "assert", "isinstance", "(", "pane", ",", "Pane", ")", "assert", "isinstance", "(", "vsplit", ",", "bool", ")", "split_cls", "=", "VSplit", "if", "vsplit", "else", "HSp...
Add another pane to this Window.
[ "Add", "another", "pane", "to", "this", "Window", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/arrangement.py#L245-L273
233,105
prompt-toolkit/pymux
pymux/arrangement.py
Window.remove_pane
def remove_pane(self, pane): """ Remove pane from this Window. """ assert isinstance(pane, Pane) if pane in self.panes: # When this pane was focused, switch to previous active or next in order. if pane == self.active_pane: if self.previous_active_pane: self.active_pane = self.previous_active_pane else: self.focus_next() # Remove from the parent. When the parent becomes empty, remove the # parent itself recursively. p = self._get_parent(pane) p.remove(pane) while len(p) == 0 and p != self.root: p2 = self._get_parent(p) p2.remove(p) p = p2 # When the parent has only one item left, collapse into its parent. while len(p) == 1 and p != self.root: p2 = self._get_parent(p) p2.weights[p[0]] = p2.weights[p] # Keep dimensions. i = p2.index(p) p2[i] = p[0] p = p2
python
def remove_pane(self, pane): assert isinstance(pane, Pane) if pane in self.panes: # When this pane was focused, switch to previous active or next in order. if pane == self.active_pane: if self.previous_active_pane: self.active_pane = self.previous_active_pane else: self.focus_next() # Remove from the parent. When the parent becomes empty, remove the # parent itself recursively. p = self._get_parent(pane) p.remove(pane) while len(p) == 0 and p != self.root: p2 = self._get_parent(p) p2.remove(p) p = p2 # When the parent has only one item left, collapse into its parent. while len(p) == 1 and p != self.root: p2 = self._get_parent(p) p2.weights[p[0]] = p2.weights[p] # Keep dimensions. i = p2.index(p) p2[i] = p[0] p = p2
[ "def", "remove_pane", "(", "self", ",", "pane", ")", ":", "assert", "isinstance", "(", "pane", ",", "Pane", ")", "if", "pane", "in", "self", ".", "panes", ":", "# When this pane was focused, switch to previous active or next in order.", "if", "pane", "==", "self",...
Remove pane from this Window.
[ "Remove", "pane", "from", "this", "Window", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/arrangement.py#L275-L305
233,106
prompt-toolkit/pymux
pymux/arrangement.py
Window.panes
def panes(self): " List with all panes from this Window. " result = [] for s in self.splits: for item in s: if isinstance(item, Pane): result.append(item) return result
python
def panes(self): " List with all panes from this Window. " result = [] for s in self.splits: for item in s: if isinstance(item, Pane): result.append(item) return result
[ "def", "panes", "(", "self", ")", ":", "result", "=", "[", "]", "for", "s", "in", "self", ".", "splits", ":", "for", "item", "in", "s", ":", "if", "isinstance", "(", "item", ",", "Pane", ")", ":", "result", ".", "append", "(", "item", ")", "ret...
List with all panes from this Window.
[ "List", "with", "all", "panes", "from", "this", "Window", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/arrangement.py#L308-L317
233,107
prompt-toolkit/pymux
pymux/arrangement.py
Window.focus_next
def focus_next(self, count=1): " Focus the next pane. " panes = self.panes if panes: self.active_pane = panes[(panes.index(self.active_pane) + count) % len(panes)] else: self.active_pane = None
python
def focus_next(self, count=1): " Focus the next pane. " panes = self.panes if panes: self.active_pane = panes[(panes.index(self.active_pane) + count) % len(panes)] else: self.active_pane = None
[ "def", "focus_next", "(", "self", ",", "count", "=", "1", ")", ":", "panes", "=", "self", ".", "panes", "if", "panes", ":", "self", ".", "active_pane", "=", "panes", "[", "(", "panes", ".", "index", "(", "self", ".", "active_pane", ")", "+", "count...
Focus the next pane.
[ "Focus", "the", "next", "pane", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/arrangement.py#L353-L359
233,108
prompt-toolkit/pymux
pymux/arrangement.py
Window.select_layout
def select_layout(self, layout_type): """ Select one of the predefined layouts. """ assert layout_type in LayoutTypes._ALL # When there is only one pane, always choose EVEN_HORIZONTAL, # Otherwise, we create VSplit/HSplit instances with an empty list of # children. if len(self.panes) == 1: layout_type = LayoutTypes.EVEN_HORIZONTAL # even-horizontal. if layout_type == LayoutTypes.EVEN_HORIZONTAL: self.root = HSplit(self.panes) # even-vertical. elif layout_type == LayoutTypes.EVEN_VERTICAL: self.root = VSplit(self.panes) # main-horizontal. elif layout_type == LayoutTypes.MAIN_HORIZONTAL: self.root = HSplit([ self.active_pane, VSplit([p for p in self.panes if p != self.active_pane]) ]) # main-vertical. elif layout_type == LayoutTypes.MAIN_VERTICAL: self.root = VSplit([ self.active_pane, HSplit([p for p in self.panes if p != self.active_pane]) ]) # tiled. elif layout_type == LayoutTypes.TILED: panes = self.panes column_count = math.ceil(len(panes) ** .5) rows = HSplit() current_row = VSplit() for p in panes: current_row.append(p) if len(current_row) >= column_count: rows.append(current_row) current_row = VSplit() if current_row: rows.append(current_row) self.root = rows self.previous_selected_layout = layout_type
python
def select_layout(self, layout_type): assert layout_type in LayoutTypes._ALL # When there is only one pane, always choose EVEN_HORIZONTAL, # Otherwise, we create VSplit/HSplit instances with an empty list of # children. if len(self.panes) == 1: layout_type = LayoutTypes.EVEN_HORIZONTAL # even-horizontal. if layout_type == LayoutTypes.EVEN_HORIZONTAL: self.root = HSplit(self.panes) # even-vertical. elif layout_type == LayoutTypes.EVEN_VERTICAL: self.root = VSplit(self.panes) # main-horizontal. elif layout_type == LayoutTypes.MAIN_HORIZONTAL: self.root = HSplit([ self.active_pane, VSplit([p for p in self.panes if p != self.active_pane]) ]) # main-vertical. elif layout_type == LayoutTypes.MAIN_VERTICAL: self.root = VSplit([ self.active_pane, HSplit([p for p in self.panes if p != self.active_pane]) ]) # tiled. elif layout_type == LayoutTypes.TILED: panes = self.panes column_count = math.ceil(len(panes) ** .5) rows = HSplit() current_row = VSplit() for p in panes: current_row.append(p) if len(current_row) >= column_count: rows.append(current_row) current_row = VSplit() if current_row: rows.append(current_row) self.root = rows self.previous_selected_layout = layout_type
[ "def", "select_layout", "(", "self", ",", "layout_type", ")", ":", "assert", "layout_type", "in", "LayoutTypes", ".", "_ALL", "# When there is only one pane, always choose EVEN_HORIZONTAL,", "# Otherwise, we create VSplit/HSplit instances with an empty list of", "# children.", "if"...
Select one of the predefined layouts.
[ "Select", "one", "of", "the", "predefined", "layouts", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/arrangement.py#L398-L451
233,109
prompt-toolkit/pymux
pymux/arrangement.py
Window.change_size_for_active_pane
def change_size_for_active_pane(self, up=0, right=0, down=0, left=0): """ Increase the size of the current pane in any of the four directions. """ child = self.active_pane self.change_size_for_pane(child, up=up, right=right, down=down, left=left)
python
def change_size_for_active_pane(self, up=0, right=0, down=0, left=0): child = self.active_pane self.change_size_for_pane(child, up=up, right=right, down=down, left=left)
[ "def", "change_size_for_active_pane", "(", "self", ",", "up", "=", "0", ",", "right", "=", "0", ",", "down", "=", "0", ",", "left", "=", "0", ")", ":", "child", "=", "self", ".", "active_pane", "self", ".", "change_size_for_pane", "(", "child", ",", ...
Increase the size of the current pane in any of the four directions.
[ "Increase", "the", "size", "of", "the", "current", "pane", "in", "any", "of", "the", "four", "directions", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/arrangement.py#L478-L483
233,110
prompt-toolkit/pymux
pymux/arrangement.py
Window.change_size_for_pane
def change_size_for_pane(self, pane, up=0, right=0, down=0, left=0): """ Increase the size of the current pane in any of the four directions. Positive values indicate an increase, negative values a decrease. """ assert isinstance(pane, Pane) def find_split_and_child(split_cls, is_before): " Find the split for which we will have to update the weights. " child = pane split = self._get_parent(child) def found(): return isinstance(split, split_cls) and ( not is_before or split.index(child) > 0) and ( is_before or split.index(child) < len(split) - 1) while split and not found(): child = split split = self._get_parent(child) return split, child # split can be None! def handle_side(split_cls, is_before, amount, trying_other_side=False): " Increase weights on one side. (top/left/right/bottom). " if amount: split, child = find_split_and_child(split_cls, is_before) if split: # Find neighbour. neighbour_index = split.index(child) + (-1 if is_before else 1) neighbour_child = split[neighbour_index] # Increase/decrease weights. split.weights[child] += amount split.weights[neighbour_child] -= amount # Ensure that all weights are at least one. for k, value in split.weights.items(): if value < 1: split.weights[k] = 1 else: # When no split has been found where we can move in this # direction, try to move the other side instead using a # negative amount. This happens when we run "resize-pane -R 4" # inside the pane that is completely on the right. In that # case it's logical to move the left border to the right # instead. if not trying_other_side: handle_side(split_cls, not is_before, -amount, trying_other_side=True) handle_side(VSplit, True, left) handle_side(VSplit, False, right) handle_side(HSplit, True, up) handle_side(HSplit, False, down)
python
def change_size_for_pane(self, pane, up=0, right=0, down=0, left=0): assert isinstance(pane, Pane) def find_split_and_child(split_cls, is_before): " Find the split for which we will have to update the weights. " child = pane split = self._get_parent(child) def found(): return isinstance(split, split_cls) and ( not is_before or split.index(child) > 0) and ( is_before or split.index(child) < len(split) - 1) while split and not found(): child = split split = self._get_parent(child) return split, child # split can be None! def handle_side(split_cls, is_before, amount, trying_other_side=False): " Increase weights on one side. (top/left/right/bottom). " if amount: split, child = find_split_and_child(split_cls, is_before) if split: # Find neighbour. neighbour_index = split.index(child) + (-1 if is_before else 1) neighbour_child = split[neighbour_index] # Increase/decrease weights. split.weights[child] += amount split.weights[neighbour_child] -= amount # Ensure that all weights are at least one. for k, value in split.weights.items(): if value < 1: split.weights[k] = 1 else: # When no split has been found where we can move in this # direction, try to move the other side instead using a # negative amount. This happens when we run "resize-pane -R 4" # inside the pane that is completely on the right. In that # case it's logical to move the left border to the right # instead. if not trying_other_side: handle_side(split_cls, not is_before, -amount, trying_other_side=True) handle_side(VSplit, True, left) handle_side(VSplit, False, right) handle_side(HSplit, True, up) handle_side(HSplit, False, down)
[ "def", "change_size_for_pane", "(", "self", ",", "pane", ",", "up", "=", "0", ",", "right", "=", "0", ",", "down", "=", "0", ",", "left", "=", "0", ")", ":", "assert", "isinstance", "(", "pane", ",", "Pane", ")", "def", "find_split_and_child", "(", ...
Increase the size of the current pane in any of the four directions. Positive values indicate an increase, negative values a decrease.
[ "Increase", "the", "size", "of", "the", "current", "pane", "in", "any", "of", "the", "four", "directions", ".", "Positive", "values", "indicate", "an", "increase", "negative", "values", "a", "decrease", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/arrangement.py#L485-L541
233,111
prompt-toolkit/pymux
pymux/arrangement.py
Window.get_pane_index
def get_pane_index(self, pane): " Return the index of the given pane. ValueError if not found. " assert isinstance(pane, Pane) return self.panes.index(pane)
python
def get_pane_index(self, pane): " Return the index of the given pane. ValueError if not found. " assert isinstance(pane, Pane) return self.panes.index(pane)
[ "def", "get_pane_index", "(", "self", ",", "pane", ")", ":", "assert", "isinstance", "(", "pane", ",", "Pane", ")", "return", "self", ".", "panes", ".", "index", "(", "pane", ")" ]
Return the index of the given pane. ValueError if not found.
[ "Return", "the", "index", "of", "the", "given", "pane", ".", "ValueError", "if", "not", "found", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/arrangement.py#L543-L546
233,112
prompt-toolkit/pymux
pymux/arrangement.py
Arrangement.set_active_window_from_pane_id
def set_active_window_from_pane_id(self, pane_id): """ Make the window with this pane ID the active Window. """ assert isinstance(pane_id, int) for w in self.windows: for p in w.panes: if p.pane_id == pane_id: self.set_active_window(w)
python
def set_active_window_from_pane_id(self, pane_id): assert isinstance(pane_id, int) for w in self.windows: for p in w.panes: if p.pane_id == pane_id: self.set_active_window(w)
[ "def", "set_active_window_from_pane_id", "(", "self", ",", "pane_id", ")", ":", "assert", "isinstance", "(", "pane_id", ",", "int", ")", "for", "w", "in", "self", ".", "windows", ":", "for", "p", "in", "w", ".", "panes", ":", "if", "p", ".", "pane_id",...
Make the window with this pane ID the active Window.
[ "Make", "the", "window", "with", "this", "pane", "ID", "the", "active", "Window", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/arrangement.py#L598-L607
233,113
prompt-toolkit/pymux
pymux/arrangement.py
Arrangement.get_window_by_index
def get_window_by_index(self, index): " Return the Window with this index or None if not found. " for w in self.windows: if w.index == index: return w
python
def get_window_by_index(self, index): " Return the Window with this index or None if not found. " for w in self.windows: if w.index == index: return w
[ "def", "get_window_by_index", "(", "self", ",", "index", ")", ":", "for", "w", "in", "self", ".", "windows", ":", "if", "w", ".", "index", "==", "index", ":", "return", "w" ]
Return the Window with this index or None if not found.
[ "Return", "the", "Window", "with", "this", "index", "or", "None", "if", "not", "found", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/arrangement.py#L618-L622
233,114
prompt-toolkit/pymux
pymux/arrangement.py
Arrangement.create_window
def create_window(self, pane, name=None, set_active=True): """ Create a new window that contains just this pane. :param pane: The :class:`.Pane` instance to put in the new window. :param name: If given, name for the new window. :param set_active: When True, focus the new window. """ assert isinstance(pane, Pane) assert name is None or isinstance(name, six.text_type) # Take the first available index. taken_indexes = [w.index for w in self.windows] index = self.base_index while index in taken_indexes: index += 1 # Create new window and add it. w = Window(index) w.add_pane(pane) self.windows.append(w) # Sort windows by index. self.windows = sorted(self.windows, key=lambda w: w.index) app = get_app(return_none=True) if app is not None and set_active: self.set_active_window(w) if name is not None: w.chosen_name = name assert w.active_pane == pane assert w._get_parent(pane)
python
def create_window(self, pane, name=None, set_active=True): assert isinstance(pane, Pane) assert name is None or isinstance(name, six.text_type) # Take the first available index. taken_indexes = [w.index for w in self.windows] index = self.base_index while index in taken_indexes: index += 1 # Create new window and add it. w = Window(index) w.add_pane(pane) self.windows.append(w) # Sort windows by index. self.windows = sorted(self.windows, key=lambda w: w.index) app = get_app(return_none=True) if app is not None and set_active: self.set_active_window(w) if name is not None: w.chosen_name = name assert w.active_pane == pane assert w._get_parent(pane)
[ "def", "create_window", "(", "self", ",", "pane", ",", "name", "=", "None", ",", "set_active", "=", "True", ")", ":", "assert", "isinstance", "(", "pane", ",", "Pane", ")", "assert", "name", "is", "None", "or", "isinstance", "(", "name", ",", "six", ...
Create a new window that contains just this pane. :param pane: The :class:`.Pane` instance to put in the new window. :param name: If given, name for the new window. :param set_active: When True, focus the new window.
[ "Create", "a", "new", "window", "that", "contains", "just", "this", "pane", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/arrangement.py#L624-L659
233,115
prompt-toolkit/pymux
pymux/arrangement.py
Arrangement.break_pane
def break_pane(self, set_active=True): """ When the current window has multiple panes, remove the pane from this window and put it in a new window. :param set_active: When True, focus the new window. """ w = self.get_active_window() if len(w.panes) > 1: pane = w.active_pane self.get_active_window().remove_pane(pane) self.create_window(pane, set_active=set_active)
python
def break_pane(self, set_active=True): w = self.get_active_window() if len(w.panes) > 1: pane = w.active_pane self.get_active_window().remove_pane(pane) self.create_window(pane, set_active=set_active)
[ "def", "break_pane", "(", "self", ",", "set_active", "=", "True", ")", ":", "w", "=", "self", ".", "get_active_window", "(", ")", "if", "len", "(", "w", ".", "panes", ")", ">", "1", ":", "pane", "=", "w", ".", "active_pane", "self", ".", "get_activ...
When the current window has multiple panes, remove the pane from this window and put it in a new window. :param set_active: When True, focus the new window.
[ "When", "the", "current", "window", "has", "multiple", "panes", "remove", "the", "pane", "from", "this", "window", "and", "put", "it", "in", "a", "new", "window", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/arrangement.py#L712-L724
233,116
prompt-toolkit/pymux
pymux/arrangement.py
Arrangement.rotate_window
def rotate_window(self, count=1): " Rotate the panes in the active window. " w = self.get_active_window() w.rotate(count=count)
python
def rotate_window(self, count=1): " Rotate the panes in the active window. " w = self.get_active_window() w.rotate(count=count)
[ "def", "rotate_window", "(", "self", ",", "count", "=", "1", ")", ":", "w", "=", "self", ".", "get_active_window", "(", ")", "w", ".", "rotate", "(", "count", "=", "count", ")" ]
Rotate the panes in the active window.
[ "Rotate", "the", "panes", "in", "the", "active", "window", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/arrangement.py#L726-L729
233,117
prompt-toolkit/pymux
pymux/server.py
ServerConnection._process
def _process(self, data): """ Process packet received from client. """ try: packet = json.loads(data) except ValueError: # So far, this never happened. But it would be good to have some # protection. logger.warning('Received invalid JSON from client. Ignoring.') return # Handle commands. if packet['cmd'] == 'run-command': self._run_command(packet) # Handle stdin. elif packet['cmd'] == 'in': self._pipeinput.send_text(packet['data']) # elif packet['cmd'] == 'flush-input': # self._inputstream.flush() # Flush escape key. # XXX: I think we no longer need this. # Set size. (The client reports the size.) elif packet['cmd'] == 'size': data = packet['data'] self.size = Size(rows=data[0], columns=data[1]) self.pymux.invalidate() # Start GUI. (Create CommandLineInterface front-end for pymux.) elif packet['cmd'] == 'start-gui': detach_other_clients = bool(packet['detach-others']) color_depth = packet['color-depth'] term = packet['term'] if detach_other_clients: for c in self.pymux.connections: c.detach_and_close() print('Create app...') self._create_app(color_depth=color_depth, term=term)
python
def _process(self, data): try: packet = json.loads(data) except ValueError: # So far, this never happened. But it would be good to have some # protection. logger.warning('Received invalid JSON from client. Ignoring.') return # Handle commands. if packet['cmd'] == 'run-command': self._run_command(packet) # Handle stdin. elif packet['cmd'] == 'in': self._pipeinput.send_text(packet['data']) # elif packet['cmd'] == 'flush-input': # self._inputstream.flush() # Flush escape key. # XXX: I think we no longer need this. # Set size. (The client reports the size.) elif packet['cmd'] == 'size': data = packet['data'] self.size = Size(rows=data[0], columns=data[1]) self.pymux.invalidate() # Start GUI. (Create CommandLineInterface front-end for pymux.) elif packet['cmd'] == 'start-gui': detach_other_clients = bool(packet['detach-others']) color_depth = packet['color-depth'] term = packet['term'] if detach_other_clients: for c in self.pymux.connections: c.detach_and_close() print('Create app...') self._create_app(color_depth=color_depth, term=term)
[ "def", "_process", "(", "self", ",", "data", ")", ":", "try", ":", "packet", "=", "json", ".", "loads", "(", "data", ")", "except", "ValueError", ":", "# So far, this never happened. But it would be good to have some", "# protection.", "logger", ".", "warning", "(...
Process packet received from client.
[ "Process", "packet", "received", "from", "client", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/server.py#L57-L97
233,118
prompt-toolkit/pymux
pymux/server.py
ServerConnection._send_packet
def _send_packet(self, data): """ Send packet to client. """ if self._closed: return data = json.dumps(data) def send(): try: yield From(self.pipe_connection.write(data)) except BrokenPipeError: self.detach_and_close() ensure_future(send())
python
def _send_packet(self, data): if self._closed: return data = json.dumps(data) def send(): try: yield From(self.pipe_connection.write(data)) except BrokenPipeError: self.detach_and_close() ensure_future(send())
[ "def", "_send_packet", "(", "self", ",", "data", ")", ":", "if", "self", ".", "_closed", ":", "return", "data", "=", "json", ".", "dumps", "(", "data", ")", "def", "send", "(", ")", ":", "try", ":", "yield", "From", "(", "self", ".", "pipe_connecti...
Send packet to client.
[ "Send", "packet", "to", "client", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/server.py#L99-L113
233,119
prompt-toolkit/pymux
pymux/server.py
ServerConnection._run_command
def _run_command(self, packet): """ Execute a run command from the client. """ create_temp_cli = self.client_states is None if create_temp_cli: # If this client doesn't have a CLI. Create a Fake CLI where the # window containing this pane, is the active one. (The CLI instance # will be removed before the render function is called, so it doesn't # hurt too much and makes the code easier.) pane_id = int(packet['pane_id']) self._create_app() with set_app(self.client_state.app): self.pymux.arrangement.set_active_window_from_pane_id(pane_id) with set_app(self.client_state.app): try: self.pymux.handle_command(packet['data']) finally: self._close_connection()
python
def _run_command(self, packet): create_temp_cli = self.client_states is None if create_temp_cli: # If this client doesn't have a CLI. Create a Fake CLI where the # window containing this pane, is the active one. (The CLI instance # will be removed before the render function is called, so it doesn't # hurt too much and makes the code easier.) pane_id = int(packet['pane_id']) self._create_app() with set_app(self.client_state.app): self.pymux.arrangement.set_active_window_from_pane_id(pane_id) with set_app(self.client_state.app): try: self.pymux.handle_command(packet['data']) finally: self._close_connection()
[ "def", "_run_command", "(", "self", ",", "packet", ")", ":", "create_temp_cli", "=", "self", ".", "client_states", "is", "None", "if", "create_temp_cli", ":", "# If this client doesn't have a CLI. Create a Fake CLI where the", "# window containing this pane, is the active one. ...
Execute a run command from the client.
[ "Execute", "a", "run", "command", "from", "the", "client", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/server.py#L115-L135
233,120
prompt-toolkit/pymux
pymux/server.py
ServerConnection._create_app
def _create_app(self, color_depth, term='xterm'): """ Create CommandLineInterface for this client. Called when the client wants to attach the UI to the server. """ output = Vt100_Output(_SocketStdout(self._send_packet), lambda: self.size, term=term, write_binary=False) self.client_state = self.pymux.add_client( input=self._pipeinput, output=output, connection=self, color_depth=color_depth) print('Start running app...') future = self.client_state.app.run_async() print('Start running app got future...', future) @future.add_done_callback def done(_): print('APP DONE.........') print(future.result()) self._close_connection()
python
def _create_app(self, color_depth, term='xterm'): output = Vt100_Output(_SocketStdout(self._send_packet), lambda: self.size, term=term, write_binary=False) self.client_state = self.pymux.add_client( input=self._pipeinput, output=output, connection=self, color_depth=color_depth) print('Start running app...') future = self.client_state.app.run_async() print('Start running app got future...', future) @future.add_done_callback def done(_): print('APP DONE.........') print(future.result()) self._close_connection()
[ "def", "_create_app", "(", "self", ",", "color_depth", ",", "term", "=", "'xterm'", ")", ":", "output", "=", "Vt100_Output", "(", "_SocketStdout", "(", "self", ".", "_send_packet", ")", ",", "lambda", ":", "self", ".", "size", ",", "term", "=", "term", ...
Create CommandLineInterface for this client. Called when the client wants to attach the UI to the server.
[ "Create", "CommandLineInterface", "for", "this", "client", ".", "Called", "when", "the", "client", "wants", "to", "attach", "the", "UI", "to", "the", "server", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/server.py#L137-L158
233,121
prompt-toolkit/pymux
pymux/server.py
_ClientInput._create_context_manager
def _create_context_manager(self, mode): " Create a context manager that sends 'mode' commands to the client. " class mode_context_manager(object): def __enter__(*a): self.send_packet({'cmd': 'mode', 'data': mode}) def __exit__(*a): self.send_packet({'cmd': 'mode', 'data': 'restore'}) return mode_context_manager()
python
def _create_context_manager(self, mode): " Create a context manager that sends 'mode' commands to the client. " class mode_context_manager(object): def __enter__(*a): self.send_packet({'cmd': 'mode', 'data': mode}) def __exit__(*a): self.send_packet({'cmd': 'mode', 'data': 'restore'}) return mode_context_manager()
[ "def", "_create_context_manager", "(", "self", ",", "mode", ")", ":", "class", "mode_context_manager", "(", "object", ")", ":", "def", "__enter__", "(", "*", "a", ")", ":", "self", ".", "send_packet", "(", "{", "'cmd'", ":", "'mode'", ",", "'data'", ":",...
Create a context manager that sends 'mode' commands to the client.
[ "Create", "a", "context", "manager", "that", "sends", "mode", "commands", "to", "the", "client", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/server.py#L224-L233
233,122
prompt-toolkit/pymux
pymux/commands/utils.py
wrap_argument
def wrap_argument(text): """ Wrap command argument in quotes and escape when this contains special characters. """ if not any(x in text for x in [' ', '"', "'", '\\']): return text else: return '"%s"' % (text.replace('\\', r'\\').replace('"', r'\"'), )
python
def wrap_argument(text): if not any(x in text for x in [' ', '"', "'", '\\']): return text else: return '"%s"' % (text.replace('\\', r'\\').replace('"', r'\"'), )
[ "def", "wrap_argument", "(", "text", ")", ":", "if", "not", "any", "(", "x", "in", "text", "for", "x", "in", "[", "' '", ",", "'\"'", ",", "\"'\"", ",", "'\\\\'", "]", ")", ":", "return", "text", "else", ":", "return", "'\"%s\"'", "%", "(", "text...
Wrap command argument in quotes and escape when this contains special characters.
[ "Wrap", "command", "argument", "in", "quotes", "and", "escape", "when", "this", "contains", "special", "characters", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/commands/utils.py#L8-L15
233,123
prompt-toolkit/pymux
pymux/utils.py
get_default_shell
def get_default_shell(): """ return the path to the default shell for the current user. """ if is_windows(): return 'cmd.exe' else: import pwd import getpass if 'SHELL' in os.environ: return os.environ['SHELL'] else: username = getpass.getuser() shell = pwd.getpwnam(username).pw_shell return shell
python
def get_default_shell(): if is_windows(): return 'cmd.exe' else: import pwd import getpass if 'SHELL' in os.environ: return os.environ['SHELL'] else: username = getpass.getuser() shell = pwd.getpwnam(username).pw_shell return shell
[ "def", "get_default_shell", "(", ")", ":", "if", "is_windows", "(", ")", ":", "return", "'cmd.exe'", "else", ":", "import", "pwd", "import", "getpass", "if", "'SHELL'", "in", "os", ".", "environ", ":", "return", "os", ".", "environ", "[", "'SHELL'", "]",...
return the path to the default shell for the current user.
[ "return", "the", "path", "to", "the", "default", "shell", "for", "the", "current", "user", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/utils.py#L91-L106
233,124
prompt-toolkit/pymux
pymux/filters.py
_confirm_or_prompt_or_command
def _confirm_or_prompt_or_command(pymux): " True when we are waiting for a command, prompt or confirmation. " client_state = pymux.get_client_state() if client_state.confirm_text or client_state.prompt_command or client_state.command_mode: return True
python
def _confirm_or_prompt_or_command(pymux): " True when we are waiting for a command, prompt or confirmation. " client_state = pymux.get_client_state() if client_state.confirm_text or client_state.prompt_command or client_state.command_mode: return True
[ "def", "_confirm_or_prompt_or_command", "(", "pymux", ")", ":", "client_state", "=", "pymux", ".", "get_client_state", "(", ")", "if", "client_state", ".", "confirm_text", "or", "client_state", ".", "prompt_command", "or", "client_state", ".", "command_mode", ":", ...
True when we are waiting for a command, prompt or confirmation.
[ "True", "when", "we", "are", "waiting", "for", "a", "command", "prompt", "or", "confirmation", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/filters.py#L61-L65
233,125
cisco-sas/kitty
kitty/model/high_level/base.py
BaseModel.mutate
def mutate(self): ''' Mutate to next state :return: True if mutated, False if not ''' self._get_ready() if self._is_last_index(): return False self._current_index += 1 self._mutate() return True
python
def mutate(self): ''' Mutate to next state :return: True if mutated, False if not ''' self._get_ready() if self._is_last_index(): return False self._current_index += 1 self._mutate() return True
[ "def", "mutate", "(", "self", ")", ":", "self", ".", "_get_ready", "(", ")", "if", "self", ".", "_is_last_index", "(", ")", ":", "return", "False", "self", ".", "_current_index", "+=", "1", "self", ".", "_mutate", "(", ")", "return", "True" ]
Mutate to next state :return: True if mutated, False if not
[ "Mutate", "to", "next", "state" ]
cb0760989dcdfe079e43ac574d872d0b18953a32
https://github.com/cisco-sas/kitty/blob/cb0760989dcdfe079e43ac574d872d0b18953a32/kitty/model/high_level/base.py#L112-L123
233,126
cisco-sas/kitty
kitty/bin/kitty_web_client.py
KittyWebClientApi.get_stats
def get_stats(self): ''' Get kitty stats as a dictionary ''' resp = requests.get('%s/api/stats.json' % self.url) assert(resp.status_code == 200) return resp.json()
python
def get_stats(self): ''' Get kitty stats as a dictionary ''' resp = requests.get('%s/api/stats.json' % self.url) assert(resp.status_code == 200) return resp.json()
[ "def", "get_stats", "(", "self", ")", ":", "resp", "=", "requests", ".", "get", "(", "'%s/api/stats.json'", "%", "self", ".", "url", ")", "assert", "(", "resp", ".", "status_code", "==", "200", ")", "return", "resp", ".", "json", "(", ")" ]
Get kitty stats as a dictionary
[ "Get", "kitty", "stats", "as", "a", "dictionary" ]
cb0760989dcdfe079e43ac574d872d0b18953a32
https://github.com/cisco-sas/kitty/blob/cb0760989dcdfe079e43ac574d872d0b18953a32/kitty/bin/kitty_web_client.py#L49-L55
233,127
cisco-sas/kitty
kitty/fuzzers/base.py
BaseFuzzer._handle_options
def _handle_options(self, option_line): ''' Handle options from command line, in docopt style. This allows passing arguments to the fuzzer from the command line without the need to re-write it in each runner. :param option_line: string with the command line options to be parsed. ''' if option_line is not None: usage = ''' These are the options to the kitty fuzzer object, not the options to the runner. Usage: fuzzer [options] [-v ...] Options: -d --delay <delay> delay between tests in secodes, float number -f --session <session-file> session file name to use -n --no-env-test don't perform environment test before the fuzzing session -r --retest <session-file> retest failed/error tests from a session file -t --test-list <test-list> a comma delimited test list string of the form "-10,12,15-20,30-" -v --verbose be more verbose in the log Removed options: end, start - use --test-list instead ''' options = docopt.docopt(usage, shlex.split(option_line)) # ranges if options['--retest']: retest_file = options['--retest'] try: test_list_str = self._get_test_list_from_session_file(retest_file) except Exception as ex: raise KittyException('Failed to open session file (%s) for retesting: %s' % (retest_file, ex)) else: test_list_str = options['--test-list'] self._set_test_ranges(None, None, test_list_str) # session file session_file = options['--session'] if session_file is not None: self.set_session_file(session_file) # delay between tests delay = options['--delay'] if delay is not None: self.set_delay_between_tests(float(delay)) # environment test skip_env_test = options['--no-env-test'] if skip_env_test: self.set_skip_env_test(True) # verbosity verbosity = options['--verbose'] self.set_verbosity(verbosity)
python
def _handle_options(self, option_line): ''' Handle options from command line, in docopt style. This allows passing arguments to the fuzzer from the command line without the need to re-write it in each runner. :param option_line: string with the command line options to be parsed. ''' if option_line is not None: usage = ''' These are the options to the kitty fuzzer object, not the options to the runner. Usage: fuzzer [options] [-v ...] Options: -d --delay <delay> delay between tests in secodes, float number -f --session <session-file> session file name to use -n --no-env-test don't perform environment test before the fuzzing session -r --retest <session-file> retest failed/error tests from a session file -t --test-list <test-list> a comma delimited test list string of the form "-10,12,15-20,30-" -v --verbose be more verbose in the log Removed options: end, start - use --test-list instead ''' options = docopt.docopt(usage, shlex.split(option_line)) # ranges if options['--retest']: retest_file = options['--retest'] try: test_list_str = self._get_test_list_from_session_file(retest_file) except Exception as ex: raise KittyException('Failed to open session file (%s) for retesting: %s' % (retest_file, ex)) else: test_list_str = options['--test-list'] self._set_test_ranges(None, None, test_list_str) # session file session_file = options['--session'] if session_file is not None: self.set_session_file(session_file) # delay between tests delay = options['--delay'] if delay is not None: self.set_delay_between_tests(float(delay)) # environment test skip_env_test = options['--no-env-test'] if skip_env_test: self.set_skip_env_test(True) # verbosity verbosity = options['--verbose'] self.set_verbosity(verbosity)
[ "def", "_handle_options", "(", "self", ",", "option_line", ")", ":", "if", "option_line", "is", "not", "None", ":", "usage", "=", "'''\n These are the options to the kitty fuzzer object, not the options to the runner.\n\n Usage:\n fuzzer [options]...
Handle options from command line, in docopt style. This allows passing arguments to the fuzzer from the command line without the need to re-write it in each runner. :param option_line: string with the command line options to be parsed.
[ "Handle", "options", "from", "command", "line", "in", "docopt", "style", ".", "This", "allows", "passing", "arguments", "to", "the", "fuzzer", "from", "the", "command", "line", "without", "the", "need", "to", "re", "-", "write", "it", "in", "each", "runner...
cb0760989dcdfe079e43ac574d872d0b18953a32
https://github.com/cisco-sas/kitty/blob/cb0760989dcdfe079e43ac574d872d0b18953a32/kitty/fuzzers/base.py#L128-L184
233,128
cisco-sas/kitty
kitty/fuzzers/base.py
BaseFuzzer.set_model
def set_model(self, model): ''' Set the model to fuzz :type model: :class:`~kitty.model.high_level.base.BaseModel` or a subclass :param model: Model object to fuzz ''' self.model = model if self.model: self.model.set_notification_handler(self) self.handle_stage_changed(model) return self
python
def set_model(self, model): ''' Set the model to fuzz :type model: :class:`~kitty.model.high_level.base.BaseModel` or a subclass :param model: Model object to fuzz ''' self.model = model if self.model: self.model.set_notification_handler(self) self.handle_stage_changed(model) return self
[ "def", "set_model", "(", "self", ",", "model", ")", ":", "self", ".", "model", "=", "model", "if", "self", ".", "model", ":", "self", ".", "model", ".", "set_notification_handler", "(", "self", ")", "self", ".", "handle_stage_changed", "(", "model", ")",...
Set the model to fuzz :type model: :class:`~kitty.model.high_level.base.BaseModel` or a subclass :param model: Model object to fuzz
[ "Set", "the", "model", "to", "fuzz" ]
cb0760989dcdfe079e43ac574d872d0b18953a32
https://github.com/cisco-sas/kitty/blob/cb0760989dcdfe079e43ac574d872d0b18953a32/kitty/fuzzers/base.py#L246-L257
233,129
cisco-sas/kitty
kitty/fuzzers/base.py
BaseFuzzer.set_range
def set_range(self, start_index=0, end_index=None): ''' Set range of tests to run .. deprecated:: use :func:`~kitty.fuzzers.base.BaseFuzzer.set_test_list` :param start_index: index to start at (default=0) :param end_index: index to end at(default=None) ''' if end_index is not None: end_index += 1 self._test_list = StartEndList(start_index, end_index) self.session_info.start_index = start_index self.session_info.current_index = 0 self.session_info.end_index = end_index self.session_info.test_list_str = self._test_list.as_test_list_str() return self
python
def set_range(self, start_index=0, end_index=None): ''' Set range of tests to run .. deprecated:: use :func:`~kitty.fuzzers.base.BaseFuzzer.set_test_list` :param start_index: index to start at (default=0) :param end_index: index to end at(default=None) ''' if end_index is not None: end_index += 1 self._test_list = StartEndList(start_index, end_index) self.session_info.start_index = start_index self.session_info.current_index = 0 self.session_info.end_index = end_index self.session_info.test_list_str = self._test_list.as_test_list_str() return self
[ "def", "set_range", "(", "self", ",", "start_index", "=", "0", ",", "end_index", "=", "None", ")", ":", "if", "end_index", "is", "not", "None", ":", "end_index", "+=", "1", "self", ".", "_test_list", "=", "StartEndList", "(", "start_index", ",", "end_ind...
Set range of tests to run .. deprecated:: use :func:`~kitty.fuzzers.base.BaseFuzzer.set_test_list` :param start_index: index to start at (default=0) :param end_index: index to end at(default=None)
[ "Set", "range", "of", "tests", "to", "run" ]
cb0760989dcdfe079e43ac574d872d0b18953a32
https://github.com/cisco-sas/kitty/blob/cb0760989dcdfe079e43ac574d872d0b18953a32/kitty/fuzzers/base.py#L275-L292
233,130
cisco-sas/kitty
kitty/fuzzers/base.py
BaseFuzzer.start
def start(self): ''' Start the fuzzing session If fuzzer already running, it will return immediatly ''' if self._started: self.logger.warning('called while fuzzer is running. ignoring.') return self._started = True assert(self.model) assert(self.user_interface) assert(self.target) if self._load_session(): self._check_session_validity() self._set_test_ranges( self.session_info.start_index, self.session_info.end_index, self.session_info.test_list_str ) else: self.session_info.kitty_version = _get_current_version() # TODO: write hash for high level self.session_info.data_model_hash = self.model.hash() # if self.session_info.end_index is None: # self.session_info.end_index = self.model.last_index() if self._test_list is None: self._test_list = StartEndList(0, self.model.num_mutations()) else: self._test_list.set_last(self.model.last_index()) list_count = self._test_list.get_count() self._test_list.skip(list_count - 1) self.session_info.end_index = self._test_list.current() self._test_list.reset() self._store_session() self._test_list.skip(self.session_info.current_index) self.session_info.test_list_str = self._test_list.as_test_list_str() self._set_signal_handler() self.user_interface.set_data_provider(self.dataman) self.user_interface.set_continue_event(self._continue_event) self.user_interface.start() self.session_info.start_time = time.time() try: self._start_message() self.target.setup() start_from = self.session_info.current_index if self._skip_env_test: self.logger.info('Skipping environment test') else: self.logger.info('Performing environment test') self._test_environment() self._in_environment_test = False self._test_list.reset() self._test_list.skip(start_from) self.session_info.current_index = start_from self.model.skip(self._test_list.current()) self._start() return True except Exception as e: self.logger.error('Error occurred while fuzzing: %s', repr(e)) self.logger.error(traceback.format_exc()) return False
python
def start(self): ''' Start the fuzzing session If fuzzer already running, it will return immediatly ''' if self._started: self.logger.warning('called while fuzzer is running. ignoring.') return self._started = True assert(self.model) assert(self.user_interface) assert(self.target) if self._load_session(): self._check_session_validity() self._set_test_ranges( self.session_info.start_index, self.session_info.end_index, self.session_info.test_list_str ) else: self.session_info.kitty_version = _get_current_version() # TODO: write hash for high level self.session_info.data_model_hash = self.model.hash() # if self.session_info.end_index is None: # self.session_info.end_index = self.model.last_index() if self._test_list is None: self._test_list = StartEndList(0, self.model.num_mutations()) else: self._test_list.set_last(self.model.last_index()) list_count = self._test_list.get_count() self._test_list.skip(list_count - 1) self.session_info.end_index = self._test_list.current() self._test_list.reset() self._store_session() self._test_list.skip(self.session_info.current_index) self.session_info.test_list_str = self._test_list.as_test_list_str() self._set_signal_handler() self.user_interface.set_data_provider(self.dataman) self.user_interface.set_continue_event(self._continue_event) self.user_interface.start() self.session_info.start_time = time.time() try: self._start_message() self.target.setup() start_from = self.session_info.current_index if self._skip_env_test: self.logger.info('Skipping environment test') else: self.logger.info('Performing environment test') self._test_environment() self._in_environment_test = False self._test_list.reset() self._test_list.skip(start_from) self.session_info.current_index = start_from self.model.skip(self._test_list.current()) self._start() return True except Exception as e: self.logger.error('Error occurred while fuzzing: %s', repr(e)) self.logger.error(traceback.format_exc()) return False
[ "def", "start", "(", "self", ")", ":", "if", "self", ".", "_started", ":", "self", ".", "logger", ".", "warning", "(", "'called while fuzzer is running. ignoring.'", ")", "return", "self", ".", "_started", "=", "True", "assert", "(", "self", ".", "model", ...
Start the fuzzing session If fuzzer already running, it will return immediatly
[ "Start", "the", "fuzzing", "session" ]
cb0760989dcdfe079e43ac574d872d0b18953a32
https://github.com/cisco-sas/kitty/blob/cb0760989dcdfe079e43ac574d872d0b18953a32/kitty/fuzzers/base.py#L331-L396
233,131
cisco-sas/kitty
kitty/fuzzers/base.py
BaseFuzzer.handle_stage_changed
def handle_stage_changed(self, model): ''' handle a stage change in the data model :param model: the data model that was changed ''' stages = model.get_stages() if self.dataman: self.dataman.set('stages', stages)
python
def handle_stage_changed(self, model): ''' handle a stage change in the data model :param model: the data model that was changed ''' stages = model.get_stages() if self.dataman: self.dataman.set('stages', stages)
[ "def", "handle_stage_changed", "(", "self", ",", "model", ")", ":", "stages", "=", "model", ".", "get_stages", "(", ")", "if", "self", ".", "dataman", ":", "self", ".", "dataman", ".", "set", "(", "'stages'", ",", "stages", ")" ]
handle a stage change in the data model :param model: the data model that was changed
[ "handle", "a", "stage", "change", "in", "the", "data", "model" ]
cb0760989dcdfe079e43ac574d872d0b18953a32
https://github.com/cisco-sas/kitty/blob/cb0760989dcdfe079e43ac574d872d0b18953a32/kitty/fuzzers/base.py#L398-L406
233,132
cisco-sas/kitty
kitty/fuzzers/base.py
BaseFuzzer.stop
def stop(self): ''' stop the fuzzing session ''' assert(self.model) assert(self.user_interface) assert(self.target) self.user_interface.stop() self.target.teardown() self.dataman.submit_task(None) self._un_set_signal_handler()
python
def stop(self): ''' stop the fuzzing session ''' assert(self.model) assert(self.user_interface) assert(self.target) self.user_interface.stop() self.target.teardown() self.dataman.submit_task(None) self._un_set_signal_handler()
[ "def", "stop", "(", "self", ")", ":", "assert", "(", "self", ".", "model", ")", "assert", "(", "self", ".", "user_interface", ")", "assert", "(", "self", ".", "target", ")", "self", ".", "user_interface", ".", "stop", "(", ")", "self", ".", "target",...
stop the fuzzing session
[ "stop", "the", "fuzzing", "session" ]
cb0760989dcdfe079e43ac574d872d0b18953a32
https://github.com/cisco-sas/kitty/blob/cb0760989dcdfe079e43ac574d872d0b18953a32/kitty/fuzzers/base.py#L522-L532
233,133
cisco-sas/kitty
kitty/fuzzers/base.py
BaseFuzzer._keep_running
def _keep_running(self): ''' Should we still fuzz?? ''' if self.config.max_failures: if self.session_info.failure_count >= self.config.max_failures: return False return self._test_list.current() is not None
python
def _keep_running(self): ''' Should we still fuzz?? ''' if self.config.max_failures: if self.session_info.failure_count >= self.config.max_failures: return False return self._test_list.current() is not None
[ "def", "_keep_running", "(", "self", ")", ":", "if", "self", ".", "config", ".", "max_failures", ":", "if", "self", ".", "session_info", ".", "failure_count", ">=", "self", ".", "config", ".", "max_failures", ":", "return", "False", "return", "self", ".", ...
Should we still fuzz??
[ "Should", "we", "still", "fuzz??" ]
cb0760989dcdfe079e43ac574d872d0b18953a32
https://github.com/cisco-sas/kitty/blob/cb0760989dcdfe079e43ac574d872d0b18953a32/kitty/fuzzers/base.py#L595-L602
233,134
cisco-sas/kitty
kitty/core/kitty_object.py
KittyObject.set_verbosity
def set_verbosity(cls, verbosity): ''' Set verbosity of logger :param verbosity: verbosity level. currently, we only support 1 (logging.DEBUG) ''' if verbosity > 0: # currently, we only toggle between INFO, DEBUG logger = KittyObject.get_logger() levels = [logging.DEBUG] verbosity = min(verbosity, len(levels)) - 1 logger.setLevel(levels[verbosity])
python
def set_verbosity(cls, verbosity): ''' Set verbosity of logger :param verbosity: verbosity level. currently, we only support 1 (logging.DEBUG) ''' if verbosity > 0: # currently, we only toggle between INFO, DEBUG logger = KittyObject.get_logger() levels = [logging.DEBUG] verbosity = min(verbosity, len(levels)) - 1 logger.setLevel(levels[verbosity])
[ "def", "set_verbosity", "(", "cls", ",", "verbosity", ")", ":", "if", "verbosity", ">", "0", ":", "# currently, we only toggle between INFO, DEBUG", "logger", "=", "KittyObject", ".", "get_logger", "(", ")", "levels", "=", "[", "logging", ".", "DEBUG", "]", "v...
Set verbosity of logger :param verbosity: verbosity level. currently, we only support 1 (logging.DEBUG)
[ "Set", "verbosity", "of", "logger" ]
cb0760989dcdfe079e43ac574d872d0b18953a32
https://github.com/cisco-sas/kitty/blob/cb0760989dcdfe079e43ac574d872d0b18953a32/kitty/core/kitty_object.py#L65-L76
233,135
cisco-sas/kitty
kitty/core/kitty_object.py
KittyObject.not_implemented
def not_implemented(self, func_name): ''' log access to unimplemented method and raise error :param func_name: name of unimplemented function. :raise: NotImplementedError detailing the function the is not implemented. ''' msg = '%s is not overridden by %s' % (func_name, type(self).__name__) self.logger.error(msg) raise NotImplementedError(msg)
python
def not_implemented(self, func_name): ''' log access to unimplemented method and raise error :param func_name: name of unimplemented function. :raise: NotImplementedError detailing the function the is not implemented. ''' msg = '%s is not overridden by %s' % (func_name, type(self).__name__) self.logger.error(msg) raise NotImplementedError(msg)
[ "def", "not_implemented", "(", "self", ",", "func_name", ")", ":", "msg", "=", "'%s is not overridden by %s'", "%", "(", "func_name", ",", "type", "(", "self", ")", ".", "__name__", ")", "self", ".", "logger", ".", "error", "(", "msg", ")", "raise", "Not...
log access to unimplemented method and raise error :param func_name: name of unimplemented function. :raise: NotImplementedError detailing the function the is not implemented.
[ "log", "access", "to", "unimplemented", "method", "and", "raise", "error" ]
cb0760989dcdfe079e43ac574d872d0b18953a32
https://github.com/cisco-sas/kitty/blob/cb0760989dcdfe079e43ac574d872d0b18953a32/kitty/core/kitty_object.py#L88-L97
233,136
cisco-sas/kitty
kitty/data/data_manager.py
synced
def synced(func): ''' Decorator for functions that should be called synchronously from another thread :param func: function to call ''' def wrapper(self, *args, **kwargs): ''' Actual wrapper for the synchronous function ''' task = DataManagerTask(func, *args, **kwargs) self.submit_task(task) return task.get_results() return wrapper
python
def synced(func): ''' Decorator for functions that should be called synchronously from another thread :param func: function to call ''' def wrapper(self, *args, **kwargs): ''' Actual wrapper for the synchronous function ''' task = DataManagerTask(func, *args, **kwargs) self.submit_task(task) return task.get_results() return wrapper
[ "def", "synced", "(", "func", ")", ":", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "'''\n Actual wrapper for the synchronous function\n '''", "task", "=", "DataManagerTask", "(", "func", ",", "*", "args", ...
Decorator for functions that should be called synchronously from another thread :param func: function to call
[ "Decorator", "for", "functions", "that", "should", "be", "called", "synchronously", "from", "another", "thread" ]
cb0760989dcdfe079e43ac574d872d0b18953a32
https://github.com/cisco-sas/kitty/blob/cb0760989dcdfe079e43ac574d872d0b18953a32/kitty/data/data_manager.py#L89-L103
233,137
cisco-sas/kitty
kitty/data/data_manager.py
DataManagerTask.execute
def execute(self, dataman): ''' run the task :type dataman: :class:`~kitty.data.data_manager.DataManager` :param dataman: the executing data manager ''' self._event.clear() try: self._result = self._task(dataman, *self._args) # # We are going to re-throw this exception from get_results, # so we are doing such a general eception handling at the point. # however, we do want to print it here as well # except Exception as ex: # pylint: disable=W0703 self._exception = ex KittyObject.get_logger().error(traceback.format_exc()) self._event.set()
python
def execute(self, dataman): ''' run the task :type dataman: :class:`~kitty.data.data_manager.DataManager` :param dataman: the executing data manager ''' self._event.clear() try: self._result = self._task(dataman, *self._args) # # We are going to re-throw this exception from get_results, # so we are doing such a general eception handling at the point. # however, we do want to print it here as well # except Exception as ex: # pylint: disable=W0703 self._exception = ex KittyObject.get_logger().error(traceback.format_exc()) self._event.set()
[ "def", "execute", "(", "self", ",", "dataman", ")", ":", "self", ".", "_event", ".", "clear", "(", ")", "try", ":", "self", ".", "_result", "=", "self", ".", "_task", "(", "dataman", ",", "*", "self", ".", "_args", ")", "#", "# We are going to re-thr...
run the task :type dataman: :class:`~kitty.data.data_manager.DataManager` :param dataman: the executing data manager
[ "run", "the", "task" ]
cb0760989dcdfe079e43ac574d872d0b18953a32
https://github.com/cisco-sas/kitty/blob/cb0760989dcdfe079e43ac574d872d0b18953a32/kitty/data/data_manager.py#L55-L73
233,138
cisco-sas/kitty
kitty/data/data_manager.py
DataManager.open
def open(self): ''' open the database ''' self._connection = sqlite3.connect(self._dbname) self._cursor = self._connection.cursor() self._session_info = SessionInfoTable(self._connection, self._cursor) self._reports = ReportsTable(self._connection, self._cursor)
python
def open(self): ''' open the database ''' self._connection = sqlite3.connect(self._dbname) self._cursor = self._connection.cursor() self._session_info = SessionInfoTable(self._connection, self._cursor) self._reports = ReportsTable(self._connection, self._cursor)
[ "def", "open", "(", "self", ")", ":", "self", ".", "_connection", "=", "sqlite3", ".", "connect", "(", "self", ".", "_dbname", ")", "self", ".", "_cursor", "=", "self", ".", "_connection", ".", "cursor", "(", ")", "self", ".", "_session_info", "=", "...
open the database
[ "open", "the", "database" ]
cb0760989dcdfe079e43ac574d872d0b18953a32
https://github.com/cisco-sas/kitty/blob/cb0760989dcdfe079e43ac574d872d0b18953a32/kitty/data/data_manager.py#L162-L169
233,139
cisco-sas/kitty
kitty/data/data_manager.py
DataManager.set
def set(self, key, data): ''' set arbitrary data by key in volatile memory :param key: key of the data :param data: data to be stored ''' if isinstance(data, dict): self._volatile_data[key] = {k: v for (k, v) in data.items()} else: self._volatile_data[key] = data
python
def set(self, key, data): ''' set arbitrary data by key in volatile memory :param key: key of the data :param data: data to be stored ''' if isinstance(data, dict): self._volatile_data[key] = {k: v for (k, v) in data.items()} else: self._volatile_data[key] = data
[ "def", "set", "(", "self", ",", "key", ",", "data", ")", ":", "if", "isinstance", "(", "data", ",", "dict", ")", ":", "self", ".", "_volatile_data", "[", "key", "]", "=", "{", "k", ":", "v", "for", "(", "k", ",", "v", ")", "in", "data", ".", ...
set arbitrary data by key in volatile memory :param key: key of the data :param data: data to be stored
[ "set", "arbitrary", "data", "by", "key", "in", "volatile", "memory" ]
cb0760989dcdfe079e43ac574d872d0b18953a32
https://github.com/cisco-sas/kitty/blob/cb0760989dcdfe079e43ac574d872d0b18953a32/kitty/data/data_manager.py#L248-L258
233,140
cisco-sas/kitty
kitty/data/data_manager.py
Table.row_to_dict
def row_to_dict(self, row): ''' translate a row of the current table to dictionary :param row: a row of the current table (selected with \\*) :return: dictionary of all fields ''' res = {} for i in range(len(self._fields)): res[self._fields[i][0]] = row[i] return res
python
def row_to_dict(self, row): ''' translate a row of the current table to dictionary :param row: a row of the current table (selected with \\*) :return: dictionary of all fields ''' res = {} for i in range(len(self._fields)): res[self._fields[i][0]] = row[i] return res
[ "def", "row_to_dict", "(", "self", ",", "row", ")", ":", "res", "=", "{", "}", "for", "i", "in", "range", "(", "len", "(", "self", ".", "_fields", ")", ")", ":", "res", "[", "self", ".", "_fields", "[", "i", "]", "[", "0", "]", "]", "=", "r...
translate a row of the current table to dictionary :param row: a row of the current table (selected with \\*) :return: dictionary of all fields
[ "translate", "a", "row", "of", "the", "current", "table", "to", "dictionary" ]
cb0760989dcdfe079e43ac574d872d0b18953a32
https://github.com/cisco-sas/kitty/blob/cb0760989dcdfe079e43ac574d872d0b18953a32/kitty/data/data_manager.py#L319-L329
233,141
aaugustin/websockets
src/websockets/protocol.py
WebSocketCommonProtocol.ensure_open
async def ensure_open(self) -> None: """ Check that the WebSocket connection is open. Raise :exc:`~websockets.exceptions.ConnectionClosed` if it isn't. """ # Handle cases from most common to least common for performance. if self.state is State.OPEN: # If self.transfer_data_task exited without a closing handshake, # self.close_connection_task may be closing it, going straight # from OPEN to CLOSED. if self.transfer_data_task.done(): await asyncio.shield(self.close_connection_task) raise ConnectionClosed( self.close_code, self.close_reason ) from self.transfer_data_exc else: return if self.state is State.CLOSED: raise ConnectionClosed( self.close_code, self.close_reason ) from self.transfer_data_exc if self.state is State.CLOSING: # If we started the closing handshake, wait for its completion to # get the proper close code and status. self.close_connection_task # will complete within 4 or 5 * close_timeout after close(). The # CLOSING state also occurs when failing the connection. In that # case self.close_connection_task will complete even faster. await asyncio.shield(self.close_connection_task) raise ConnectionClosed( self.close_code, self.close_reason ) from self.transfer_data_exc # Control may only reach this point in buggy third-party subclasses. assert self.state is State.CONNECTING raise InvalidState("WebSocket connection isn't established yet")
python
async def ensure_open(self) -> None: # Handle cases from most common to least common for performance. if self.state is State.OPEN: # If self.transfer_data_task exited without a closing handshake, # self.close_connection_task may be closing it, going straight # from OPEN to CLOSED. if self.transfer_data_task.done(): await asyncio.shield(self.close_connection_task) raise ConnectionClosed( self.close_code, self.close_reason ) from self.transfer_data_exc else: return if self.state is State.CLOSED: raise ConnectionClosed( self.close_code, self.close_reason ) from self.transfer_data_exc if self.state is State.CLOSING: # If we started the closing handshake, wait for its completion to # get the proper close code and status. self.close_connection_task # will complete within 4 or 5 * close_timeout after close(). The # CLOSING state also occurs when failing the connection. In that # case self.close_connection_task will complete even faster. await asyncio.shield(self.close_connection_task) raise ConnectionClosed( self.close_code, self.close_reason ) from self.transfer_data_exc # Control may only reach this point in buggy third-party subclasses. assert self.state is State.CONNECTING raise InvalidState("WebSocket connection isn't established yet")
[ "async", "def", "ensure_open", "(", "self", ")", "->", "None", ":", "# Handle cases from most common to least common for performance.", "if", "self", ".", "state", "is", "State", ".", "OPEN", ":", "# If self.transfer_data_task exited without a closing handshake,", "# self.clo...
Check that the WebSocket connection is open. Raise :exc:`~websockets.exceptions.ConnectionClosed` if it isn't.
[ "Check", "that", "the", "WebSocket", "connection", "is", "open", "." ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/protocol.py#L662-L700
233,142
aaugustin/websockets
src/websockets/protocol.py
WebSocketCommonProtocol.transfer_data
async def transfer_data(self) -> None: """ Read incoming messages and put them in a queue. This coroutine runs in a task until the closing handshake is started. """ try: while True: message = await self.read_message() # Exit the loop when receiving a close frame. if message is None: break # Wait until there's room in the queue (if necessary). if self.max_queue is not None: while len(self.messages) >= self.max_queue: self._put_message_waiter = self.loop.create_future() try: await self._put_message_waiter finally: self._put_message_waiter = None # Put the message in the queue. self.messages.append(message) # Notify recv(). if self._pop_message_waiter is not None: self._pop_message_waiter.set_result(None) self._pop_message_waiter = None except asyncio.CancelledError as exc: self.transfer_data_exc = exc # If fail_connection() cancels this task, avoid logging the error # twice and failing the connection again. raise except WebSocketProtocolError as exc: self.transfer_data_exc = exc self.fail_connection(1002) except (ConnectionError, EOFError) as exc: # Reading data with self.reader.readexactly may raise: # - most subclasses of ConnectionError if the TCP connection # breaks, is reset, or is aborted; # - IncompleteReadError, a subclass of EOFError, if fewer # bytes are available than requested. self.transfer_data_exc = exc self.fail_connection(1006) except UnicodeDecodeError as exc: self.transfer_data_exc = exc self.fail_connection(1007) except PayloadTooBig as exc: self.transfer_data_exc = exc self.fail_connection(1009) except Exception as exc: # This shouldn't happen often because exceptions expected under # regular circumstances are handled above. If it does, consider # catching and handling more exceptions. logger.error("Error in data transfer", exc_info=True) self.transfer_data_exc = exc self.fail_connection(1011)
python
async def transfer_data(self) -> None: try: while True: message = await self.read_message() # Exit the loop when receiving a close frame. if message is None: break # Wait until there's room in the queue (if necessary). if self.max_queue is not None: while len(self.messages) >= self.max_queue: self._put_message_waiter = self.loop.create_future() try: await self._put_message_waiter finally: self._put_message_waiter = None # Put the message in the queue. self.messages.append(message) # Notify recv(). if self._pop_message_waiter is not None: self._pop_message_waiter.set_result(None) self._pop_message_waiter = None except asyncio.CancelledError as exc: self.transfer_data_exc = exc # If fail_connection() cancels this task, avoid logging the error # twice and failing the connection again. raise except WebSocketProtocolError as exc: self.transfer_data_exc = exc self.fail_connection(1002) except (ConnectionError, EOFError) as exc: # Reading data with self.reader.readexactly may raise: # - most subclasses of ConnectionError if the TCP connection # breaks, is reset, or is aborted; # - IncompleteReadError, a subclass of EOFError, if fewer # bytes are available than requested. self.transfer_data_exc = exc self.fail_connection(1006) except UnicodeDecodeError as exc: self.transfer_data_exc = exc self.fail_connection(1007) except PayloadTooBig as exc: self.transfer_data_exc = exc self.fail_connection(1009) except Exception as exc: # This shouldn't happen often because exceptions expected under # regular circumstances are handled above. If it does, consider # catching and handling more exceptions. logger.error("Error in data transfer", exc_info=True) self.transfer_data_exc = exc self.fail_connection(1011)
[ "async", "def", "transfer_data", "(", "self", ")", "->", "None", ":", "try", ":", "while", "True", ":", "message", "=", "await", "self", ".", "read_message", "(", ")", "# Exit the loop when receiving a close frame.", "if", "message", "is", "None", ":", "break"...
Read incoming messages and put them in a queue. This coroutine runs in a task until the closing handshake is started.
[ "Read", "incoming", "messages", "and", "put", "them", "in", "a", "queue", "." ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/protocol.py#L702-L768
233,143
aaugustin/websockets
src/websockets/protocol.py
WebSocketCommonProtocol.read_message
async def read_message(self) -> Optional[Data]: """ Read a single message from the connection. Re-assemble data frames if the message is fragmented. Return ``None`` when the closing handshake is started. """ frame = await self.read_data_frame(max_size=self.max_size) # A close frame was received. if frame is None: return None if frame.opcode == OP_TEXT: text = True elif frame.opcode == OP_BINARY: text = False else: # frame.opcode == OP_CONT raise WebSocketProtocolError("Unexpected opcode") # Shortcut for the common case - no fragmentation if frame.fin: return frame.data.decode("utf-8") if text else frame.data # 5.4. Fragmentation chunks: List[Data] = [] max_size = self.max_size if text: decoder_factory = codecs.getincrementaldecoder("utf-8") # https://github.com/python/typeshed/pull/2752 decoder = decoder_factory(errors="strict") # type: ignore if max_size is None: def append(frame: Frame) -> None: nonlocal chunks chunks.append(decoder.decode(frame.data, frame.fin)) else: def append(frame: Frame) -> None: nonlocal chunks, max_size chunks.append(decoder.decode(frame.data, frame.fin)) max_size -= len(frame.data) else: if max_size is None: def append(frame: Frame) -> None: nonlocal chunks chunks.append(frame.data) else: def append(frame: Frame) -> None: nonlocal chunks, max_size chunks.append(frame.data) max_size -= len(frame.data) append(frame) while not frame.fin: frame = await self.read_data_frame(max_size=max_size) if frame is None: raise WebSocketProtocolError("Incomplete fragmented message") if frame.opcode != OP_CONT: raise WebSocketProtocolError("Unexpected opcode") append(frame) # mypy cannot figure out that chunks have the proper type. return ("" if text else b"").join(chunks)
python
async def read_message(self) -> Optional[Data]: frame = await self.read_data_frame(max_size=self.max_size) # A close frame was received. if frame is None: return None if frame.opcode == OP_TEXT: text = True elif frame.opcode == OP_BINARY: text = False else: # frame.opcode == OP_CONT raise WebSocketProtocolError("Unexpected opcode") # Shortcut for the common case - no fragmentation if frame.fin: return frame.data.decode("utf-8") if text else frame.data # 5.4. Fragmentation chunks: List[Data] = [] max_size = self.max_size if text: decoder_factory = codecs.getincrementaldecoder("utf-8") # https://github.com/python/typeshed/pull/2752 decoder = decoder_factory(errors="strict") # type: ignore if max_size is None: def append(frame: Frame) -> None: nonlocal chunks chunks.append(decoder.decode(frame.data, frame.fin)) else: def append(frame: Frame) -> None: nonlocal chunks, max_size chunks.append(decoder.decode(frame.data, frame.fin)) max_size -= len(frame.data) else: if max_size is None: def append(frame: Frame) -> None: nonlocal chunks chunks.append(frame.data) else: def append(frame: Frame) -> None: nonlocal chunks, max_size chunks.append(frame.data) max_size -= len(frame.data) append(frame) while not frame.fin: frame = await self.read_data_frame(max_size=max_size) if frame is None: raise WebSocketProtocolError("Incomplete fragmented message") if frame.opcode != OP_CONT: raise WebSocketProtocolError("Unexpected opcode") append(frame) # mypy cannot figure out that chunks have the proper type. return ("" if text else b"").join(chunks)
[ "async", "def", "read_message", "(", "self", ")", "->", "Optional", "[", "Data", "]", ":", "frame", "=", "await", "self", ".", "read_data_frame", "(", "max_size", "=", "self", ".", "max_size", ")", "# A close frame was received.", "if", "frame", "is", "None"...
Read a single message from the connection. Re-assemble data frames if the message is fragmented. Return ``None`` when the closing handshake is started.
[ "Read", "a", "single", "message", "from", "the", "connection", "." ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/protocol.py#L770-L841
233,144
aaugustin/websockets
src/websockets/protocol.py
WebSocketCommonProtocol.read_data_frame
async def read_data_frame(self, max_size: int) -> Optional[Frame]: """ Read a single data frame from the connection. Process control frames received before the next data frame. Return ``None`` if a close frame is encountered before any data frame. """ # 6.2. Receiving Data while True: frame = await self.read_frame(max_size) # 5.5. Control Frames if frame.opcode == OP_CLOSE: # 7.1.5. The WebSocket Connection Close Code # 7.1.6. The WebSocket Connection Close Reason self.close_code, self.close_reason = parse_close(frame.data) # Echo the original data instead of re-serializing it with # serialize_close() because that fails when the close frame is # empty and parse_close() synthetizes a 1005 close code. await self.write_close_frame(frame.data) return None elif frame.opcode == OP_PING: # Answer pings. ping_hex = frame.data.hex() or "[empty]" logger.debug( "%s - received ping, sending pong: %s", self.side, ping_hex ) await self.pong(frame.data) elif frame.opcode == OP_PONG: # Acknowledge pings on solicited pongs. if frame.data in self.pings: # Acknowledge all pings up to the one matching this pong. ping_id = None ping_ids = [] while ping_id != frame.data: ping_id, pong_waiter = self.pings.popitem(last=False) ping_ids.append(ping_id) pong_waiter.set_result(None) pong_hex = binascii.hexlify(frame.data).decode() or "[empty]" logger.debug( "%s - received solicited pong: %s", self.side, pong_hex ) ping_ids = ping_ids[:-1] if ping_ids: pings_hex = ", ".join( binascii.hexlify(ping_id).decode() or "[empty]" for ping_id in ping_ids ) plural = "s" if len(ping_ids) > 1 else "" logger.debug( "%s - acknowledged previous ping%s: %s", self.side, plural, pings_hex, ) else: pong_hex = binascii.hexlify(frame.data).decode() or "[empty]" logger.debug( "%s - received unsolicited pong: %s", self.side, pong_hex ) # 5.6. Data Frames else: return frame
python
async def read_data_frame(self, max_size: int) -> Optional[Frame]: # 6.2. Receiving Data while True: frame = await self.read_frame(max_size) # 5.5. Control Frames if frame.opcode == OP_CLOSE: # 7.1.5. The WebSocket Connection Close Code # 7.1.6. The WebSocket Connection Close Reason self.close_code, self.close_reason = parse_close(frame.data) # Echo the original data instead of re-serializing it with # serialize_close() because that fails when the close frame is # empty and parse_close() synthetizes a 1005 close code. await self.write_close_frame(frame.data) return None elif frame.opcode == OP_PING: # Answer pings. ping_hex = frame.data.hex() or "[empty]" logger.debug( "%s - received ping, sending pong: %s", self.side, ping_hex ) await self.pong(frame.data) elif frame.opcode == OP_PONG: # Acknowledge pings on solicited pongs. if frame.data in self.pings: # Acknowledge all pings up to the one matching this pong. ping_id = None ping_ids = [] while ping_id != frame.data: ping_id, pong_waiter = self.pings.popitem(last=False) ping_ids.append(ping_id) pong_waiter.set_result(None) pong_hex = binascii.hexlify(frame.data).decode() or "[empty]" logger.debug( "%s - received solicited pong: %s", self.side, pong_hex ) ping_ids = ping_ids[:-1] if ping_ids: pings_hex = ", ".join( binascii.hexlify(ping_id).decode() or "[empty]" for ping_id in ping_ids ) plural = "s" if len(ping_ids) > 1 else "" logger.debug( "%s - acknowledged previous ping%s: %s", self.side, plural, pings_hex, ) else: pong_hex = binascii.hexlify(frame.data).decode() or "[empty]" logger.debug( "%s - received unsolicited pong: %s", self.side, pong_hex ) # 5.6. Data Frames else: return frame
[ "async", "def", "read_data_frame", "(", "self", ",", "max_size", ":", "int", ")", "->", "Optional", "[", "Frame", "]", ":", "# 6.2. Receiving Data", "while", "True", ":", "frame", "=", "await", "self", ".", "read_frame", "(", "max_size", ")", "# 5.5. Control...
Read a single data frame from the connection. Process control frames received before the next data frame. Return ``None`` if a close frame is encountered before any data frame.
[ "Read", "a", "single", "data", "frame", "from", "the", "connection", "." ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/protocol.py#L843-L910
233,145
aaugustin/websockets
src/websockets/protocol.py
WebSocketCommonProtocol.read_frame
async def read_frame(self, max_size: int) -> Frame: """ Read a single frame from the connection. """ frame = await Frame.read( self.reader.readexactly, mask=not self.is_client, max_size=max_size, extensions=self.extensions, ) logger.debug("%s < %r", self.side, frame) return frame
python
async def read_frame(self, max_size: int) -> Frame: frame = await Frame.read( self.reader.readexactly, mask=not self.is_client, max_size=max_size, extensions=self.extensions, ) logger.debug("%s < %r", self.side, frame) return frame
[ "async", "def", "read_frame", "(", "self", ",", "max_size", ":", "int", ")", "->", "Frame", ":", "frame", "=", "await", "Frame", ".", "read", "(", "self", ".", "reader", ".", "readexactly", ",", "mask", "=", "not", "self", ".", "is_client", ",", "max...
Read a single frame from the connection.
[ "Read", "a", "single", "frame", "from", "the", "connection", "." ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/protocol.py#L912-L924
233,146
aaugustin/websockets
src/websockets/protocol.py
WebSocketCommonProtocol.write_close_frame
async def write_close_frame(self, data: bytes = b"") -> None: """ Write a close frame if and only if the connection state is OPEN. This dedicated coroutine must be used for writing close frames to ensure that at most one close frame is sent on a given connection. """ # Test and set the connection state before sending the close frame to # avoid sending two frames in case of concurrent calls. if self.state is State.OPEN: # 7.1.3. The WebSocket Closing Handshake is Started self.state = State.CLOSING logger.debug("%s - state = CLOSING", self.side) # 7.1.2. Start the WebSocket Closing Handshake await self.write_frame(True, OP_CLOSE, data, _expected_state=State.CLOSING)
python
async def write_close_frame(self, data: bytes = b"") -> None: # Test and set the connection state before sending the close frame to # avoid sending two frames in case of concurrent calls. if self.state is State.OPEN: # 7.1.3. The WebSocket Closing Handshake is Started self.state = State.CLOSING logger.debug("%s - state = CLOSING", self.side) # 7.1.2. Start the WebSocket Closing Handshake await self.write_frame(True, OP_CLOSE, data, _expected_state=State.CLOSING)
[ "async", "def", "write_close_frame", "(", "self", ",", "data", ":", "bytes", "=", "b\"\"", ")", "->", "None", ":", "# Test and set the connection state before sending the close frame to", "# avoid sending two frames in case of concurrent calls.", "if", "self", ".", "state", ...
Write a close frame if and only if the connection state is OPEN. This dedicated coroutine must be used for writing close frames to ensure that at most one close frame is sent on a given connection.
[ "Write", "a", "close", "frame", "if", "and", "only", "if", "the", "connection", "state", "is", "OPEN", "." ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/protocol.py#L953-L969
233,147
aaugustin/websockets
src/websockets/protocol.py
WebSocketCommonProtocol.keepalive_ping
async def keepalive_ping(self) -> None: """ Send a Ping frame and wait for a Pong frame at regular intervals. This coroutine exits when the connection terminates and one of the following happens: - :meth:`ping` raises :exc:`ConnectionClosed`, or - :meth:`close_connection` cancels :attr:`keepalive_ping_task`. """ if self.ping_interval is None: return try: while True: await asyncio.sleep(self.ping_interval, loop=self.loop) # ping() cannot raise ConnectionClosed, only CancelledError: # - If the connection is CLOSING, keepalive_ping_task will be # canceled by close_connection() before ping() returns. # - If the connection is CLOSED, keepalive_ping_task must be # canceled already. ping_waiter = await self.ping() if self.ping_timeout is not None: try: await asyncio.wait_for( ping_waiter, self.ping_timeout, loop=self.loop ) except asyncio.TimeoutError: logger.debug("%s ! timed out waiting for pong", self.side) self.fail_connection(1011) break except asyncio.CancelledError: raise except Exception: logger.warning("Unexpected exception in keepalive ping task", exc_info=True)
python
async def keepalive_ping(self) -> None: if self.ping_interval is None: return try: while True: await asyncio.sleep(self.ping_interval, loop=self.loop) # ping() cannot raise ConnectionClosed, only CancelledError: # - If the connection is CLOSING, keepalive_ping_task will be # canceled by close_connection() before ping() returns. # - If the connection is CLOSED, keepalive_ping_task must be # canceled already. ping_waiter = await self.ping() if self.ping_timeout is not None: try: await asyncio.wait_for( ping_waiter, self.ping_timeout, loop=self.loop ) except asyncio.TimeoutError: logger.debug("%s ! timed out waiting for pong", self.side) self.fail_connection(1011) break except asyncio.CancelledError: raise except Exception: logger.warning("Unexpected exception in keepalive ping task", exc_info=True)
[ "async", "def", "keepalive_ping", "(", "self", ")", "->", "None", ":", "if", "self", ".", "ping_interval", "is", "None", ":", "return", "try", ":", "while", "True", ":", "await", "asyncio", ".", "sleep", "(", "self", ".", "ping_interval", ",", "loop", ...
Send a Ping frame and wait for a Pong frame at regular intervals. This coroutine exits when the connection terminates and one of the following happens: - :meth:`ping` raises :exc:`ConnectionClosed`, or - :meth:`close_connection` cancels :attr:`keepalive_ping_task`.
[ "Send", "a", "Ping", "frame", "and", "wait", "for", "a", "Pong", "frame", "at", "regular", "intervals", "." ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/protocol.py#L971-L1009
233,148
aaugustin/websockets
src/websockets/protocol.py
WebSocketCommonProtocol.close_connection
async def close_connection(self) -> None: """ 7.1.1. Close the WebSocket Connection When the opening handshake succeeds, :meth:`connection_open` starts this coroutine in a task. It waits for the data transfer phase to complete then it closes the TCP connection cleanly. When the opening handshake fails, :meth:`fail_connection` does the same. There's no data transfer phase in that case. """ try: # Wait for the data transfer phase to complete. if hasattr(self, "transfer_data_task"): try: await self.transfer_data_task except asyncio.CancelledError: pass # Cancel the keepalive ping task. if hasattr(self, "keepalive_ping_task"): self.keepalive_ping_task.cancel() # A client should wait for a TCP close from the server. if self.is_client and hasattr(self, "transfer_data_task"): if await self.wait_for_connection_lost(): return logger.debug("%s ! timed out waiting for TCP close", self.side) # Half-close the TCP connection if possible (when there's no TLS). if self.writer.can_write_eof(): logger.debug("%s x half-closing TCP connection", self.side) self.writer.write_eof() if await self.wait_for_connection_lost(): return logger.debug("%s ! timed out waiting for TCP close", self.side) finally: # The try/finally ensures that the transport never remains open, # even if this coroutine is canceled (for example). # If connection_lost() was called, the TCP connection is closed. # However, if TLS is enabled, the transport still needs closing. # Else asyncio complains: ResourceWarning: unclosed transport. if self.connection_lost_waiter.done() and not self.secure: return # Close the TCP connection. Buffers are flushed asynchronously. logger.debug("%s x closing TCP connection", self.side) self.writer.close() if await self.wait_for_connection_lost(): return logger.debug("%s ! timed out waiting for TCP close", self.side) # Abort the TCP connection. Buffers are discarded. logger.debug("%s x aborting TCP connection", self.side) # mypy thinks self.writer.transport is a BaseTransport, not a Transport. self.writer.transport.abort() # type: ignore # connection_lost() is called quickly after aborting. await self.wait_for_connection_lost()
python
async def close_connection(self) -> None: try: # Wait for the data transfer phase to complete. if hasattr(self, "transfer_data_task"): try: await self.transfer_data_task except asyncio.CancelledError: pass # Cancel the keepalive ping task. if hasattr(self, "keepalive_ping_task"): self.keepalive_ping_task.cancel() # A client should wait for a TCP close from the server. if self.is_client and hasattr(self, "transfer_data_task"): if await self.wait_for_connection_lost(): return logger.debug("%s ! timed out waiting for TCP close", self.side) # Half-close the TCP connection if possible (when there's no TLS). if self.writer.can_write_eof(): logger.debug("%s x half-closing TCP connection", self.side) self.writer.write_eof() if await self.wait_for_connection_lost(): return logger.debug("%s ! timed out waiting for TCP close", self.side) finally: # The try/finally ensures that the transport never remains open, # even if this coroutine is canceled (for example). # If connection_lost() was called, the TCP connection is closed. # However, if TLS is enabled, the transport still needs closing. # Else asyncio complains: ResourceWarning: unclosed transport. if self.connection_lost_waiter.done() and not self.secure: return # Close the TCP connection. Buffers are flushed asynchronously. logger.debug("%s x closing TCP connection", self.side) self.writer.close() if await self.wait_for_connection_lost(): return logger.debug("%s ! timed out waiting for TCP close", self.side) # Abort the TCP connection. Buffers are discarded. logger.debug("%s x aborting TCP connection", self.side) # mypy thinks self.writer.transport is a BaseTransport, not a Transport. self.writer.transport.abort() # type: ignore # connection_lost() is called quickly after aborting. await self.wait_for_connection_lost()
[ "async", "def", "close_connection", "(", "self", ")", "->", "None", ":", "try", ":", "# Wait for the data transfer phase to complete.", "if", "hasattr", "(", "self", ",", "\"transfer_data_task\"", ")", ":", "try", ":", "await", "self", ".", "transfer_data_task", "...
7.1.1. Close the WebSocket Connection When the opening handshake succeeds, :meth:`connection_open` starts this coroutine in a task. It waits for the data transfer phase to complete then it closes the TCP connection cleanly. When the opening handshake fails, :meth:`fail_connection` does the same. There's no data transfer phase in that case.
[ "7", ".", "1", ".", "1", ".", "Close", "the", "WebSocket", "Connection" ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/protocol.py#L1011-L1074
233,149
aaugustin/websockets
src/websockets/protocol.py
WebSocketCommonProtocol.wait_for_connection_lost
async def wait_for_connection_lost(self) -> bool: """ Wait until the TCP connection is closed or ``self.close_timeout`` elapses. Return ``True`` if the connection is closed and ``False`` otherwise. """ if not self.connection_lost_waiter.done(): try: await asyncio.wait_for( asyncio.shield(self.connection_lost_waiter), self.close_timeout, loop=self.loop, ) except asyncio.TimeoutError: pass # Re-check self.connection_lost_waiter.done() synchronously because # connection_lost() could run between the moment the timeout occurs # and the moment this coroutine resumes running. return self.connection_lost_waiter.done()
python
async def wait_for_connection_lost(self) -> bool: if not self.connection_lost_waiter.done(): try: await asyncio.wait_for( asyncio.shield(self.connection_lost_waiter), self.close_timeout, loop=self.loop, ) except asyncio.TimeoutError: pass # Re-check self.connection_lost_waiter.done() synchronously because # connection_lost() could run between the moment the timeout occurs # and the moment this coroutine resumes running. return self.connection_lost_waiter.done()
[ "async", "def", "wait_for_connection_lost", "(", "self", ")", "->", "bool", ":", "if", "not", "self", ".", "connection_lost_waiter", ".", "done", "(", ")", ":", "try", ":", "await", "asyncio", ".", "wait_for", "(", "asyncio", ".", "shield", "(", "self", ...
Wait until the TCP connection is closed or ``self.close_timeout`` elapses. Return ``True`` if the connection is closed and ``False`` otherwise.
[ "Wait", "until", "the", "TCP", "connection", "is", "closed", "or", "self", ".", "close_timeout", "elapses", "." ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/protocol.py#L1076-L1095
233,150
aaugustin/websockets
src/websockets/protocol.py
WebSocketCommonProtocol.fail_connection
def fail_connection(self, code: int = 1006, reason: str = "") -> None: """ 7.1.7. Fail the WebSocket Connection This requires: 1. Stopping all processing of incoming data, which means cancelling :attr:`transfer_data_task`. The close code will be 1006 unless a close frame was received earlier. 2. Sending a close frame with an appropriate code if the opening handshake succeeded and the other side is likely to process it. 3. Closing the connection. :meth:`close_connection` takes care of this once :attr:`transfer_data_task` exits after being canceled. (The specification describes these steps in the opposite order.) """ logger.debug( "%s ! failing %s WebSocket connection with code %d", self.side, self.state.name, code, ) # Cancel transfer_data_task if the opening handshake succeeded. # cancel() is idempotent and ignored if the task is done already. if hasattr(self, "transfer_data_task"): self.transfer_data_task.cancel() # Send a close frame when the state is OPEN (a close frame was already # sent if it's CLOSING), except when failing the connection because of # an error reading from or writing to the network. # Don't send a close frame if the connection is broken. if code != 1006 and self.state is State.OPEN: frame_data = serialize_close(code, reason) # Write the close frame without draining the write buffer. # Keeping fail_connection() synchronous guarantees it can't # get stuck and simplifies the implementation of the callers. # Not drainig the write buffer is acceptable in this context. # This duplicates a few lines of code from write_close_frame() # and write_frame(). self.state = State.CLOSING logger.debug("%s - state = CLOSING", self.side) frame = Frame(True, OP_CLOSE, frame_data) logger.debug("%s > %r", self.side, frame) frame.write( self.writer.write, mask=self.is_client, extensions=self.extensions ) # Start close_connection_task if the opening handshake didn't succeed. if not hasattr(self, "close_connection_task"): self.close_connection_task = self.loop.create_task(self.close_connection())
python
def fail_connection(self, code: int = 1006, reason: str = "") -> None: logger.debug( "%s ! failing %s WebSocket connection with code %d", self.side, self.state.name, code, ) # Cancel transfer_data_task if the opening handshake succeeded. # cancel() is idempotent and ignored if the task is done already. if hasattr(self, "transfer_data_task"): self.transfer_data_task.cancel() # Send a close frame when the state is OPEN (a close frame was already # sent if it's CLOSING), except when failing the connection because of # an error reading from or writing to the network. # Don't send a close frame if the connection is broken. if code != 1006 and self.state is State.OPEN: frame_data = serialize_close(code, reason) # Write the close frame without draining the write buffer. # Keeping fail_connection() synchronous guarantees it can't # get stuck and simplifies the implementation of the callers. # Not drainig the write buffer is acceptable in this context. # This duplicates a few lines of code from write_close_frame() # and write_frame(). self.state = State.CLOSING logger.debug("%s - state = CLOSING", self.side) frame = Frame(True, OP_CLOSE, frame_data) logger.debug("%s > %r", self.side, frame) frame.write( self.writer.write, mask=self.is_client, extensions=self.extensions ) # Start close_connection_task if the opening handshake didn't succeed. if not hasattr(self, "close_connection_task"): self.close_connection_task = self.loop.create_task(self.close_connection())
[ "def", "fail_connection", "(", "self", ",", "code", ":", "int", "=", "1006", ",", "reason", ":", "str", "=", "\"\"", ")", "->", "None", ":", "logger", ".", "debug", "(", "\"%s ! failing %s WebSocket connection with code %d\"", ",", "self", ".", "side", ",", ...
7.1.7. Fail the WebSocket Connection This requires: 1. Stopping all processing of incoming data, which means cancelling :attr:`transfer_data_task`. The close code will be 1006 unless a close frame was received earlier. 2. Sending a close frame with an appropriate code if the opening handshake succeeded and the other side is likely to process it. 3. Closing the connection. :meth:`close_connection` takes care of this once :attr:`transfer_data_task` exits after being canceled. (The specification describes these steps in the opposite order.)
[ "7", ".", "1", ".", "7", ".", "Fail", "the", "WebSocket", "Connection" ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/protocol.py#L1097-L1156
233,151
aaugustin/websockets
src/websockets/protocol.py
WebSocketCommonProtocol.abort_keepalive_pings
def abort_keepalive_pings(self) -> None: """ Raise ConnectionClosed in pending keepalive pings. They'll never receive a pong once the connection is closed. """ assert self.state is State.CLOSED exc = ConnectionClosed(self.close_code, self.close_reason) exc.__cause__ = self.transfer_data_exc # emulate raise ... from ... for ping in self.pings.values(): ping.set_exception(exc) if self.pings: pings_hex = ", ".join( binascii.hexlify(ping_id).decode() or "[empty]" for ping_id in self.pings ) plural = "s" if len(self.pings) > 1 else "" logger.debug( "%s - aborted pending ping%s: %s", self.side, plural, pings_hex )
python
def abort_keepalive_pings(self) -> None: assert self.state is State.CLOSED exc = ConnectionClosed(self.close_code, self.close_reason) exc.__cause__ = self.transfer_data_exc # emulate raise ... from ... for ping in self.pings.values(): ping.set_exception(exc) if self.pings: pings_hex = ", ".join( binascii.hexlify(ping_id).decode() or "[empty]" for ping_id in self.pings ) plural = "s" if len(self.pings) > 1 else "" logger.debug( "%s - aborted pending ping%s: %s", self.side, plural, pings_hex )
[ "def", "abort_keepalive_pings", "(", "self", ")", "->", "None", ":", "assert", "self", ".", "state", "is", "State", ".", "CLOSED", "exc", "=", "ConnectionClosed", "(", "self", ".", "close_code", ",", "self", ".", "close_reason", ")", "exc", ".", "__cause__...
Raise ConnectionClosed in pending keepalive pings. They'll never receive a pong once the connection is closed.
[ "Raise", "ConnectionClosed", "in", "pending", "keepalive", "pings", "." ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/protocol.py#L1158-L1180
233,152
aaugustin/websockets
src/websockets/protocol.py
WebSocketCommonProtocol.connection_made
def connection_made(self, transport: asyncio.BaseTransport) -> None: """ Configure write buffer limits. The high-water limit is defined by ``self.write_limit``. The low-water limit currently defaults to ``self.write_limit // 4`` in :meth:`~asyncio.WriteTransport.set_write_buffer_limits`, which should be all right for reasonable use cases of this library. This is the earliest point where we can get hold of the transport, which means it's the best point for configuring it. """ logger.debug("%s - event = connection_made(%s)", self.side, transport) # mypy thinks transport is a BaseTransport, not a Transport. transport.set_write_buffer_limits(self.write_limit) # type: ignore super().connection_made(transport)
python
def connection_made(self, transport: asyncio.BaseTransport) -> None: logger.debug("%s - event = connection_made(%s)", self.side, transport) # mypy thinks transport is a BaseTransport, not a Transport. transport.set_write_buffer_limits(self.write_limit) # type: ignore super().connection_made(transport)
[ "def", "connection_made", "(", "self", ",", "transport", ":", "asyncio", ".", "BaseTransport", ")", "->", "None", ":", "logger", ".", "debug", "(", "\"%s - event = connection_made(%s)\"", ",", "self", ".", "side", ",", "transport", ")", "# mypy thinks transport is...
Configure write buffer limits. The high-water limit is defined by ``self.write_limit``. The low-water limit currently defaults to ``self.write_limit // 4`` in :meth:`~asyncio.WriteTransport.set_write_buffer_limits`, which should be all right for reasonable use cases of this library. This is the earliest point where we can get hold of the transport, which means it's the best point for configuring it.
[ "Configure", "write", "buffer", "limits", "." ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/protocol.py#L1184-L1201
233,153
aaugustin/websockets
src/websockets/protocol.py
WebSocketCommonProtocol.eof_received
def eof_received(self) -> bool: """ Close the transport after receiving EOF. Since Python 3.5, `:meth:~StreamReaderProtocol.eof_received` returns ``True`` on non-TLS connections. See http://bugs.python.org/issue24539 for more information. This is inappropriate for websockets for at least three reasons: 1. The use case is to read data until EOF with self.reader.read(-1). Since websockets is a TLV protocol, this never happens. 2. It doesn't work on TLS connections. A falsy value must be returned to have the same behavior on TLS and plain connections. 3. The websockets protocol has its own closing handshake. Endpoints close the TCP connection after sending a close frame. As a consequence we revert to the previous, more useful behavior. """ logger.debug("%s - event = eof_received()", self.side) super().eof_received() return False
python
def eof_received(self) -> bool: logger.debug("%s - event = eof_received()", self.side) super().eof_received() return False
[ "def", "eof_received", "(", "self", ")", "->", "bool", ":", "logger", ".", "debug", "(", "\"%s - event = eof_received()\"", ",", "self", ".", "side", ")", "super", "(", ")", ".", "eof_received", "(", ")", "return", "False" ]
Close the transport after receiving EOF. Since Python 3.5, `:meth:~StreamReaderProtocol.eof_received` returns ``True`` on non-TLS connections. See http://bugs.python.org/issue24539 for more information. This is inappropriate for websockets for at least three reasons: 1. The use case is to read data until EOF with self.reader.read(-1). Since websockets is a TLV protocol, this never happens. 2. It doesn't work on TLS connections. A falsy value must be returned to have the same behavior on TLS and plain connections. 3. The websockets protocol has its own closing handshake. Endpoints close the TCP connection after sending a close frame. As a consequence we revert to the previous, more useful behavior.
[ "Close", "the", "transport", "after", "receiving", "EOF", "." ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/protocol.py#L1203-L1228
233,154
aaugustin/websockets
src/websockets/protocol.py
WebSocketCommonProtocol.connection_lost
def connection_lost(self, exc: Optional[Exception]) -> None: """ 7.1.4. The WebSocket Connection is Closed. """ logger.debug("%s - event = connection_lost(%s)", self.side, exc) self.state = State.CLOSED logger.debug("%s - state = CLOSED", self.side) if not hasattr(self, "close_code"): self.close_code = 1006 if not hasattr(self, "close_reason"): self.close_reason = "" logger.debug( "%s x code = %d, reason = %s", self.side, self.close_code, self.close_reason or "[no reason]", ) self.abort_keepalive_pings() # If self.connection_lost_waiter isn't pending, that's a bug, because: # - it's set only here in connection_lost() which is called only once; # - it must never be canceled. self.connection_lost_waiter.set_result(None) super().connection_lost(exc)
python
def connection_lost(self, exc: Optional[Exception]) -> None: logger.debug("%s - event = connection_lost(%s)", self.side, exc) self.state = State.CLOSED logger.debug("%s - state = CLOSED", self.side) if not hasattr(self, "close_code"): self.close_code = 1006 if not hasattr(self, "close_reason"): self.close_reason = "" logger.debug( "%s x code = %d, reason = %s", self.side, self.close_code, self.close_reason or "[no reason]", ) self.abort_keepalive_pings() # If self.connection_lost_waiter isn't pending, that's a bug, because: # - it's set only here in connection_lost() which is called only once; # - it must never be canceled. self.connection_lost_waiter.set_result(None) super().connection_lost(exc)
[ "def", "connection_lost", "(", "self", ",", "exc", ":", "Optional", "[", "Exception", "]", ")", "->", "None", ":", "logger", ".", "debug", "(", "\"%s - event = connection_lost(%s)\"", ",", "self", ".", "side", ",", "exc", ")", "self", ".", "state", "=", ...
7.1.4. The WebSocket Connection is Closed.
[ "7", ".", "1", ".", "4", ".", "The", "WebSocket", "Connection", "is", "Closed", "." ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/protocol.py#L1230-L1253
233,155
aaugustin/websockets
src/websockets/handshake.py
build_request
def build_request(headers: Headers) -> str: """ Build a handshake request to send to the server. Return the ``key`` which must be passed to :func:`check_response`. """ raw_key = bytes(random.getrandbits(8) for _ in range(16)) key = base64.b64encode(raw_key).decode() headers["Upgrade"] = "websocket" headers["Connection"] = "Upgrade" headers["Sec-WebSocket-Key"] = key headers["Sec-WebSocket-Version"] = "13" return key
python
def build_request(headers: Headers) -> str: raw_key = bytes(random.getrandbits(8) for _ in range(16)) key = base64.b64encode(raw_key).decode() headers["Upgrade"] = "websocket" headers["Connection"] = "Upgrade" headers["Sec-WebSocket-Key"] = key headers["Sec-WebSocket-Version"] = "13" return key
[ "def", "build_request", "(", "headers", ":", "Headers", ")", "->", "str", ":", "raw_key", "=", "bytes", "(", "random", ".", "getrandbits", "(", "8", ")", "for", "_", "in", "range", "(", "16", ")", ")", "key", "=", "base64", ".", "b64encode", "(", "...
Build a handshake request to send to the server. Return the ``key`` which must be passed to :func:`check_response`.
[ "Build", "a", "handshake", "request", "to", "send", "to", "the", "server", "." ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/handshake.py#L49-L62
233,156
aaugustin/websockets
src/websockets/handshake.py
check_request
def check_request(headers: Headers) -> str: """ Check a handshake request received from the client. If the handshake is valid, this function returns the ``key`` which must be passed to :func:`build_response`. Otherwise it raises an :exc:`~websockets.exceptions.InvalidHandshake` exception and the server must return an error like 400 Bad Request. This function doesn't verify that the request is an HTTP/1.1 or higher GET request and doesn't perform Host and Origin checks. These controls are usually performed earlier in the HTTP request handling code. They're the responsibility of the caller. """ connection = sum( [parse_connection(value) for value in headers.get_all("Connection")], [] ) if not any(value.lower() == "upgrade" for value in connection): raise InvalidUpgrade("Connection", ", ".join(connection)) upgrade = sum([parse_upgrade(value) for value in headers.get_all("Upgrade")], []) # For compatibility with non-strict implementations, ignore case when # checking the Upgrade header. It's supposed to be 'WebSocket'. if not (len(upgrade) == 1 and upgrade[0].lower() == "websocket"): raise InvalidUpgrade("Upgrade", ", ".join(upgrade)) try: s_w_key = headers["Sec-WebSocket-Key"] except KeyError: raise InvalidHeader("Sec-WebSocket-Key") except MultipleValuesError: raise InvalidHeader( "Sec-WebSocket-Key", "more than one Sec-WebSocket-Key header found" ) try: raw_key = base64.b64decode(s_w_key.encode(), validate=True) except binascii.Error: raise InvalidHeaderValue("Sec-WebSocket-Key", s_w_key) if len(raw_key) != 16: raise InvalidHeaderValue("Sec-WebSocket-Key", s_w_key) try: s_w_version = headers["Sec-WebSocket-Version"] except KeyError: raise InvalidHeader("Sec-WebSocket-Version") except MultipleValuesError: raise InvalidHeader( "Sec-WebSocket-Version", "more than one Sec-WebSocket-Version header found" ) if s_w_version != "13": raise InvalidHeaderValue("Sec-WebSocket-Version", s_w_version) return s_w_key
python
def check_request(headers: Headers) -> str: connection = sum( [parse_connection(value) for value in headers.get_all("Connection")], [] ) if not any(value.lower() == "upgrade" for value in connection): raise InvalidUpgrade("Connection", ", ".join(connection)) upgrade = sum([parse_upgrade(value) for value in headers.get_all("Upgrade")], []) # For compatibility with non-strict implementations, ignore case when # checking the Upgrade header. It's supposed to be 'WebSocket'. if not (len(upgrade) == 1 and upgrade[0].lower() == "websocket"): raise InvalidUpgrade("Upgrade", ", ".join(upgrade)) try: s_w_key = headers["Sec-WebSocket-Key"] except KeyError: raise InvalidHeader("Sec-WebSocket-Key") except MultipleValuesError: raise InvalidHeader( "Sec-WebSocket-Key", "more than one Sec-WebSocket-Key header found" ) try: raw_key = base64.b64decode(s_w_key.encode(), validate=True) except binascii.Error: raise InvalidHeaderValue("Sec-WebSocket-Key", s_w_key) if len(raw_key) != 16: raise InvalidHeaderValue("Sec-WebSocket-Key", s_w_key) try: s_w_version = headers["Sec-WebSocket-Version"] except KeyError: raise InvalidHeader("Sec-WebSocket-Version") except MultipleValuesError: raise InvalidHeader( "Sec-WebSocket-Version", "more than one Sec-WebSocket-Version header found" ) if s_w_version != "13": raise InvalidHeaderValue("Sec-WebSocket-Version", s_w_version) return s_w_key
[ "def", "check_request", "(", "headers", ":", "Headers", ")", "->", "str", ":", "connection", "=", "sum", "(", "[", "parse_connection", "(", "value", ")", "for", "value", "in", "headers", ".", "get_all", "(", "\"Connection\"", ")", "]", ",", "[", "]", "...
Check a handshake request received from the client. If the handshake is valid, this function returns the ``key`` which must be passed to :func:`build_response`. Otherwise it raises an :exc:`~websockets.exceptions.InvalidHandshake` exception and the server must return an error like 400 Bad Request. This function doesn't verify that the request is an HTTP/1.1 or higher GET request and doesn't perform Host and Origin checks. These controls are usually performed earlier in the HTTP request handling code. They're the responsibility of the caller.
[ "Check", "a", "handshake", "request", "received", "from", "the", "client", "." ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/handshake.py#L65-L123
233,157
aaugustin/websockets
src/websockets/handshake.py
build_response
def build_response(headers: Headers, key: str) -> None: """ Build a handshake response to send to the client. ``key`` comes from :func:`check_request`. """ headers["Upgrade"] = "websocket" headers["Connection"] = "Upgrade" headers["Sec-WebSocket-Accept"] = accept(key)
python
def build_response(headers: Headers, key: str) -> None: headers["Upgrade"] = "websocket" headers["Connection"] = "Upgrade" headers["Sec-WebSocket-Accept"] = accept(key)
[ "def", "build_response", "(", "headers", ":", "Headers", ",", "key", ":", "str", ")", "->", "None", ":", "headers", "[", "\"Upgrade\"", "]", "=", "\"websocket\"", "headers", "[", "\"Connection\"", "]", "=", "\"Upgrade\"", "headers", "[", "\"Sec-WebSocket-Accep...
Build a handshake response to send to the client. ``key`` comes from :func:`check_request`.
[ "Build", "a", "handshake", "response", "to", "send", "to", "the", "client", "." ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/handshake.py#L126-L135
233,158
aaugustin/websockets
src/websockets/handshake.py
check_response
def check_response(headers: Headers, key: str) -> None: """ Check a handshake response received from the server. ``key`` comes from :func:`build_request`. If the handshake is valid, this function returns ``None``. Otherwise it raises an :exc:`~websockets.exceptions.InvalidHandshake` exception. This function doesn't verify that the response is an HTTP/1.1 or higher response with a 101 status code. These controls are the responsibility of the caller. """ connection = sum( [parse_connection(value) for value in headers.get_all("Connection")], [] ) if not any(value.lower() == "upgrade" for value in connection): raise InvalidUpgrade("Connection", " ".join(connection)) upgrade = sum([parse_upgrade(value) for value in headers.get_all("Upgrade")], []) # For compatibility with non-strict implementations, ignore case when # checking the Upgrade header. It's supposed to be 'WebSocket'. if not (len(upgrade) == 1 and upgrade[0].lower() == "websocket"): raise InvalidUpgrade("Upgrade", ", ".join(upgrade)) try: s_w_accept = headers["Sec-WebSocket-Accept"] except KeyError: raise InvalidHeader("Sec-WebSocket-Accept") except MultipleValuesError: raise InvalidHeader( "Sec-WebSocket-Accept", "more than one Sec-WebSocket-Accept header found" ) if s_w_accept != accept(key): raise InvalidHeaderValue("Sec-WebSocket-Accept", s_w_accept)
python
def check_response(headers: Headers, key: str) -> None: connection = sum( [parse_connection(value) for value in headers.get_all("Connection")], [] ) if not any(value.lower() == "upgrade" for value in connection): raise InvalidUpgrade("Connection", " ".join(connection)) upgrade = sum([parse_upgrade(value) for value in headers.get_all("Upgrade")], []) # For compatibility with non-strict implementations, ignore case when # checking the Upgrade header. It's supposed to be 'WebSocket'. if not (len(upgrade) == 1 and upgrade[0].lower() == "websocket"): raise InvalidUpgrade("Upgrade", ", ".join(upgrade)) try: s_w_accept = headers["Sec-WebSocket-Accept"] except KeyError: raise InvalidHeader("Sec-WebSocket-Accept") except MultipleValuesError: raise InvalidHeader( "Sec-WebSocket-Accept", "more than one Sec-WebSocket-Accept header found" ) if s_w_accept != accept(key): raise InvalidHeaderValue("Sec-WebSocket-Accept", s_w_accept)
[ "def", "check_response", "(", "headers", ":", "Headers", ",", "key", ":", "str", ")", "->", "None", ":", "connection", "=", "sum", "(", "[", "parse_connection", "(", "value", ")", "for", "value", "in", "headers", ".", "get_all", "(", "\"Connection\"", ")...
Check a handshake response received from the server. ``key`` comes from :func:`build_request`. If the handshake is valid, this function returns ``None``. Otherwise it raises an :exc:`~websockets.exceptions.InvalidHandshake` exception. This function doesn't verify that the response is an HTTP/1.1 or higher response with a 101 status code. These controls are the responsibility of the caller.
[ "Check", "a", "handshake", "response", "received", "from", "the", "server", "." ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/handshake.py#L138-L178
233,159
aaugustin/websockets
src/websockets/extensions/permessage_deflate.py
PerMessageDeflate.decode
def decode(self, frame: Frame, *, max_size: Optional[int] = None) -> Frame: """ Decode an incoming frame. """ # Skip control frames. if frame.opcode in CTRL_OPCODES: return frame # Handle continuation data frames: # - skip if the initial data frame wasn't encoded # - reset "decode continuation data" flag if it's a final frame if frame.opcode == OP_CONT: if not self.decode_cont_data: return frame if frame.fin: self.decode_cont_data = False # Handle text and binary data frames: # - skip if the frame isn't encoded # - set "decode continuation data" flag if it's a non-final frame else: if not frame.rsv1: return frame if not frame.fin: # frame.rsv1 is True at this point self.decode_cont_data = True # Re-initialize per-message decoder. if self.remote_no_context_takeover: self.decoder = zlib.decompressobj(wbits=-self.remote_max_window_bits) # Uncompress compressed frames. Protect against zip bombs by # preventing zlib from decompressing more than max_length bytes # (except when the limit is disabled with max_size = None). data = frame.data if frame.fin: data += _EMPTY_UNCOMPRESSED_BLOCK max_length = 0 if max_size is None else max_size data = self.decoder.decompress(data, max_length) if self.decoder.unconsumed_tail: raise PayloadTooBig( f"Uncompressed payload length exceeds size limit (? > {max_size} bytes)" ) # Allow garbage collection of the decoder if it won't be reused. if frame.fin and self.remote_no_context_takeover: del self.decoder return frame._replace(data=data, rsv1=False)
python
def decode(self, frame: Frame, *, max_size: Optional[int] = None) -> Frame: # Skip control frames. if frame.opcode in CTRL_OPCODES: return frame # Handle continuation data frames: # - skip if the initial data frame wasn't encoded # - reset "decode continuation data" flag if it's a final frame if frame.opcode == OP_CONT: if not self.decode_cont_data: return frame if frame.fin: self.decode_cont_data = False # Handle text and binary data frames: # - skip if the frame isn't encoded # - set "decode continuation data" flag if it's a non-final frame else: if not frame.rsv1: return frame if not frame.fin: # frame.rsv1 is True at this point self.decode_cont_data = True # Re-initialize per-message decoder. if self.remote_no_context_takeover: self.decoder = zlib.decompressobj(wbits=-self.remote_max_window_bits) # Uncompress compressed frames. Protect against zip bombs by # preventing zlib from decompressing more than max_length bytes # (except when the limit is disabled with max_size = None). data = frame.data if frame.fin: data += _EMPTY_UNCOMPRESSED_BLOCK max_length = 0 if max_size is None else max_size data = self.decoder.decompress(data, max_length) if self.decoder.unconsumed_tail: raise PayloadTooBig( f"Uncompressed payload length exceeds size limit (? > {max_size} bytes)" ) # Allow garbage collection of the decoder if it won't be reused. if frame.fin and self.remote_no_context_takeover: del self.decoder return frame._replace(data=data, rsv1=False)
[ "def", "decode", "(", "self", ",", "frame", ":", "Frame", ",", "*", ",", "max_size", ":", "Optional", "[", "int", "]", "=", "None", ")", "->", "Frame", ":", "# Skip control frames.", "if", "frame", ".", "opcode", "in", "CTRL_OPCODES", ":", "return", "f...
Decode an incoming frame.
[ "Decode", "an", "incoming", "frame", "." ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/extensions/permessage_deflate.py#L91-L139
233,160
aaugustin/websockets
src/websockets/extensions/permessage_deflate.py
PerMessageDeflate.encode
def encode(self, frame: Frame) -> Frame: """ Encode an outgoing frame. """ # Skip control frames. if frame.opcode in CTRL_OPCODES: return frame # Since we always encode and never fragment messages, there's no logic # similar to decode() here at this time. if frame.opcode != OP_CONT: # Re-initialize per-message decoder. if self.local_no_context_takeover: self.encoder = zlib.compressobj( wbits=-self.local_max_window_bits, **self.compress_settings ) # Compress data frames. data = self.encoder.compress(frame.data) + self.encoder.flush(zlib.Z_SYNC_FLUSH) if frame.fin and data.endswith(_EMPTY_UNCOMPRESSED_BLOCK): data = data[:-4] # Allow garbage collection of the encoder if it won't be reused. if frame.fin and self.local_no_context_takeover: del self.encoder return frame._replace(data=data, rsv1=True)
python
def encode(self, frame: Frame) -> Frame: # Skip control frames. if frame.opcode in CTRL_OPCODES: return frame # Since we always encode and never fragment messages, there's no logic # similar to decode() here at this time. if frame.opcode != OP_CONT: # Re-initialize per-message decoder. if self.local_no_context_takeover: self.encoder = zlib.compressobj( wbits=-self.local_max_window_bits, **self.compress_settings ) # Compress data frames. data = self.encoder.compress(frame.data) + self.encoder.flush(zlib.Z_SYNC_FLUSH) if frame.fin and data.endswith(_EMPTY_UNCOMPRESSED_BLOCK): data = data[:-4] # Allow garbage collection of the encoder if it won't be reused. if frame.fin and self.local_no_context_takeover: del self.encoder return frame._replace(data=data, rsv1=True)
[ "def", "encode", "(", "self", ",", "frame", ":", "Frame", ")", "->", "Frame", ":", "# Skip control frames.", "if", "frame", ".", "opcode", "in", "CTRL_OPCODES", ":", "return", "frame", "# Since we always encode and never fragment messages, there's no logic", "# similar ...
Encode an outgoing frame.
[ "Encode", "an", "outgoing", "frame", "." ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/extensions/permessage_deflate.py#L141-L169
233,161
aaugustin/websockets
src/websockets/extensions/permessage_deflate.py
ClientPerMessageDeflateFactory.get_request_params
def get_request_params(self) -> List[ExtensionParameter]: """ Build request parameters. """ return _build_parameters( self.server_no_context_takeover, self.client_no_context_takeover, self.server_max_window_bits, self.client_max_window_bits, )
python
def get_request_params(self) -> List[ExtensionParameter]: return _build_parameters( self.server_no_context_takeover, self.client_no_context_takeover, self.server_max_window_bits, self.client_max_window_bits, )
[ "def", "get_request_params", "(", "self", ")", "->", "List", "[", "ExtensionParameter", "]", ":", "return", "_build_parameters", "(", "self", ".", "server_no_context_takeover", ",", "self", ".", "client_no_context_takeover", ",", "self", ".", "server_max_window_bits",...
Build request parameters.
[ "Build", "request", "parameters", "." ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/extensions/permessage_deflate.py#L313-L323
233,162
aaugustin/websockets
src/websockets/extensions/permessage_deflate.py
ClientPerMessageDeflateFactory.process_response_params
def process_response_params( self, params: Sequence[ExtensionParameter], accepted_extensions: Sequence["Extension"], ) -> PerMessageDeflate: """ Process response parameters. Return an extension instance. """ if any(other.name == self.name for other in accepted_extensions): raise NegotiationError(f"Received duplicate {self.name}") # Request parameters are available in instance variables. # Load response parameters in local variables. ( server_no_context_takeover, client_no_context_takeover, server_max_window_bits, client_max_window_bits, ) = _extract_parameters(params, is_server=False) # After comparing the request and the response, the final # configuration must be available in the local variables. # server_no_context_takeover # # Req. Resp. Result # ------ ------ -------------------------------------------------- # False False False # False True True # True False Error! # True True True if self.server_no_context_takeover: if not server_no_context_takeover: raise NegotiationError("Expected server_no_context_takeover") # client_no_context_takeover # # Req. Resp. Result # ------ ------ -------------------------------------------------- # False False False # False True True # True False True - must change value # True True True if self.client_no_context_takeover: if not client_no_context_takeover: client_no_context_takeover = True # server_max_window_bits # Req. Resp. Result # ------ ------ -------------------------------------------------- # None None None # None 8≤M≤15 M # 8≤N≤15 None Error! # 8≤N≤15 8≤M≤N M # 8≤N≤15 N<M≤15 Error! if self.server_max_window_bits is None: pass else: if server_max_window_bits is None: raise NegotiationError("Expected server_max_window_bits") elif server_max_window_bits > self.server_max_window_bits: raise NegotiationError("Unsupported server_max_window_bits") # client_max_window_bits # Req. Resp. Result # ------ ------ -------------------------------------------------- # None None None # None 8≤M≤15 Error! # True None None # True 8≤M≤15 M # 8≤N≤15 None N - must change value # 8≤N≤15 8≤M≤N M # 8≤N≤15 N<M≤15 Error! if self.client_max_window_bits is None: if client_max_window_bits is not None: raise NegotiationError("Unexpected client_max_window_bits") elif self.client_max_window_bits is True: pass else: if client_max_window_bits is None: client_max_window_bits = self.client_max_window_bits elif client_max_window_bits > self.client_max_window_bits: raise NegotiationError("Unsupported client_max_window_bits") return PerMessageDeflate( server_no_context_takeover, # remote_no_context_takeover client_no_context_takeover, # local_no_context_takeover server_max_window_bits or 15, # remote_max_window_bits client_max_window_bits or 15, # local_max_window_bits self.compress_settings, )
python
def process_response_params( self, params: Sequence[ExtensionParameter], accepted_extensions: Sequence["Extension"], ) -> PerMessageDeflate: if any(other.name == self.name for other in accepted_extensions): raise NegotiationError(f"Received duplicate {self.name}") # Request parameters are available in instance variables. # Load response parameters in local variables. ( server_no_context_takeover, client_no_context_takeover, server_max_window_bits, client_max_window_bits, ) = _extract_parameters(params, is_server=False) # After comparing the request and the response, the final # configuration must be available in the local variables. # server_no_context_takeover # # Req. Resp. Result # ------ ------ -------------------------------------------------- # False False False # False True True # True False Error! # True True True if self.server_no_context_takeover: if not server_no_context_takeover: raise NegotiationError("Expected server_no_context_takeover") # client_no_context_takeover # # Req. Resp. Result # ------ ------ -------------------------------------------------- # False False False # False True True # True False True - must change value # True True True if self.client_no_context_takeover: if not client_no_context_takeover: client_no_context_takeover = True # server_max_window_bits # Req. Resp. Result # ------ ------ -------------------------------------------------- # None None None # None 8≤M≤15 M # 8≤N≤15 None Error! # 8≤N≤15 8≤M≤N M # 8≤N≤15 N<M≤15 Error! if self.server_max_window_bits is None: pass else: if server_max_window_bits is None: raise NegotiationError("Expected server_max_window_bits") elif server_max_window_bits > self.server_max_window_bits: raise NegotiationError("Unsupported server_max_window_bits") # client_max_window_bits # Req. Resp. Result # ------ ------ -------------------------------------------------- # None None None # None 8≤M≤15 Error! # True None None # True 8≤M≤15 M # 8≤N≤15 None N - must change value # 8≤N≤15 8≤M≤N M # 8≤N≤15 N<M≤15 Error! if self.client_max_window_bits is None: if client_max_window_bits is not None: raise NegotiationError("Unexpected client_max_window_bits") elif self.client_max_window_bits is True: pass else: if client_max_window_bits is None: client_max_window_bits = self.client_max_window_bits elif client_max_window_bits > self.client_max_window_bits: raise NegotiationError("Unsupported client_max_window_bits") return PerMessageDeflate( server_no_context_takeover, # remote_no_context_takeover client_no_context_takeover, # local_no_context_takeover server_max_window_bits or 15, # remote_max_window_bits client_max_window_bits or 15, # local_max_window_bits self.compress_settings, )
[ "def", "process_response_params", "(", "self", ",", "params", ":", "Sequence", "[", "ExtensionParameter", "]", ",", "accepted_extensions", ":", "Sequence", "[", "\"Extension\"", "]", ",", ")", "->", "PerMessageDeflate", ":", "if", "any", "(", "other", ".", "na...
Process response parameters. Return an extension instance.
[ "Process", "response", "parameters", "." ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/extensions/permessage_deflate.py#L325-L428
233,163
aaugustin/websockets
src/websockets/extensions/permessage_deflate.py
ServerPerMessageDeflateFactory.process_request_params
def process_request_params( self, params: Sequence[ExtensionParameter], accepted_extensions: Sequence["Extension"], ) -> Tuple[List[ExtensionParameter], PerMessageDeflate]: """ Process request parameters. Return response params and an extension instance. """ if any(other.name == self.name for other in accepted_extensions): raise NegotiationError(f"Skipped duplicate {self.name}") # Load request parameters in local variables. ( server_no_context_takeover, client_no_context_takeover, server_max_window_bits, client_max_window_bits, ) = _extract_parameters(params, is_server=True) # Configuration parameters are available in instance variables. # After comparing the request and the configuration, the response must # be available in the local variables. # server_no_context_takeover # # Config Req. Resp. # ------ ------ -------------------------------------------------- # False False False # False True True # True False True - must change value to True # True True True if self.server_no_context_takeover: if not server_no_context_takeover: server_no_context_takeover = True # client_no_context_takeover # # Config Req. Resp. # ------ ------ -------------------------------------------------- # False False False # False True True (or False) # True False True - must change value to True # True True True (or False) if self.client_no_context_takeover: if not client_no_context_takeover: client_no_context_takeover = True # server_max_window_bits # Config Req. Resp. # ------ ------ -------------------------------------------------- # None None None # None 8≤M≤15 M # 8≤N≤15 None N - must change value # 8≤N≤15 8≤M≤N M # 8≤N≤15 N<M≤15 N - must change value if self.server_max_window_bits is None: pass else: if server_max_window_bits is None: server_max_window_bits = self.server_max_window_bits elif server_max_window_bits > self.server_max_window_bits: server_max_window_bits = self.server_max_window_bits # client_max_window_bits # Config Req. Resp. # ------ ------ -------------------------------------------------- # None None None # None True None - must change value # None 8≤M≤15 M (or None) # 8≤N≤15 None Error! # 8≤N≤15 True N - must change value # 8≤N≤15 8≤M≤N M (or None) # 8≤N≤15 N<M≤15 N if self.client_max_window_bits is None: if client_max_window_bits is True: client_max_window_bits = self.client_max_window_bits else: if client_max_window_bits is None: raise NegotiationError("Required client_max_window_bits") elif client_max_window_bits is True: client_max_window_bits = self.client_max_window_bits elif self.client_max_window_bits < client_max_window_bits: client_max_window_bits = self.client_max_window_bits return ( _build_parameters( server_no_context_takeover, client_no_context_takeover, server_max_window_bits, client_max_window_bits, ), PerMessageDeflate( client_no_context_takeover, # remote_no_context_takeover server_no_context_takeover, # local_no_context_takeover client_max_window_bits or 15, # remote_max_window_bits server_max_window_bits or 15, # local_max_window_bits self.compress_settings, ), )
python
def process_request_params( self, params: Sequence[ExtensionParameter], accepted_extensions: Sequence["Extension"], ) -> Tuple[List[ExtensionParameter], PerMessageDeflate]: if any(other.name == self.name for other in accepted_extensions): raise NegotiationError(f"Skipped duplicate {self.name}") # Load request parameters in local variables. ( server_no_context_takeover, client_no_context_takeover, server_max_window_bits, client_max_window_bits, ) = _extract_parameters(params, is_server=True) # Configuration parameters are available in instance variables. # After comparing the request and the configuration, the response must # be available in the local variables. # server_no_context_takeover # # Config Req. Resp. # ------ ------ -------------------------------------------------- # False False False # False True True # True False True - must change value to True # True True True if self.server_no_context_takeover: if not server_no_context_takeover: server_no_context_takeover = True # client_no_context_takeover # # Config Req. Resp. # ------ ------ -------------------------------------------------- # False False False # False True True (or False) # True False True - must change value to True # True True True (or False) if self.client_no_context_takeover: if not client_no_context_takeover: client_no_context_takeover = True # server_max_window_bits # Config Req. Resp. # ------ ------ -------------------------------------------------- # None None None # None 8≤M≤15 M # 8≤N≤15 None N - must change value # 8≤N≤15 8≤M≤N M # 8≤N≤15 N<M≤15 N - must change value if self.server_max_window_bits is None: pass else: if server_max_window_bits is None: server_max_window_bits = self.server_max_window_bits elif server_max_window_bits > self.server_max_window_bits: server_max_window_bits = self.server_max_window_bits # client_max_window_bits # Config Req. Resp. # ------ ------ -------------------------------------------------- # None None None # None True None - must change value # None 8≤M≤15 M (or None) # 8≤N≤15 None Error! # 8≤N≤15 True N - must change value # 8≤N≤15 8≤M≤N M (or None) # 8≤N≤15 N<M≤15 N if self.client_max_window_bits is None: if client_max_window_bits is True: client_max_window_bits = self.client_max_window_bits else: if client_max_window_bits is None: raise NegotiationError("Required client_max_window_bits") elif client_max_window_bits is True: client_max_window_bits = self.client_max_window_bits elif self.client_max_window_bits < client_max_window_bits: client_max_window_bits = self.client_max_window_bits return ( _build_parameters( server_no_context_takeover, client_no_context_takeover, server_max_window_bits, client_max_window_bits, ), PerMessageDeflate( client_no_context_takeover, # remote_no_context_takeover server_no_context_takeover, # local_no_context_takeover client_max_window_bits or 15, # remote_max_window_bits server_max_window_bits or 15, # local_max_window_bits self.compress_settings, ), )
[ "def", "process_request_params", "(", "self", ",", "params", ":", "Sequence", "[", "ExtensionParameter", "]", ",", "accepted_extensions", ":", "Sequence", "[", "\"Extension\"", "]", ",", ")", "->", "Tuple", "[", "List", "[", "ExtensionParameter", "]", ",", "Pe...
Process request parameters. Return response params and an extension instance.
[ "Process", "request", "parameters", "." ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/extensions/permessage_deflate.py#L482-L592
233,164
aaugustin/websockets
src/websockets/utils.py
apply_mask
def apply_mask(data: bytes, mask: bytes) -> bytes: """ Apply masking to the data of a WebSocket message. ``data`` and ``mask`` are bytes-like objects. Return :class:`bytes`. """ if len(mask) != 4: raise ValueError("mask must contain 4 bytes") return bytes(b ^ m for b, m in zip(data, itertools.cycle(mask)))
python
def apply_mask(data: bytes, mask: bytes) -> bytes: if len(mask) != 4: raise ValueError("mask must contain 4 bytes") return bytes(b ^ m for b, m in zip(data, itertools.cycle(mask)))
[ "def", "apply_mask", "(", "data", ":", "bytes", ",", "mask", ":", "bytes", ")", "->", "bytes", ":", "if", "len", "(", "mask", ")", "!=", "4", ":", "raise", "ValueError", "(", "\"mask must contain 4 bytes\"", ")", "return", "bytes", "(", "b", "^", "m", ...
Apply masking to the data of a WebSocket message. ``data`` and ``mask`` are bytes-like objects. Return :class:`bytes`.
[ "Apply", "masking", "to", "the", "data", "of", "a", "WebSocket", "message", "." ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/utils.py#L7-L19
233,165
aaugustin/websockets
src/websockets/exceptions.py
format_close
def format_close(code: int, reason: str) -> str: """ Display a human-readable version of the close code and reason. """ if 3000 <= code < 4000: explanation = "registered" elif 4000 <= code < 5000: explanation = "private use" else: explanation = CLOSE_CODES.get(code, "unknown") result = f"code = {code} ({explanation}), " if reason: result += f"reason = {reason}" else: result += "no reason" return result
python
def format_close(code: int, reason: str) -> str: if 3000 <= code < 4000: explanation = "registered" elif 4000 <= code < 5000: explanation = "private use" else: explanation = CLOSE_CODES.get(code, "unknown") result = f"code = {code} ({explanation}), " if reason: result += f"reason = {reason}" else: result += "no reason" return result
[ "def", "format_close", "(", "code", ":", "int", ",", "reason", ":", "str", ")", "->", "str", ":", "if", "3000", "<=", "code", "<", "4000", ":", "explanation", "=", "\"registered\"", "elif", "4000", "<=", "code", "<", "5000", ":", "explanation", "=", ...
Display a human-readable version of the close code and reason.
[ "Display", "a", "human", "-", "readable", "version", "of", "the", "close", "code", "and", "reason", "." ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/exceptions.py#L202-L221
233,166
nameko/nameko
nameko/runners.py
ServiceRunner.start
def start(self): """ Start all the registered services. A new container is created for each service using the container class provided in the __init__ method. All containers are started concurrently and the method will block until all have completed their startup routine. """ service_names = ', '.join(self.service_names) _log.info('starting services: %s', service_names) SpawningProxy(self.containers).start() _log.debug('services started: %s', service_names)
python
def start(self): service_names = ', '.join(self.service_names) _log.info('starting services: %s', service_names) SpawningProxy(self.containers).start() _log.debug('services started: %s', service_names)
[ "def", "start", "(", "self", ")", ":", "service_names", "=", "', '", ".", "join", "(", "self", ".", "service_names", ")", "_log", ".", "info", "(", "'starting services: %s'", ",", "service_names", ")", "SpawningProxy", "(", "self", ".", "containers", ")", ...
Start all the registered services. A new container is created for each service using the container class provided in the __init__ method. All containers are started concurrently and the method will block until all have completed their startup routine.
[ "Start", "all", "the", "registered", "services", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/runners.py#L54-L68
233,167
nameko/nameko
nameko/runners.py
ServiceRunner.wait
def wait(self): """ Wait for all running containers to stop. """ try: SpawningProxy(self.containers, abort_on_error=True).wait() except Exception: # If a single container failed, stop its peers and re-raise the # exception self.stop() raise
python
def wait(self): try: SpawningProxy(self.containers, abort_on_error=True).wait() except Exception: # If a single container failed, stop its peers and re-raise the # exception self.stop() raise
[ "def", "wait", "(", "self", ")", ":", "try", ":", "SpawningProxy", "(", "self", ".", "containers", ",", "abort_on_error", "=", "True", ")", ".", "wait", "(", ")", "except", "Exception", ":", "# If a single container failed, stop its peers and re-raise the", "# exc...
Wait for all running containers to stop.
[ "Wait", "for", "all", "running", "containers", "to", "stop", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/runners.py#L92-L101
233,168
nameko/nameko
nameko/amqp/publish.py
Publisher.publish
def publish(self, payload, **kwargs): """ Publish a message. """ publish_kwargs = self.publish_kwargs.copy() # merge headers from when the publisher was instantiated # with any provided now; "extra" headers always win headers = publish_kwargs.pop('headers', {}).copy() headers.update(kwargs.pop('headers', {})) headers.update(kwargs.pop('extra_headers', {})) use_confirms = kwargs.pop('use_confirms', self.use_confirms) transport_options = kwargs.pop('transport_options', self.transport_options ) transport_options['confirm_publish'] = use_confirms delivery_mode = kwargs.pop('delivery_mode', self.delivery_mode) mandatory = kwargs.pop('mandatory', self.mandatory) priority = kwargs.pop('priority', self.priority) expiration = kwargs.pop('expiration', self.expiration) serializer = kwargs.pop('serializer', self.serializer) compression = kwargs.pop('compression', self.compression) retry = kwargs.pop('retry', self.retry) retry_policy = kwargs.pop('retry_policy', self.retry_policy) declare = self.declare[:] declare.extend(kwargs.pop('declare', ())) publish_kwargs.update(kwargs) # remaining publish-time kwargs win with get_producer(self.amqp_uri, use_confirms, self.ssl, transport_options, ) as producer: try: producer.publish( payload, headers=headers, delivery_mode=delivery_mode, mandatory=mandatory, priority=priority, expiration=expiration, compression=compression, declare=declare, retry=retry, retry_policy=retry_policy, serializer=serializer, **publish_kwargs ) except ChannelError as exc: if "NO_ROUTE" in str(exc): raise UndeliverableMessage() raise if mandatory: if not use_confirms: warnings.warn( "Mandatory delivery was requested, but " "unroutable messages cannot be detected without " "publish confirms enabled." )
python
def publish(self, payload, **kwargs): publish_kwargs = self.publish_kwargs.copy() # merge headers from when the publisher was instantiated # with any provided now; "extra" headers always win headers = publish_kwargs.pop('headers', {}).copy() headers.update(kwargs.pop('headers', {})) headers.update(kwargs.pop('extra_headers', {})) use_confirms = kwargs.pop('use_confirms', self.use_confirms) transport_options = kwargs.pop('transport_options', self.transport_options ) transport_options['confirm_publish'] = use_confirms delivery_mode = kwargs.pop('delivery_mode', self.delivery_mode) mandatory = kwargs.pop('mandatory', self.mandatory) priority = kwargs.pop('priority', self.priority) expiration = kwargs.pop('expiration', self.expiration) serializer = kwargs.pop('serializer', self.serializer) compression = kwargs.pop('compression', self.compression) retry = kwargs.pop('retry', self.retry) retry_policy = kwargs.pop('retry_policy', self.retry_policy) declare = self.declare[:] declare.extend(kwargs.pop('declare', ())) publish_kwargs.update(kwargs) # remaining publish-time kwargs win with get_producer(self.amqp_uri, use_confirms, self.ssl, transport_options, ) as producer: try: producer.publish( payload, headers=headers, delivery_mode=delivery_mode, mandatory=mandatory, priority=priority, expiration=expiration, compression=compression, declare=declare, retry=retry, retry_policy=retry_policy, serializer=serializer, **publish_kwargs ) except ChannelError as exc: if "NO_ROUTE" in str(exc): raise UndeliverableMessage() raise if mandatory: if not use_confirms: warnings.warn( "Mandatory delivery was requested, but " "unroutable messages cannot be detected without " "publish confirms enabled." )
[ "def", "publish", "(", "self", ",", "payload", ",", "*", "*", "kwargs", ")", ":", "publish_kwargs", "=", "self", ".", "publish_kwargs", ".", "copy", "(", ")", "# merge headers from when the publisher was instantiated", "# with any provided now; \"extra\" headers always wi...
Publish a message.
[ "Publish", "a", "message", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/amqp/publish.py#L161-L223
233,169
nameko/nameko
nameko/rpc.py
RpcConsumer.stop
def stop(self): """ Stop the RpcConsumer. The RpcConsumer ordinary unregisters from the QueueConsumer when the last Rpc subclass unregisters from it. If no providers were registered, we should unregister from the QueueConsumer as soon as we're asked to stop. """ if not self._providers_registered: self.queue_consumer.unregister_provider(self) self._unregistered_from_queue_consumer.send(True)
python
def stop(self): if not self._providers_registered: self.queue_consumer.unregister_provider(self) self._unregistered_from_queue_consumer.send(True)
[ "def", "stop", "(", "self", ")", ":", "if", "not", "self", ".", "_providers_registered", ":", "self", ".", "queue_consumer", ".", "unregister_provider", "(", "self", ")", "self", ".", "_unregistered_from_queue_consumer", ".", "send", "(", "True", ")" ]
Stop the RpcConsumer. The RpcConsumer ordinary unregisters from the QueueConsumer when the last Rpc subclass unregisters from it. If no providers were registered, we should unregister from the QueueConsumer as soon as we're asked to stop.
[ "Stop", "the", "RpcConsumer", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/rpc.py#L70-L80
233,170
nameko/nameko
nameko/rpc.py
RpcConsumer.unregister_provider
def unregister_provider(self, provider): """ Unregister a provider. Blocks until this RpcConsumer is unregistered from its QueueConsumer, which only happens when all providers have asked to unregister. """ self._unregistering_providers.add(provider) remaining_providers = self._providers - self._unregistering_providers if not remaining_providers: _log.debug('unregistering from queueconsumer %s', self) self.queue_consumer.unregister_provider(self) _log.debug('unregistered from queueconsumer %s', self) self._unregistered_from_queue_consumer.send(True) _log.debug('waiting for unregister from queue consumer %s', self) self._unregistered_from_queue_consumer.wait() super(RpcConsumer, self).unregister_provider(provider)
python
def unregister_provider(self, provider): self._unregistering_providers.add(provider) remaining_providers = self._providers - self._unregistering_providers if not remaining_providers: _log.debug('unregistering from queueconsumer %s', self) self.queue_consumer.unregister_provider(self) _log.debug('unregistered from queueconsumer %s', self) self._unregistered_from_queue_consumer.send(True) _log.debug('waiting for unregister from queue consumer %s', self) self._unregistered_from_queue_consumer.wait() super(RpcConsumer, self).unregister_provider(provider)
[ "def", "unregister_provider", "(", "self", ",", "provider", ")", ":", "self", ".", "_unregistering_providers", ".", "add", "(", "provider", ")", "remaining_providers", "=", "self", ".", "_providers", "-", "self", ".", "_unregistering_providers", "if", "not", "re...
Unregister a provider. Blocks until this RpcConsumer is unregistered from its QueueConsumer, which only happens when all providers have asked to unregister.
[ "Unregister", "a", "provider", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/rpc.py#L82-L98
233,171
nameko/nameko
nameko/events.py
EventDispatcher.get_dependency
def get_dependency(self, worker_ctx): """ Inject a dispatch method onto the service instance """ extra_headers = self.get_message_headers(worker_ctx) def dispatch(event_type, event_data): self.publisher.publish( event_data, exchange=self.exchange, routing_key=event_type, extra_headers=extra_headers ) return dispatch
python
def get_dependency(self, worker_ctx): extra_headers = self.get_message_headers(worker_ctx) def dispatch(event_type, event_data): self.publisher.publish( event_data, exchange=self.exchange, routing_key=event_type, extra_headers=extra_headers ) return dispatch
[ "def", "get_dependency", "(", "self", ",", "worker_ctx", ")", ":", "extra_headers", "=", "self", ".", "get_message_headers", "(", "worker_ctx", ")", "def", "dispatch", "(", "event_type", ",", "event_data", ")", ":", "self", ".", "publisher", ".", "publish", ...
Inject a dispatch method onto the service instance
[ "Inject", "a", "dispatch", "method", "onto", "the", "service", "instance" ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/events.py#L86-L99
233,172
nameko/nameko
nameko/events.py
EventHandler.broadcast_identifier
def broadcast_identifier(self): """ A unique string to identify a service instance for `BROADCAST` type handlers. The `broadcast_identifier` is appended to the queue name when the `BROADCAST` handler type is used. It must uniquely identify service instances that receive broadcasts. The default `broadcast_identifier` is a uuid that is set when the service starts. It will change when the service restarts, meaning that any unconsumed messages that were broadcast to the 'old' service instance will not be received by the 'new' one. :: @property def broadcast_identifier(self): # use a uuid as the identifier. # the identifier will change when the service restarts and # any unconsumed messages will be lost return uuid.uuid4().hex The default behaviour is therefore incompatible with reliable delivery. An alternative `broadcast_identifier` that would survive service restarts is :: @property def broadcast_identifier(self): # use the machine hostname as the identifier. # this assumes that only one instance of a service runs on # any given machine return socket.gethostname() If neither of these approaches are appropriate, you could read the value out of a configuration file :: @property def broadcast_identifier(self): return self.config['SERVICE_IDENTIFIER'] # or similar Broadcast queues are exclusive to ensure that `broadcast_identifier` values are unique. Because this method is a descriptor, it will be called during container creation, regardless of the configured `handler_type`. See :class:`nameko.extensions.Extension` for more details. """ if self.handler_type is not BROADCAST: return None if self.reliable_delivery: raise EventHandlerConfigurationError( "You are using the default broadcast identifier " "which is not compatible with reliable delivery. See " ":meth:`nameko.events.EventHandler.broadcast_identifier` " "for details.") return uuid.uuid4().hex
python
def broadcast_identifier(self): if self.handler_type is not BROADCAST: return None if self.reliable_delivery: raise EventHandlerConfigurationError( "You are using the default broadcast identifier " "which is not compatible with reliable delivery. See " ":meth:`nameko.events.EventHandler.broadcast_identifier` " "for details.") return uuid.uuid4().hex
[ "def", "broadcast_identifier", "(", "self", ")", ":", "if", "self", ".", "handler_type", "is", "not", "BROADCAST", ":", "return", "None", "if", "self", ".", "reliable_delivery", ":", "raise", "EventHandlerConfigurationError", "(", "\"You are using the default broadcas...
A unique string to identify a service instance for `BROADCAST` type handlers. The `broadcast_identifier` is appended to the queue name when the `BROADCAST` handler type is used. It must uniquely identify service instances that receive broadcasts. The default `broadcast_identifier` is a uuid that is set when the service starts. It will change when the service restarts, meaning that any unconsumed messages that were broadcast to the 'old' service instance will not be received by the 'new' one. :: @property def broadcast_identifier(self): # use a uuid as the identifier. # the identifier will change when the service restarts and # any unconsumed messages will be lost return uuid.uuid4().hex The default behaviour is therefore incompatible with reliable delivery. An alternative `broadcast_identifier` that would survive service restarts is :: @property def broadcast_identifier(self): # use the machine hostname as the identifier. # this assumes that only one instance of a service runs on # any given machine return socket.gethostname() If neither of these approaches are appropriate, you could read the value out of a configuration file :: @property def broadcast_identifier(self): return self.config['SERVICE_IDENTIFIER'] # or similar Broadcast queues are exclusive to ensure that `broadcast_identifier` values are unique. Because this method is a descriptor, it will be called during container creation, regardless of the configured `handler_type`. See :class:`nameko.extensions.Extension` for more details.
[ "A", "unique", "string", "to", "identify", "a", "service", "instance", "for", "BROADCAST", "type", "handlers", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/events.py#L166-L222
233,173
nameko/nameko
nameko/exceptions.py
get_module_path
def get_module_path(exc_type): """ Return the dotted module path of `exc_type`, including the class name. e.g.:: >>> get_module_path(MethodNotFound) >>> "nameko.exceptions.MethodNotFound" """ module = inspect.getmodule(exc_type) return "{}.{}".format(module.__name__, exc_type.__name__)
python
def get_module_path(exc_type): module = inspect.getmodule(exc_type) return "{}.{}".format(module.__name__, exc_type.__name__)
[ "def", "get_module_path", "(", "exc_type", ")", ":", "module", "=", "inspect", ".", "getmodule", "(", "exc_type", ")", "return", "\"{}.{}\"", ".", "format", "(", "module", ".", "__name__", ",", "exc_type", ".", "__name__", ")" ]
Return the dotted module path of `exc_type`, including the class name. e.g.:: >>> get_module_path(MethodNotFound) >>> "nameko.exceptions.MethodNotFound"
[ "Return", "the", "dotted", "module", "path", "of", "exc_type", "including", "the", "class", "name", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/exceptions.py#L38-L48
233,174
nameko/nameko
nameko/exceptions.py
safe_for_serialization
def safe_for_serialization(value): """ Transform a value in preparation for serializing as json no-op for strings, mappings and iterables have their entries made safe, and all other values are stringified, with a fallback value if that fails """ if isinstance(value, six.string_types): return value if isinstance(value, dict): return { safe_for_serialization(key): safe_for_serialization(val) for key, val in six.iteritems(value) } if isinstance(value, collections.Iterable): return list(map(safe_for_serialization, value)) try: return six.text_type(value) except Exception: return '[__unicode__ failed]'
python
def safe_for_serialization(value): if isinstance(value, six.string_types): return value if isinstance(value, dict): return { safe_for_serialization(key): safe_for_serialization(val) for key, val in six.iteritems(value) } if isinstance(value, collections.Iterable): return list(map(safe_for_serialization, value)) try: return six.text_type(value) except Exception: return '[__unicode__ failed]'
[ "def", "safe_for_serialization", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", ":", "return", "value", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "return", "{", "safe_for_serialization", "(", ...
Transform a value in preparation for serializing as json no-op for strings, mappings and iterables have their entries made safe, and all other values are stringified, with a fallback value if that fails
[ "Transform", "a", "value", "in", "preparation", "for", "serializing", "as", "json" ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/exceptions.py#L62-L82
233,175
nameko/nameko
nameko/exceptions.py
serialize
def serialize(exc): """ Serialize `self.exc` into a data dictionary representing it. """ return { 'exc_type': type(exc).__name__, 'exc_path': get_module_path(type(exc)), 'exc_args': list(map(safe_for_serialization, exc.args)), 'value': safe_for_serialization(exc), }
python
def serialize(exc): return { 'exc_type': type(exc).__name__, 'exc_path': get_module_path(type(exc)), 'exc_args': list(map(safe_for_serialization, exc.args)), 'value': safe_for_serialization(exc), }
[ "def", "serialize", "(", "exc", ")", ":", "return", "{", "'exc_type'", ":", "type", "(", "exc", ")", ".", "__name__", ",", "'exc_path'", ":", "get_module_path", "(", "type", "(", "exc", ")", ")", ",", "'exc_args'", ":", "list", "(", "map", "(", "safe...
Serialize `self.exc` into a data dictionary representing it.
[ "Serialize", "self", ".", "exc", "into", "a", "data", "dictionary", "representing", "it", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/exceptions.py#L85-L94
233,176
nameko/nameko
nameko/exceptions.py
deserialize
def deserialize(data): """ Deserialize `data` to an exception instance. If the `exc_path` value matches an exception registered as ``deserializable``, return an instance of that exception type. Otherwise, return a `RemoteError` instance describing the exception that occurred. """ key = data.get('exc_path') if key in registry: exc_args = data.get('exc_args', ()) return registry[key](*exc_args) exc_type = data.get('exc_type') value = data.get('value') return RemoteError(exc_type=exc_type, value=value)
python
def deserialize(data): key = data.get('exc_path') if key in registry: exc_args = data.get('exc_args', ()) return registry[key](*exc_args) exc_type = data.get('exc_type') value = data.get('value') return RemoteError(exc_type=exc_type, value=value)
[ "def", "deserialize", "(", "data", ")", ":", "key", "=", "data", ".", "get", "(", "'exc_path'", ")", "if", "key", "in", "registry", ":", "exc_args", "=", "data", ".", "get", "(", "'exc_args'", ",", "(", ")", ")", "return", "registry", "[", "key", "...
Deserialize `data` to an exception instance. If the `exc_path` value matches an exception registered as ``deserializable``, return an instance of that exception type. Otherwise, return a `RemoteError` instance describing the exception that occurred.
[ "Deserialize", "data", "to", "an", "exception", "instance", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/exceptions.py#L97-L112
233,177
nameko/nameko
nameko/utils/__init__.py
import_from_path
def import_from_path(path): """ Import and return the object at `path` if it exists. Raises an :exc:`ImportError` if the object is not found. """ if path is None: return obj = locate(path) if obj is None: raise ImportError( "`{}` could not be imported".format(path) ) return obj
python
def import_from_path(path): if path is None: return obj = locate(path) if obj is None: raise ImportError( "`{}` could not be imported".format(path) ) return obj
[ "def", "import_from_path", "(", "path", ")", ":", "if", "path", "is", "None", ":", "return", "obj", "=", "locate", "(", "path", ")", "if", "obj", "is", "None", ":", "raise", "ImportError", "(", "\"`{}` could not be imported\"", ".", "format", "(", "path", ...
Import and return the object at `path` if it exists. Raises an :exc:`ImportError` if the object is not found.
[ "Import", "and", "return", "the", "object", "at", "path", "if", "it", "exists", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/utils/__init__.py#L110-L124
233,178
nameko/nameko
nameko/utils/__init__.py
sanitize_url
def sanitize_url(url): """Redact password in urls.""" parts = urlparse(url) if parts.password is None: return url host_info = parts.netloc.rsplit('@', 1)[-1] parts = parts._replace(netloc='{}:{}@{}'.format( parts.username, REDACTED, host_info)) return parts.geturl()
python
def sanitize_url(url): parts = urlparse(url) if parts.password is None: return url host_info = parts.netloc.rsplit('@', 1)[-1] parts = parts._replace(netloc='{}:{}@{}'.format( parts.username, REDACTED, host_info)) return parts.geturl()
[ "def", "sanitize_url", "(", "url", ")", ":", "parts", "=", "urlparse", "(", "url", ")", "if", "parts", ".", "password", "is", "None", ":", "return", "url", "host_info", "=", "parts", ".", "netloc", ".", "rsplit", "(", "'@'", ",", "1", ")", "[", "-"...
Redact password in urls.
[ "Redact", "password", "in", "urls", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/utils/__init__.py#L127-L135
233,179
nameko/nameko
nameko/web/websocket.py
WebSocketHub.get_subscriptions
def get_subscriptions(self, socket_id): """Returns a list of all the subscriptions of a socket.""" con = self._get_connection(socket_id, create=False) if con is None: return [] return sorted(con.subscriptions)
python
def get_subscriptions(self, socket_id): con = self._get_connection(socket_id, create=False) if con is None: return [] return sorted(con.subscriptions)
[ "def", "get_subscriptions", "(", "self", ",", "socket_id", ")", ":", "con", "=", "self", ".", "_get_connection", "(", "socket_id", ",", "create", "=", "False", ")", "if", "con", "is", "None", ":", "return", "[", "]", "return", "sorted", "(", "con", "."...
Returns a list of all the subscriptions of a socket.
[ "Returns", "a", "list", "of", "all", "the", "subscriptions", "of", "a", "socket", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/web/websocket.py#L189-L194
233,180
nameko/nameko
nameko/web/websocket.py
WebSocketHub.subscribe
def subscribe(self, socket_id, channel): """Subscribes a socket to a channel.""" con = self._get_connection(socket_id) self.subscriptions.setdefault(channel, set()).add(socket_id) con.subscriptions.add(channel)
python
def subscribe(self, socket_id, channel): con = self._get_connection(socket_id) self.subscriptions.setdefault(channel, set()).add(socket_id) con.subscriptions.add(channel)
[ "def", "subscribe", "(", "self", ",", "socket_id", ",", "channel", ")", ":", "con", "=", "self", ".", "_get_connection", "(", "socket_id", ")", "self", ".", "subscriptions", ".", "setdefault", "(", "channel", ",", "set", "(", ")", ")", ".", "add", "(",...
Subscribes a socket to a channel.
[ "Subscribes", "a", "socket", "to", "a", "channel", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/web/websocket.py#L196-L200
233,181
nameko/nameko
nameko/web/websocket.py
WebSocketHub.unsubscribe
def unsubscribe(self, socket_id, channel): """Unsubscribes a socket from a channel.""" con = self._get_connection(socket_id, create=False) if con is not None: con.subscriptions.discard(channel) try: self.subscriptions[channel].discard(socket_id) except KeyError: pass
python
def unsubscribe(self, socket_id, channel): con = self._get_connection(socket_id, create=False) if con is not None: con.subscriptions.discard(channel) try: self.subscriptions[channel].discard(socket_id) except KeyError: pass
[ "def", "unsubscribe", "(", "self", ",", "socket_id", ",", "channel", ")", ":", "con", "=", "self", ".", "_get_connection", "(", "socket_id", ",", "create", "=", "False", ")", "if", "con", "is", "not", "None", ":", "con", ".", "subscriptions", ".", "dis...
Unsubscribes a socket from a channel.
[ "Unsubscribes", "a", "socket", "from", "a", "channel", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/web/websocket.py#L202-L210
233,182
nameko/nameko
nameko/web/websocket.py
WebSocketHub.broadcast
def broadcast(self, channel, event, data): """Broadcasts an event to all sockets listening on a channel.""" payload = self._server.serialize_event(event, data) for socket_id in self.subscriptions.get(channel, ()): rv = self._server.sockets.get(socket_id) if rv is not None: rv.socket.send(payload)
python
def broadcast(self, channel, event, data): payload = self._server.serialize_event(event, data) for socket_id in self.subscriptions.get(channel, ()): rv = self._server.sockets.get(socket_id) if rv is not None: rv.socket.send(payload)
[ "def", "broadcast", "(", "self", ",", "channel", ",", "event", ",", "data", ")", ":", "payload", "=", "self", ".", "_server", ".", "serialize_event", "(", "event", ",", "data", ")", "for", "socket_id", "in", "self", ".", "subscriptions", ".", "get", "(...
Broadcasts an event to all sockets listening on a channel.
[ "Broadcasts", "an", "event", "to", "all", "sockets", "listening", "on", "a", "channel", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/web/websocket.py#L212-L218
233,183
nameko/nameko
nameko/web/websocket.py
WebSocketHub.unicast
def unicast(self, socket_id, event, data): """Sends an event to a single socket. Returns `True` if that worked or `False` if not. """ payload = self._server.serialize_event(event, data) rv = self._server.sockets.get(socket_id) if rv is not None: rv.socket.send(payload) return True return False
python
def unicast(self, socket_id, event, data): payload = self._server.serialize_event(event, data) rv = self._server.sockets.get(socket_id) if rv is not None: rv.socket.send(payload) return True return False
[ "def", "unicast", "(", "self", ",", "socket_id", ",", "event", ",", "data", ")", ":", "payload", "=", "self", ".", "_server", ".", "serialize_event", "(", "event", ",", "data", ")", "rv", "=", "self", ".", "_server", ".", "sockets", ".", "get", "(", ...
Sends an event to a single socket. Returns `True` if that worked or `False` if not.
[ "Sends", "an", "event", "to", "a", "single", "socket", ".", "Returns", "True", "if", "that", "worked", "or", "False", "if", "not", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/web/websocket.py#L220-L229
233,184
nameko/nameko
nameko/log_helpers.py
make_timing_logger
def make_timing_logger(logger, precision=3, level=logging.DEBUG): """ Return a timing logger. Usage:: >>> logger = logging.getLogger('foobar') >>> log_time = make_timing_logger( ... logger, level=logging.INFO, precision=2) >>> >>> with log_time("hello %s", "world"): ... time.sleep(1) INFO:foobar:hello world in 1.00s """ @contextmanager def log_time(msg, *args): """ Log `msg` and `*args` with (naive wallclock) timing information when the context block exits. """ start_time = time.time() try: yield finally: message = "{} in %0.{}fs".format(msg, precision) duration = time.time() - start_time args = args + (duration,) logger.log(level, message, *args) return log_time
python
def make_timing_logger(logger, precision=3, level=logging.DEBUG): @contextmanager def log_time(msg, *args): """ Log `msg` and `*args` with (naive wallclock) timing information when the context block exits. """ start_time = time.time() try: yield finally: message = "{} in %0.{}fs".format(msg, precision) duration = time.time() - start_time args = args + (duration,) logger.log(level, message, *args) return log_time
[ "def", "make_timing_logger", "(", "logger", ",", "precision", "=", "3", ",", "level", "=", "logging", ".", "DEBUG", ")", ":", "@", "contextmanager", "def", "log_time", "(", "msg", ",", "*", "args", ")", ":", "\"\"\" Log `msg` and `*args` with (naive wallclock) t...
Return a timing logger. Usage:: >>> logger = logging.getLogger('foobar') >>> log_time = make_timing_logger( ... logger, level=logging.INFO, precision=2) >>> >>> with log_time("hello %s", "world"): ... time.sleep(1) INFO:foobar:hello world in 1.00s
[ "Return", "a", "timing", "logger", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/log_helpers.py#L8-L36
233,185
nameko/nameko
nameko/web/server.py
WebServer.get_wsgi_server
def get_wsgi_server( self, sock, wsgi_app, protocol=HttpOnlyProtocol, debug=False ): """Get the WSGI server used to process requests.""" return wsgi.Server( sock, sock.getsockname(), wsgi_app, protocol=protocol, debug=debug, log=getLogger(__name__) )
python
def get_wsgi_server( self, sock, wsgi_app, protocol=HttpOnlyProtocol, debug=False ): return wsgi.Server( sock, sock.getsockname(), wsgi_app, protocol=protocol, debug=debug, log=getLogger(__name__) )
[ "def", "get_wsgi_server", "(", "self", ",", "sock", ",", "wsgi_app", ",", "protocol", "=", "HttpOnlyProtocol", ",", "debug", "=", "False", ")", ":", "return", "wsgi", ".", "Server", "(", "sock", ",", "sock", ".", "getsockname", "(", ")", ",", "wsgi_app",...
Get the WSGI server used to process requests.
[ "Get", "the", "WSGI", "server", "used", "to", "process", "requests", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/web/server.py#L125-L136
233,186
nameko/nameko
nameko/standalone/events.py
get_event_exchange
def get_event_exchange(service_name): """ Get an exchange for ``service_name`` events. """ exchange_name = "{}.events".format(service_name) exchange = Exchange( exchange_name, type='topic', durable=True, delivery_mode=PERSISTENT ) return exchange
python
def get_event_exchange(service_name): exchange_name = "{}.events".format(service_name) exchange = Exchange( exchange_name, type='topic', durable=True, delivery_mode=PERSISTENT ) return exchange
[ "def", "get_event_exchange", "(", "service_name", ")", ":", "exchange_name", "=", "\"{}.events\"", ".", "format", "(", "service_name", ")", "exchange", "=", "Exchange", "(", "exchange_name", ",", "type", "=", "'topic'", ",", "durable", "=", "True", ",", "deliv...
Get an exchange for ``service_name`` events.
[ "Get", "an", "exchange", "for", "service_name", "events", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/standalone/events.py#L10-L18
233,187
nameko/nameko
nameko/standalone/events.py
event_dispatcher
def event_dispatcher(nameko_config, **kwargs): """ Return a function that dispatches nameko events. """ amqp_uri = nameko_config[AMQP_URI_CONFIG_KEY] serializer, _ = serialization.setup(nameko_config) serializer = kwargs.pop('serializer', serializer) ssl = nameko_config.get(AMQP_SSL_CONFIG_KEY) # TODO: standalone event dispatcher should accept context event_data # and insert a call id publisher = Publisher(amqp_uri, serializer=serializer, ssl=ssl, **kwargs) def dispatch(service_name, event_type, event_data): """ Dispatch an event claiming to originate from `service_name` with the given `event_type` and `event_data`. """ exchange = get_event_exchange(service_name) publisher.publish( event_data, exchange=exchange, routing_key=event_type ) return dispatch
python
def event_dispatcher(nameko_config, **kwargs): amqp_uri = nameko_config[AMQP_URI_CONFIG_KEY] serializer, _ = serialization.setup(nameko_config) serializer = kwargs.pop('serializer', serializer) ssl = nameko_config.get(AMQP_SSL_CONFIG_KEY) # TODO: standalone event dispatcher should accept context event_data # and insert a call id publisher = Publisher(amqp_uri, serializer=serializer, ssl=ssl, **kwargs) def dispatch(service_name, event_type, event_data): """ Dispatch an event claiming to originate from `service_name` with the given `event_type` and `event_data`. """ exchange = get_event_exchange(service_name) publisher.publish( event_data, exchange=exchange, routing_key=event_type ) return dispatch
[ "def", "event_dispatcher", "(", "nameko_config", ",", "*", "*", "kwargs", ")", ":", "amqp_uri", "=", "nameko_config", "[", "AMQP_URI_CONFIG_KEY", "]", "serializer", ",", "_", "=", "serialization", ".", "setup", "(", "nameko_config", ")", "serializer", "=", "kw...
Return a function that dispatches nameko events.
[ "Return", "a", "function", "that", "dispatches", "nameko", "events", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/standalone/events.py#L21-L48
233,188
nameko/nameko
nameko/timer.py
Timer._run
def _run(self): """ Runs the interval loop. """ def get_next_interval(): start_time = time.time() start = 0 if self.eager else 1 for count in itertools.count(start=start): yield max(start_time + count * self.interval - time.time(), 0) interval = get_next_interval() sleep_time = next(interval) while True: # sleep for `sleep_time`, unless `should_stop` fires, in which # case we leave the while loop and stop entirely with Timeout(sleep_time, exception=False): self.should_stop.wait() break self.handle_timer_tick() self.worker_complete.wait() self.worker_complete.reset() sleep_time = next(interval)
python
def _run(self): def get_next_interval(): start_time = time.time() start = 0 if self.eager else 1 for count in itertools.count(start=start): yield max(start_time + count * self.interval - time.time(), 0) interval = get_next_interval() sleep_time = next(interval) while True: # sleep for `sleep_time`, unless `should_stop` fires, in which # case we leave the while loop and stop entirely with Timeout(sleep_time, exception=False): self.should_stop.wait() break self.handle_timer_tick() self.worker_complete.wait() self.worker_complete.reset() sleep_time = next(interval)
[ "def", "_run", "(", "self", ")", ":", "def", "get_next_interval", "(", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "start", "=", "0", "if", "self", ".", "eager", "else", "1", "for", "count", "in", "itertools", ".", "count", "(", "st...
Runs the interval loop.
[ "Runs", "the", "interval", "loop", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/timer.py#L58-L80
233,189
nameko/nameko
nameko/messaging.py
QueueConsumer.stop
def stop(self): """ Stop the queue-consumer gracefully. Wait until the last provider has been unregistered and for the ConsumerMixin's greenthread to exit (i.e. until all pending messages have been acked or requeued and all consumers stopped). """ if not self._consumers_ready.ready(): _log.debug('stopping while consumer is starting %s', self) stop_exc = QueueConsumerStopped() # stopping before we have started successfully by brutally # killing the consumer thread as we don't have a way to hook # into the pre-consumption startup process self._gt.kill(stop_exc) self.wait_for_providers() try: _log.debug('waiting for consumer death %s', self) self._gt.wait() except QueueConsumerStopped: pass super(QueueConsumer, self).stop() _log.debug('stopped %s', self)
python
def stop(self): if not self._consumers_ready.ready(): _log.debug('stopping while consumer is starting %s', self) stop_exc = QueueConsumerStopped() # stopping before we have started successfully by brutally # killing the consumer thread as we don't have a way to hook # into the pre-consumption startup process self._gt.kill(stop_exc) self.wait_for_providers() try: _log.debug('waiting for consumer death %s', self) self._gt.wait() except QueueConsumerStopped: pass super(QueueConsumer, self).stop() _log.debug('stopped %s', self)
[ "def", "stop", "(", "self", ")", ":", "if", "not", "self", ".", "_consumers_ready", ".", "ready", "(", ")", ":", "_log", ".", "debug", "(", "'stopping while consumer is starting %s'", ",", "self", ")", "stop_exc", "=", "QueueConsumerStopped", "(", ")", "# st...
Stop the queue-consumer gracefully. Wait until the last provider has been unregistered and for the ConsumerMixin's greenthread to exit (i.e. until all pending messages have been acked or requeued and all consumers stopped).
[ "Stop", "the", "queue", "-", "consumer", "gracefully", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/messaging.py#L240-L266
233,190
nameko/nameko
nameko/messaging.py
QueueConsumer.kill
def kill(self): """ Kill the queue-consumer. Unlike `stop()` any pending message ack or requeue-requests, requests to remove providers, etc are lost and the consume thread is asked to terminate as soon as possible. """ # greenlet has a magic attribute ``dead`` - pylint: disable=E1101 if self._gt is not None and not self._gt.dead: # we can't just kill the thread because we have to give # ConsumerMixin a chance to close the sockets properly. self._providers = set() self._pending_remove_providers = {} self.should_stop = True try: self._gt.wait() except Exception as exc: # discard the exception since we're already being killed _log.warn( 'QueueConsumer %s raised `%s` during kill', self, exc) super(QueueConsumer, self).kill() _log.debug('killed %s', self)
python
def kill(self): # greenlet has a magic attribute ``dead`` - pylint: disable=E1101 if self._gt is not None and not self._gt.dead: # we can't just kill the thread because we have to give # ConsumerMixin a chance to close the sockets properly. self._providers = set() self._pending_remove_providers = {} self.should_stop = True try: self._gt.wait() except Exception as exc: # discard the exception since we're already being killed _log.warn( 'QueueConsumer %s raised `%s` during kill', self, exc) super(QueueConsumer, self).kill() _log.debug('killed %s', self)
[ "def", "kill", "(", "self", ")", ":", "# greenlet has a magic attribute ``dead`` - pylint: disable=E1101", "if", "self", ".", "_gt", "is", "not", "None", "and", "not", "self", ".", "_gt", ".", "dead", ":", "# we can't just kill the thread because we have to give", "# Co...
Kill the queue-consumer. Unlike `stop()` any pending message ack or requeue-requests, requests to remove providers, etc are lost and the consume thread is asked to terminate as soon as possible.
[ "Kill", "the", "queue", "-", "consumer", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/messaging.py#L268-L290
233,191
nameko/nameko
nameko/messaging.py
QueueConsumer.connection
def connection(self): """ Provide the connection parameters for kombu's ConsumerMixin. The `Connection` object is a declaration of connection parameters that is lazily evaluated. It doesn't represent an established connection to the broker at this point. """ heartbeat = self.container.config.get( HEARTBEAT_CONFIG_KEY, DEFAULT_HEARTBEAT ) transport_options = self.container.config.get( TRANSPORT_OPTIONS_CONFIG_KEY, DEFAULT_TRANSPORT_OPTIONS ) ssl = self.container.config.get(AMQP_SSL_CONFIG_KEY) conn = Connection(self.amqp_uri, transport_options=transport_options, heartbeat=heartbeat, ssl=ssl ) return conn
python
def connection(self): heartbeat = self.container.config.get( HEARTBEAT_CONFIG_KEY, DEFAULT_HEARTBEAT ) transport_options = self.container.config.get( TRANSPORT_OPTIONS_CONFIG_KEY, DEFAULT_TRANSPORT_OPTIONS ) ssl = self.container.config.get(AMQP_SSL_CONFIG_KEY) conn = Connection(self.amqp_uri, transport_options=transport_options, heartbeat=heartbeat, ssl=ssl ) return conn
[ "def", "connection", "(", "self", ")", ":", "heartbeat", "=", "self", ".", "container", ".", "config", ".", "get", "(", "HEARTBEAT_CONFIG_KEY", ",", "DEFAULT_HEARTBEAT", ")", "transport_options", "=", "self", ".", "container", ".", "config", ".", "get", "(",...
Provide the connection parameters for kombu's ConsumerMixin. The `Connection` object is a declaration of connection parameters that is lazily evaluated. It doesn't represent an established connection to the broker at this point.
[ "Provide", "the", "connection", "parameters", "for", "kombu", "s", "ConsumerMixin", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/messaging.py#L339-L359
233,192
nameko/nameko
nameko/messaging.py
QueueConsumer.get_consumers
def get_consumers(self, consumer_cls, channel): """ Kombu callback to set up consumers. Called after any (re)connection to the broker. """ _log.debug('setting up consumers %s', self) for provider in self._providers: callbacks = [partial(self.handle_message, provider)] consumer = consumer_cls( queues=[provider.queue], callbacks=callbacks, accept=self.accept ) consumer.qos(prefetch_count=self.prefetch_count) self._consumers[provider] = consumer return self._consumers.values()
python
def get_consumers(self, consumer_cls, channel): _log.debug('setting up consumers %s', self) for provider in self._providers: callbacks = [partial(self.handle_message, provider)] consumer = consumer_cls( queues=[provider.queue], callbacks=callbacks, accept=self.accept ) consumer.qos(prefetch_count=self.prefetch_count) self._consumers[provider] = consumer return self._consumers.values()
[ "def", "get_consumers", "(", "self", ",", "consumer_cls", ",", "channel", ")", ":", "_log", ".", "debug", "(", "'setting up consumers %s'", ",", "self", ")", "for", "provider", "in", "self", ".", "_providers", ":", "callbacks", "=", "[", "partial", "(", "s...
Kombu callback to set up consumers. Called after any (re)connection to the broker.
[ "Kombu", "callback", "to", "set", "up", "consumers", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/messaging.py#L369-L388
233,193
nameko/nameko
nameko/messaging.py
QueueConsumer.on_iteration
def on_iteration(self): """ Kombu callback for each `drain_events` loop iteration.""" self._cancel_consumers_if_requested() if len(self._consumers) == 0: _log.debug('requesting stop after iteration') self.should_stop = True
python
def on_iteration(self): self._cancel_consumers_if_requested() if len(self._consumers) == 0: _log.debug('requesting stop after iteration') self.should_stop = True
[ "def", "on_iteration", "(", "self", ")", ":", "self", ".", "_cancel_consumers_if_requested", "(", ")", "if", "len", "(", "self", ".", "_consumers", ")", "==", "0", ":", "_log", ".", "debug", "(", "'requesting stop after iteration'", ")", "self", ".", "should...
Kombu callback for each `drain_events` loop iteration.
[ "Kombu", "callback", "for", "each", "drain_events", "loop", "iteration", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/messaging.py#L390-L396
233,194
nameko/nameko
nameko/messaging.py
QueueConsumer.on_consume_ready
def on_consume_ready(self, connection, channel, consumers, **kwargs): """ Kombu callback when consumers are ready to accept messages. Called after any (re)connection to the broker. """ if not self._consumers_ready.ready(): _log.debug('consumer started %s', self) self._consumers_ready.send(None)
python
def on_consume_ready(self, connection, channel, consumers, **kwargs): if not self._consumers_ready.ready(): _log.debug('consumer started %s', self) self._consumers_ready.send(None)
[ "def", "on_consume_ready", "(", "self", ",", "connection", ",", "channel", ",", "consumers", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "_consumers_ready", ".", "ready", "(", ")", ":", "_log", ".", "debug", "(", "'consumer started %s'", ...
Kombu callback when consumers are ready to accept messages. Called after any (re)connection to the broker.
[ "Kombu", "callback", "when", "consumers", "are", "ready", "to", "accept", "messages", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/messaging.py#L404-L411
233,195
nameko/nameko
nameko/cli/shell.py
make_nameko_helper
def make_nameko_helper(config): """Create a fake module that provides some convenient access to nameko standalone functionality for interactive shell usage. """ module = ModuleType('nameko') module.__doc__ = """Nameko shell helper for making rpc calls and dispatching events. Usage: >>> n.rpc.service.method() "reply" >>> n.dispatch_event('service', 'event_type', 'event_data') """ proxy = ClusterRpcProxy(config) module.rpc = proxy.start() module.dispatch_event = event_dispatcher(config) module.config = config module.disconnect = proxy.stop return module
python
def make_nameko_helper(config): module = ModuleType('nameko') module.__doc__ = """Nameko shell helper for making rpc calls and dispatching events. Usage: >>> n.rpc.service.method() "reply" >>> n.dispatch_event('service', 'event_type', 'event_data') """ proxy = ClusterRpcProxy(config) module.rpc = proxy.start() module.dispatch_event = event_dispatcher(config) module.config = config module.disconnect = proxy.stop return module
[ "def", "make_nameko_helper", "(", "config", ")", ":", "module", "=", "ModuleType", "(", "'nameko'", ")", "module", ".", "__doc__", "=", "\"\"\"Nameko shell helper for making rpc calls and dispatching\nevents.\n\nUsage:\n >>> n.rpc.service.method()\n \"reply\"\n\n >>> n.dispa...
Create a fake module that provides some convenient access to nameko standalone functionality for interactive shell usage.
[ "Create", "a", "fake", "module", "that", "provides", "some", "convenient", "access", "to", "nameko", "standalone", "functionality", "for", "interactive", "shell", "usage", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/cli/shell.py#L58-L77
233,196
nameko/nameko
nameko/extensions.py
iter_extensions
def iter_extensions(extension): """ Depth-first iterator over sub-extensions on `extension`. """ for _, ext in inspect.getmembers(extension, is_extension): for item in iter_extensions(ext): yield item yield ext
python
def iter_extensions(extension): for _, ext in inspect.getmembers(extension, is_extension): for item in iter_extensions(ext): yield item yield ext
[ "def", "iter_extensions", "(", "extension", ")", ":", "for", "_", ",", "ext", "in", "inspect", ".", "getmembers", "(", "extension", ",", "is_extension", ")", ":", "for", "item", "in", "iter_extensions", "(", "ext", ")", ":", "yield", "item", "yield", "ex...
Depth-first iterator over sub-extensions on `extension`.
[ "Depth", "-", "first", "iterator", "over", "sub", "-", "extensions", "on", "extension", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/extensions.py#L354-L360
233,197
nameko/nameko
nameko/extensions.py
Extension.bind
def bind(self, container): """ Get an instance of this Extension to bind to `container`. """ def clone(prototype): if prototype.is_bound(): raise RuntimeError('Cannot `bind` a bound extension.') cls = type(prototype) args, kwargs = prototype.__params instance = cls(*args, **kwargs) # instance.container must be a weakref to avoid a strong reference # from value to key in the `shared_extensions` weakkey dict # see test_extension_sharing.py: test_weakref instance.container = weakref.proxy(container) return instance instance = clone(self) # recurse over sub-extensions for name, ext in inspect.getmembers(self, is_extension): setattr(instance, name, ext.bind(container)) return instance
python
def bind(self, container): def clone(prototype): if prototype.is_bound(): raise RuntimeError('Cannot `bind` a bound extension.') cls = type(prototype) args, kwargs = prototype.__params instance = cls(*args, **kwargs) # instance.container must be a weakref to avoid a strong reference # from value to key in the `shared_extensions` weakkey dict # see test_extension_sharing.py: test_weakref instance.container = weakref.proxy(container) return instance instance = clone(self) # recurse over sub-extensions for name, ext in inspect.getmembers(self, is_extension): setattr(instance, name, ext.bind(container)) return instance
[ "def", "bind", "(", "self", ",", "container", ")", ":", "def", "clone", "(", "prototype", ")", ":", "if", "prototype", ".", "is_bound", "(", ")", ":", "raise", "RuntimeError", "(", "'Cannot `bind` a bound extension.'", ")", "cls", "=", "type", "(", "protot...
Get an instance of this Extension to bind to `container`.
[ "Get", "an", "instance", "of", "this", "Extension", "to", "bind", "to", "container", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/extensions.py#L81-L103
233,198
nameko/nameko
nameko/extensions.py
SharedExtension.bind
def bind(self, container): """ Bind implementation that supports sharing. """ # if there's already a matching bound instance, return that shared = container.shared_extensions.get(self.sharing_key) if shared: return shared instance = super(SharedExtension, self).bind(container) # save the new instance container.shared_extensions[self.sharing_key] = instance return instance
python
def bind(self, container): # if there's already a matching bound instance, return that shared = container.shared_extensions.get(self.sharing_key) if shared: return shared instance = super(SharedExtension, self).bind(container) # save the new instance container.shared_extensions[self.sharing_key] = instance return instance
[ "def", "bind", "(", "self", ",", "container", ")", ":", "# if there's already a matching bound instance, return that", "shared", "=", "container", ".", "shared_extensions", ".", "get", "(", "self", ".", "sharing_key", ")", "if", "shared", ":", "return", "shared", ...
Bind implementation that supports sharing.
[ "Bind", "implementation", "that", "supports", "sharing", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/extensions.py#L123-L136
233,199
nameko/nameko
nameko/extensions.py
DependencyProvider.bind
def bind(self, container, attr_name): """ Get an instance of this Dependency to bind to `container` with `attr_name`. """ instance = super(DependencyProvider, self).bind(container) instance.attr_name = attr_name self.attr_name = attr_name return instance
python
def bind(self, container, attr_name): instance = super(DependencyProvider, self).bind(container) instance.attr_name = attr_name self.attr_name = attr_name return instance
[ "def", "bind", "(", "self", ",", "container", ",", "attr_name", ")", ":", "instance", "=", "super", "(", "DependencyProvider", ",", "self", ")", ".", "bind", "(", "container", ")", "instance", ".", "attr_name", "=", "attr_name", "self", ".", "attr_name", ...
Get an instance of this Dependency to bind to `container` with `attr_name`.
[ "Get", "an", "instance", "of", "this", "Dependency", "to", "bind", "to", "container", "with", "attr_name", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/extensions.py#L143-L150