code
stringlengths
501
5.19M
package
stringlengths
2
81
path
stringlengths
9
304
filename
stringlengths
4
145
import argparse import os import sys import traceback from dataclasses import dataclass, field from typing import Dict, Optional import yaml from zuper_commons.types import import_name from zuper_ipce import object_from_ipce from zuper_typing import debug_print from . import logger from zuper_nodes_wrapper.constants import CTRL_ABORTED, CTRL_OVER from zuper_nodes_wrapper.wrapper import CommContext, open_comms from .interface import wrap_direct __all__ = ['launcher_main'] @dataclass class NodeLaunchConfig: node: str protocol: str config: Dict[str, object] = field(default_factory=dict) # noinspection PyBroadException def launcher_main(): sys.path.append(os.getcwd()) prog = 'node-launch' parser = argparse.ArgumentParser(prog=prog) # define arguments parser.add_argument( "--config", required=True, help="Config file (node_launch.yaml)", ) parser.add_argument( "--protocol", help="Protocol (python symbol)", ) parser.add_argument( "--node", help="node class (python symbol)", ) parser.add_argument( "--check", default=False, action='store_true', help="only check symbols importable" ) # parse arguments parsed = parser.parse_args() errors = [] node_type = None node = None config:Optional[NodeLaunchConfig] = None def complain(m: str, **kwargs): er = m, kwargs logger.error(er[0], **er[1]) errors.append(er) if parsed.config: if not os.path.exists(parsed.config): msg = f'Cannot find path {parsed.config}' complain(msg) else: try: with open(parsed.config) as f: data = f.read() y = yaml.load(data, Loader=yaml.Loader) config = object_from_ipce(y, NodeLaunchConfig) except Exception: msg = f'Cannot load config file {parsed.config}' complain(msg, tb=traceback.format_exc()) else: node_symbol = parsed.node protocol_symbol = parsed.protocol if node_symbol is None or protocol_symbol is None: msg = 'Either specify --config or both --node and --protocol' complain(msg) else: config = NodeLaunchConfig(node=node_symbol, protocol=protocol_symbol, config={}) protocol = None sys.path.append(os.getcwd()) if not errors: try: node_type = import_name(config.node) except Exception: msg = 'Cannot import the node class' complain(msg, node_symbol=config.node, tb=traceback.format_exc()) if parsed.check: if errors: logger.error('Check not passed') sys.exit(1) else: logger.info('Check passed') sys.exit(0) if not errors: try: # noinspection PyCallingNonCallable node = node_type() except Exception: msg = 'Cannot instantiate the node class' complain(msg, node_symbol=config.node, node_type=node_type, tb=traceback.format_exc()) if not errors: try: protocol = import_name(config.protocol) except Exception: msg = 'Cannot import the protocol class' complain(msg, protocol_symbol=config.protocol, tb=traceback.format_exc()) if not errors: return wrap_direct(node=node, protocol=protocol, args=[]) else: cc: CommContext with open_comms('unnamed', logger_meta=logger) as cc: msg = debug_print(errors) cc.fo_sink.write_control_message(CTRL_ABORTED, msg) cc.fo_sink.write_control_message(CTRL_OVER) if __name__ == '__main__': launcher_main()
zuper-nodes-z6
/zuper-nodes-z6-6.2.17.tar.gz/zuper-nodes-z6-6.2.17/src/zuper_nodes_wrapper/launcher.py
launcher.py
import termcolor __all__ = ['setup_logging_color', 'setup_logging_format', 'setup_logging', 'logger'] def get_FORMAT_datefmt(): def dark(s): return termcolor.colored(s, attrs=['dark']) pre = dark('%(asctime)s|') pre += '%(name)s' pre += dark('|%(filename)s:%(lineno)s|%(funcName)s(): ') FORMAT = pre + "%(message)s" datefmt = "%H:%M:%S" return FORMAT, datefmt def setup_logging_format(): from logging import Logger, StreamHandler, Formatter import logging FORMAT, datefmt = get_FORMAT_datefmt() logging.basicConfig(format=FORMAT, datefmt=datefmt) if Logger.root.handlers: # @UndefinedVariable for handler in Logger.root.handlers: # @UndefinedVariable if isinstance(handler, StreamHandler): formatter = Formatter(FORMAT, datefmt=datefmt) handler.setFormatter(formatter) else: logging.basicConfig(format=FORMAT, datefmt=datefmt) def add_coloring_to_emit_ansi(fn): # add methods we need to the class def new(*args): levelno = args[1].levelno if levelno >= 50: color = '\x1b[31m' # red elif levelno >= 40: color = '\x1b[31m' # red elif levelno >= 30: color = '\x1b[33m' # yellow elif levelno >= 20: color = '\x1b[32m' # green elif levelno >= 10: color = '\x1b[35m' # pink else: color = '\x1b[0m' # normal msg = str(args[1].msg) lines = msg.split('\n') def color_line(l): return "%s%s%s" % (color, l, '\x1b[0m') # normal lines = list(map(color_line, lines)) args[1].msg = "\n".join(lines) return fn(*args) return new def setup_logging_color(): import platform if platform.system() != 'Windows': emit2 = add_coloring_to_emit_ansi(logging.StreamHandler.emit) logging.StreamHandler.emit = emit2 def setup_logging(): # logging.basicConfig() setup_logging_color() setup_logging_format() import logging logging.basicConfig() setup_logging()
zuper-nodes
/zuper-nodes-2.0.3.tar.gz/zuper-nodes-2.0.3/src/zuper_nodes/col_logging.py
col_logging.py
from pyparsing import Suppress, Literal, Keyword, ParserElement, pyparsing_common, opAssoc, operatorPrecedence from .language import ExpectInputReceived, ExpectOutputProduced, InSequence, ZeroOrMore, ZeroOrOne, Either, Language, \ OneOrMore __all__ = [ 'parse_language', 'language_to_str', 'Syntax', ] ParserElement.enablePackrat() S = Suppress L = Literal K = Keyword def parse_language(s: str) -> Language: res = Syntax.language.parseString(s, parseAll=True) res = res[0] return res def language_to_str(l: Language): def quote_if(s): if ';' in s or '|' in s: return "(" + s + ')' else: return s if isinstance(l, ExpectInputReceived): return f"in:{l.channel}" if isinstance(l, ExpectOutputProduced): return f"out:{l.channel}" if isinstance(l, InSequence): return " ; ".join(quote_if(language_to_str(_)) for _ in l.ls) if isinstance(l, Either): return " | ".join(quote_if(language_to_str(_)) for _ in l.ls) if isinstance(l, ZeroOrMore): return "(" + language_to_str(l.l) + ")" + '*' if isinstance(l, OneOrMore): return "(" + language_to_str(l.l) + ")" + '+' if isinstance(l, ZeroOrOne): return "(" + language_to_str(l.l) + ")" + '?' raise NotImplementedError(type(l)) def on_input_received(s, loc, tokens): return ExpectInputReceived(tokens[0]) def on_output_produced(s, loc, tokens): return ExpectOutputProduced(tokens[0]) def on_in_sequence(tokens): return InSequence(tuple(tokens[0])) def on_either(tokens): return Either(tuple(tokens[0])) def on_zero_or_one(tokens): return ZeroOrOne(tokens[0][0]) def on_zero_or_more(tokens): return ZeroOrMore(tokens[0][0]) def on_one_or_more(tokens): return OneOrMore(tokens[0][0]) class Syntax: input_received = S(K("in") + L(":")) + pyparsing_common.identifier output_produced = S(K("out") + L(":")) + pyparsing_common.identifier basic = input_received | output_produced language = operatorPrecedence(basic, [ (S(L('*')), 1, opAssoc.LEFT, on_zero_or_more), (S(L('+')), 1, opAssoc.LEFT, on_one_or_more), (S(L('?')), 1, opAssoc.LEFT, on_zero_or_one), (S(L(';')), 2, opAssoc.LEFT, on_in_sequence), (S(L('|')), 2, opAssoc.LEFT, on_either), ]) input_received.setParseAction(on_input_received) output_produced.setParseAction(on_output_produced)
zuper-nodes
/zuper-nodes-2.0.3.tar.gz/zuper-nodes-2.0.3/src/zuper_nodes/language_parse.py
language_parse.py
from dataclasses import dataclass from typing import Union, Tuple, Optional, Set from .language import Language, OutputProduced, InputReceived, Event, ExpectInputReceived, ExpectOutputProduced, \ InSequence, ZeroOrMore, Either, OneOrMore, ZeroOrOne from contracts.utils import indent class Result: pass @dataclass class Enough(Result): pass @dataclass class Unexpected(Result): msg: str def __repr__(self): return 'Unexpected:' + indent(self.msg, ' ') @dataclass class NeedMore(Result): pass import networkx as nx NodeName = Tuple[str, ...] class Always: pass def get_nfa(g: Optional[nx.DiGraph], start_node: NodeName, accept_node: NodeName, l: Language, prefix: Tuple[str, ...] = ()): # assert start_node != accept_node if not start_node in g: g.add_node(start_node, label="/".join(start_node)) if not accept_node in g: g.add_node(accept_node, label="/".join(accept_node)) if isinstance(l, ExpectOutputProduced): g.add_edge(start_node, accept_node, event_match=l, label=f'out/{l.channel}') elif isinstance(l, ExpectInputReceived): g.add_edge(start_node, accept_node, event_match=l, label=f'in/{l.channel}') elif isinstance(l, InSequence): current = start_node for i, li in enumerate(l.ls): # if i == len(l.ls) - 1: # n = accept_node # else: n = prefix + (f'after{i}',) g.add_node(n) # logger.debug(f'sequence {i} start {current} to {n}') get_nfa(g, start_node=current, accept_node=n, prefix=prefix + (f'{i}',), l=li) current = n g.add_edge(current, accept_node, event_match=Always(), label='always') elif isinstance(l, ZeroOrMore): # logger.debug(f'zeroormore {start_node} -> {accept_node}') g.add_edge(start_node, accept_node, event_match=Always(), label='always') get_nfa(g, start_node=accept_node, accept_node=accept_node, l=l.l, prefix=prefix + ('zero_or_more',)) elif isinstance(l, OneOrMore): # start to accept get_nfa(g, start_node=start_node, accept_node=accept_node, l=l.l, prefix=prefix + ('one_or_more', '1')) # accept to accept get_nfa(g, start_node=accept_node, accept_node=accept_node, l=l.l, prefix=prefix + ('one_or_more', '2')) elif isinstance(l, ZeroOrOne): g.add_edge(start_node, accept_node, event_match=Always(), label='always') get_nfa(g, start_node=start_node, accept_node=accept_node, l=l.l, prefix=prefix + ('zero_or_one',)) elif isinstance(l, Either): for i, li in enumerate(l.ls): get_nfa(g, start_node=start_node, accept_node=accept_node, l=li, prefix=prefix + (f'either{i}',)) else: assert False, type(l) def event_matches(l: Language, event: Event): if isinstance(l, ExpectInputReceived): return isinstance(event, InputReceived) and event.channel == l.channel if isinstance(l, ExpectOutputProduced): return isinstance(event, OutputProduced) and event.channel == l.channel if isinstance(l, Always): return False raise NotImplementedError(l) START = ('start',) ACCEPT = ('accept',) class LanguageChecker: g: nx.DiGraph active: Set[NodeName] def __init__(self, language: Language): self.g = nx.MultiDiGraph() self.start_node = START self.accept_node = ACCEPT get_nfa(g=self.g, l=language, start_node=self.start_node, accept_node=self.accept_node, prefix=()) # for (a, b, data) in self.g.out_edges(data=True): # print(f'{a} -> {b} {data["event_match"]}') a = 2 for n in self.g: if n not in [START, ACCEPT]: # noinspection PyUnresolvedReferences self.g.node[n]['label'] = f'S{a}' a += 1 elif n == START: # noinspection PyUnresolvedReferences self.g.node[n]['label'] = 'start' elif n == ACCEPT: # noinspection PyUnresolvedReferences self.g.node[n]['label'] = 'accept' self.active = {self.start_node} # logger.debug(f'active {self.active}') self._evolve_empty() def _evolve_empty(self): while True: now_active = set() for node in self.active: nalways = 0 nother = 0 for (_, neighbor, data) in self.g.out_edges([node], data=True): # print(f'-> {neighbor} {data["event_match"]}') if isinstance(data['event_match'], Always): now_active.add(neighbor) nalways += 1 else: nother += 1 if nother or (nalways == 0): now_active.add(node) if self.active == now_active: break self.active = now_active def push(self, event) -> Result: now_active = set() # print(f'push: active is {self.active}') # print(f'push: considering {event}') for node in self.active: for (_, neighbor, data) in self.g.out_edges([node], data=True): if event_matches(data['event_match'], event): # print(f'now activating {neighbor}') now_active.add(neighbor) # else: # print(f"event_match {event} does not match {data['event_match']}") # # if not now_active: # return Unexpected('') self.active = now_active # print(f'push: now active is {self.active}') self._evolve_empty() # print(f'push: now active is {self.active}') return self.finish() def finish(self) -> Union[NeedMore, Enough, Unexpected]: # print(f'finish: active is {self.active}') if not self.active: return Unexpected('no active') if self.accept_node in self.active: return Enough() return NeedMore() def get_active_states_names(self): return [self.g.nodes[_]['label'] for _ in self.active] def get_expected_events(self) -> Set: events = set() for state in self.active: for (_, neighbor, data) in self.g.out_edges([state], data=True): em = data['event_match'] if not isinstance(em, Always): events.add(em) return events
zuper-nodes
/zuper-nodes-2.0.3.tar.gz/zuper-nodes-2.0.3/src/zuper_nodes/language_recognize.py
language_recognize.py
from abc import abstractmethod, ABCMeta from dataclasses import dataclass from typing import Tuple, Dict, Iterator, Optional, Union # Events ChannelName = str class Event: pass @dataclass(frozen=True, unsafe_hash=True) class InputReceived(Event): channel: ChannelName @dataclass(frozen=True, unsafe_hash=True) class OutputProduced(Event): channel: ChannelName # Language over events class Language(metaclass=ABCMeta): @abstractmethod def collect_simple_events(self) -> Iterator[Event]: pass @dataclass(frozen=True, unsafe_hash=True) class ExpectInputReceived(Language): channel: ChannelName def collect_simple_events(self): yield InputReceived(self.channel) @dataclass(frozen=True, unsafe_hash=True) class ExpectOutputProduced(Language): channel: ChannelName def collect_simple_events(self): yield OutputProduced(self.channel) @dataclass(frozen=True, unsafe_hash=True) class InSequence(Language): ls: Tuple[Language, ...] def collect_simple_events(self): for l in self.ls: yield from l.collect_simple_events() @dataclass(frozen=True, unsafe_hash=True) class ZeroOrOne(Language): l: Language def collect_simple_events(self): yield from self.l.collect_simple_events() @dataclass(frozen=True, unsafe_hash=True) class ZeroOrMore(Language): l: Language def collect_simple_events(self): yield from self.l.collect_simple_events() @dataclass(frozen=True, unsafe_hash=True) class OneOrMore(Language): l: Language def collect_simple_events(self): yield from self.l.collect_simple_events() @dataclass(frozen=True, unsafe_hash=True) class Either(Language): ls: Tuple[Language, ...] def collect_simple_events(self): for l in self.ls: yield from l.collect_simple_events() # Interaction protocol @dataclass class InteractionProtocol: # Description description: str # Type for each input or output inputs: Dict[ChannelName, type] outputs: Dict[ChannelName, type] # The interaction language language: str # interaction: Language = None def __post_init__(self): from .language_parse import parse_language, language_to_str self.interaction = parse_language(self.language) simple_events = list(self.interaction.collect_simple_events()) for e in simple_events: if isinstance(e, InputReceived): if e.channel not in self.inputs: msg = f'Could not find input channel "{e.channel}" among {sorted(self.inputs)}.' raise ValueError(msg) if isinstance(e, OutputProduced): if e.channel not in self.outputs: msg = f'Could not find output channel "{e.channel}" among {sorted(self.outputs)}.' raise ValueError(msg) self.language = language_to_str(self.interaction) def particularize(ip: InteractionProtocol, description: Optional[str] = None, inputs: Optional[Dict[str, type]] = None, outputs: Optional[Dict[str, type]] = None) -> InteractionProtocol: inputs2 = dict(ip.inputs) inputs2.update(inputs or {}) outputs2 = dict(ip.outputs) outputs2.update(outputs or {}) language = ip.language description = description or ip.description protocol2 = InteractionProtocol(description, inputs2, outputs2, language) from .compatibility import check_compatible_protocol check_compatible_protocol(protocol2, ip) return protocol2
zuper-nodes
/zuper-nodes-2.0.3.tar.gz/zuper-nodes-2.0.3/src/zuper_nodes/language.py
language.py
import argparse import json import os import socket import time import traceback from dataclasses import dataclass from typing import * import yaml from contracts.utils import format_obs from zuper_commons.text import indent from zuper_commons.types import check_isinstance from zuper_json.ipce import object_to_ipce, ipce_to_object from zuper_nodes import InteractionProtocol, InputReceived, OutputProduced, Unexpected, LanguageChecker from zuper_nodes.structures import TimingInfo, local_time, TimeSpec, timestamp_from_seconds, DecodingError, \ ExternalProtocolViolation, NotConforming, ExternalTimeout, InternalProblem from .reading import inputs from .streams import open_for_read, open_for_write from .struct import RawTopicMessage, ControlMessage from .utils import call_if_fun_exists from .writing import Sink from . import logger, logger_interaction from .interface import Context from .meta_protocol import basic_protocol, SetConfig, ProtocolDescription, ConfigDescription, \ BuildDescription, NodeDescription class ConcreteContext(Context): protocol: InteractionProtocol to_write: List[RawTopicMessage] def __init__(self, sink: Sink, protocol: InteractionProtocol, node_name: str, tout: Dict[str, str]): self.sink = sink self.protocol = protocol self.pc = LanguageChecker(protocol.interaction) self.node_name = node_name self.hostname = socket.gethostname() self.tout = tout self.to_write = [] self.last_timing = None def set_last_timing(self, timing: TimingInfo): self.last_timing = timing def get_hostname(self): return self.hostname def write(self, topic, data, timing=None, with_schema=False): if topic not in self.protocol.outputs: msg = f'Output channel "{topic}" not found in protocol; know {sorted(self.protocol.outputs)}.' raise Exception(msg) # logger.info(f'Writing output "{topic}".') klass = self.protocol.outputs[topic] if isinstance(klass, type): check_isinstance(data, klass) event = OutputProduced(topic) res = self.pc.push(event) if isinstance(res, Unexpected): msg = f'Unexpected output {topic}: {res}' logger.error(msg) return klass = self.protocol.outputs[topic] if isinstance(data, dict): data = ipce_to_object(data, {}, {}, expect_type=klass) if timing is None: timing = self.last_timing if timing is not None: s = time.time() if timing.received is None: # XXX time1 = timestamp_from_seconds(s) else: time1 = timing.received.time processed = TimeSpec(time=time1, time2=timestamp_from_seconds(s), frame='epoch', clock=socket.gethostname()) timing.processed[self.node_name] = processed timing.received = None topic_o = self.tout.get(topic, topic) data = object_to_ipce(data, {}, with_schema=with_schema) if timing is not None: timing_o = object_to_ipce(timing, {}, with_schema=False) else: timing_o = None rtm = RawTopicMessage(topic_o, data, timing_o) self.to_write.append(rtm) def get_to_write(self) -> List[RawTopicMessage]: """ Returns the messages to send and resets the queue""" res = self.to_write self.to_write = [] return res def log(self, s): prefix = f'{self.hostname}:{self.node_name}: ' logger.info(prefix + s) def info(self, s): prefix = f'{self.hostname}:{self.node_name}: ' logger.info(prefix + s) def debug(self, s): prefix = f'{self.hostname}:{self.node_name}: ' logger.debug(prefix + s) def warning(self, s): prefix = f'{self.hostname}:{self.node_name}: ' logger.warning(prefix + s) def error(self, s): prefix = f'{self.hostname}:{self.node_name}: ' logger.error(prefix + s) def get_translation_table(t: str) -> Tuple[Dict[str, str], Dict[str, str]]: tout = {} tin = {} for t in t.split(','): ts = t.split(':') if ts[0] == 'in': tin[ts[1]] = ts[2] if ts[0] == 'out': tout[ts[1]] = ts[2] return tin, tout def check_variables(): for k, v in os.environ.items(): if k.startswith('AIDO') and k not in KNOWN: msg = f'I do not expect variable "{k}" set in environment with value "{v}".' msg += ' I expect: %s' % ", ".join(KNOWN) logger.warn(msg) from .constants import * def run_loop(node, protocol: InteractionProtocol, args: Optional[List[str]] = None): parser = argparse.ArgumentParser() check_variables() data_in = os.environ.get(ENV_DATA_IN, '/dev/stdin') data_out = os.environ.get(ENV_DATA_OUT, '/dev/stdout') default_name = os.environ.get(ENV_NAME, None) translate = os.environ.get(ENV_TRANSLATE, '') config = os.environ.get(ENV_CONFIG, '{}') parser.add_argument('--data-in', default=data_in) parser.add_argument('--data-out', default=data_out) parser.add_argument('--name', default=default_name) parser.add_argument('--config', default=config) parser.add_argument('--translate', default=translate) parser.add_argument('--loose', default=False, action='store_true') parsed = parser.parse_args(args) tin, tout = get_translation_table(parsed.translate) # expect in:name1:name2, out:name2:name1 fin = parsed.data_in fout = parsed.data_out fi = open_for_read(fin) fo = open_for_write(fout) node_name = parsed.name or type(node).__name__ logger.name = node_name config = yaml.load(config, Loader=yaml.SafeLoader) try: loop(node_name, fi, fo, node, protocol, tin, tout, config=config) except BaseException as e: msg = f'Error in node {node_name}' logger.error(f'Error in node {node_name}: \n{traceback.format_exc()}') raise Exception(msg) from e finally: fo.flush() fo.close() fi.close() def loop(node_name: str, fi, fo, node, protocol: InteractionProtocol, tin, tout, config: dict): logger.info(f'Starting reading') initialized = False context_data = None sink = Sink(fo) try: context_data = ConcreteContext(sink=sink, protocol=protocol, node_name=node_name, tout=tout) context_meta = ConcreteContext(sink=sink, protocol=basic_protocol, node_name=node_name + '.wrapper', tout=tout) wrapper = MetaHandler(node, protocol) for k, v in config.items(): wrapper.set_config(k, v) waiting_for = 'Expecting control message or one of: %s' % context_data.pc.get_expected_events() for parsed in inputs(fi, waiting_for=waiting_for): if isinstance(parsed, ControlMessage): expect = [CTRL_CAPABILITIES] if parsed.code not in expect: msg = f'I expect any of {expect}, not "{parsed.code}".' sink.write_control_message(CTRL_NOT_UNDERSTOOD, msg) sink.write_control_message(CTRL_OVER) else: if parsed.code == CTRL_CAPABILITIES: my_capabilities = { 'z2': { CAPABILITY_PROTOCOL_REFLECTION: True } } sink.write_control_message(CTRL_UNDERSTOOD) sink.write_control_message(CTRL_CAPABILITIES, my_capabilities) sink.write_control_message(CTRL_OVER) else: assert False elif isinstance(parsed, RawTopicMessage): parsed.topic = tin.get(parsed.topic, parsed.topic) logger_interaction.info(f'Received message of topic "{parsed.topic}".') if parsed.topic.startswith('wrapper.'): parsed.topic = parsed.topic.replace('wrapper.', '') receiver0 = wrapper context0 = context_meta else: receiver0 = node context0 = context_data if receiver0 is node and not initialized: try: call_if_fun_exists(node, 'init', context=context_data) except BaseException as e: msg = "Exception while calling the node's init() function." msg += '\n\n' + indent(traceback.format_exc(), '| ') context_meta.write('aborted', msg) raise Exception(msg) from e initialized = True if parsed.topic not in context0.protocol.inputs: msg = f'Input channel "{parsed.topic}" not found in protocol. ' msg += f'\n\nKnown channels: {sorted(context0.protocol.inputs)}' sink.write_control_message(CTRL_NOT_UNDERSTOOD, msg) sink.write_control_message(CTRL_OVER) raise ExternalProtocolViolation(msg) sink.write_control_message(CTRL_UNDERSTOOD) try: handle_message_node(parsed, receiver0, context0) to_write = context0.get_to_write() # msg = f'I wrote {len(to_write)} messages.' # logger.info(msg) for rtm in to_write: sink.write_topic_message(rtm.topic, rtm.data, rtm.timing) sink.write_control_message(CTRL_OVER) except BaseException as e: msg = f'Exception while handling a message on topic "{parsed.topic}".' msg += '\n\n' + indent(traceback.format_exc(), '| ') sink.write_control_message(CTRL_ABORTED, msg) sink.write_control_message(CTRL_OVER) raise InternalProblem(msg) from e # XXX else: assert False res = context_data.pc.finish() if isinstance(res, Unexpected): msg = f'Protocol did not finish: {res}' logger_interaction.error(msg) if initialized: try: call_if_fun_exists(node, 'finish', context=context_data) except BaseException as e: msg = "Exception while calling the node's finish() function." msg += '\n\n' + indent(traceback.format_exc(), '| ') context_meta.write('aborted', msg) raise Exception(msg) from e except BrokenPipeError: msg = 'The other side closed communication.' logger.info(msg) return except ExternalTimeout as e: msg = 'Could not receive any other messages.' if context_data: msg += '\n Expecting one of: %s' % context_data.pc.get_expected_events() sink.write_control_message(CTRL_ABORTED, msg) sink.write_control_message(CTRL_OVER) raise ExternalTimeout(msg) from e except InternalProblem: raise except BaseException as e: msg = f"Unexpected error:" msg += '\n\n' + indent(traceback.format_exc(), '| ') sink.write_control_message(CTRL_ABORTED, msg) sink.write_control_message(CTRL_OVER) raise InternalProblem(msg) from e # XXX class MetaHandler: def __init__(self, node, protocol): self.node = node self.protocol = protocol def set_config(self, key, value): if hasattr(self.node, ATT_CONFIG): config = self.node.config if hasattr(config, key): setattr(self.node.config, key, value) else: msg = f'Could not find config key {key}' raise ValueError(msg) else: msg = 'Node does not have the "config" attribute.' raise ValueError(msg) def on_received_set_config(self, context, data: SetConfig): key = data.key value = data.value try: self.set_config(key, value) except ValueError as e: context.write('set_config_error', str(e)) else: context.write('set_config_ack', None) def on_received_describe_protocol(self, context): desc = ProtocolDescription(data=self.protocol, meta=basic_protocol) context.write('protocol_description', desc) def on_received_describe_config(self, context): K = type(self.node) if hasattr(K, '__annotations__') and ATT_CONFIG in K.__annotations__: config_type = K.__annotations__[ATT_CONFIG] config_current = getattr(self.node, ATT_CONFIG) else: @dataclass class NoConfig: pass config_type = NoConfig config_current = NoConfig() desc = ConfigDescription(config=config_type, current=config_current) context.write('config_description', desc, with_schema=True) def on_received_describe_node(self, context): desc = NodeDescription(self.node.__doc__) context.write('node_description', desc, with_schema=True) def on_received_describe_build(self, context): desc = BuildDescription() context.write('build_description', desc, with_schema=True) def handle_message_node(parsed: RawTopicMessage, agent, context: ConcreteContext): protocol = context.protocol topic = parsed.topic data = parsed.data pc = context.pc klass = protocol.inputs[topic] try: ob = ipce_to_object(data, {}, {}, expect_type=klass) except BaseException as e: msg = f'Cannot deserialize object for topic "{topic}" expecting {klass}.' try: parsed = json.dumps(parsed, indent=2) except: parsed = str(parsed) msg += '\n\n' + indent(parsed, '|', 'parsed: |') raise DecodingError(msg) from e if parsed.timing is not None: timing = ipce_to_object(parsed.timing, {}, {}, expect_type=TimingInfo) else: timing = TimingInfo() timing.received = local_time() context.set_last_timing(timing) # logger.info(f'Before push the state is\n{pc}') event = InputReceived(topic) expected = pc.get_expected_events() res = pc.push(event) # names = pc.get_active_states_names() # logger.info(f'After push of {event}: result \n{res} active {names}' ) if isinstance(res, Unexpected): msg = f'Unexpected input "{topic}": {res}' msg += f'\nI expected: {expected}' msg += '\n' + format_obs(dict(pc=pc)) logger.error(msg) raise ExternalProtocolViolation(msg) else: expect_fn = f'on_received_{topic}' call_if_fun_exists(agent, expect_fn, data=ob, context=context, timing=timing) def check_implementation(node, protocol: InteractionProtocol): logger.info('checking implementation') for n in protocol.inputs: expect_fn = f'on_received_{n}' if not hasattr(node, expect_fn): msg = f'Missing function {expect_fn}' msg += f'\nI know {sorted(type(node).__dict__)}' raise NotConforming(msg) for x in type(node).__dict__: if x.startswith('on_received_'): input_name = x.replace('on_received_', '') if input_name not in protocol.inputs: msg = f'The node has function "{x}" but there is no input "{input_name}".' raise NotConforming(msg)
zuper-nodes
/zuper-nodes-2.0.3.tar.gz/zuper-nodes-2.0.3/src/zuper_nodes_wrapper/wrapper.py
wrapper.py
import os import stat import time from io import BufferedReader from zuper_commons.fs import make_sure_dir_exists from . import logger_interaction from . import logger def wait_for_creation(fn): while not os.path.exists(fn): msg = 'waiting for creation of %s' % fn logger.info(msg) time.sleep(1) def open_for_read(fin, timeout=None): t0 = time.time() # first open reader file in case somebody is waiting for it while not os.path.exists(fin): delta = time.time() - t0 if timeout is not None and (delta > timeout): msg = f'The file {fin} was not created before {timeout} seconds. I give up.' raise EnvironmentError(msg) logger_interaction.info(f'waiting for file {fin} to be created') time.sleep(1) logger_interaction.info(f'Opening input {fin}') fi = open(fin, 'rb', buffering=0) # noinspection PyTypeChecker fi = BufferedReader(fi, buffer_size=1) return fi def open_for_write(fout): if fout == '/dev/stdout': return open('/dev/stdout', 'wb', buffering=0) else: wants_fifo = fout.startswith('fifo:') fout = fout.replace('fifo:', '') logger_interaction.info(f'Opening output file {fout} (wants fifo: {wants_fifo})') if not os.path.exists(fout): if wants_fifo: make_sure_dir_exists(fout) os.mkfifo(fout) logger_interaction.info('Fifo created.') else: is_fifo = stat.S_ISFIFO(os.stat(fout).st_mode) if wants_fifo and not is_fifo: logger_interaction.info(f'Recreating {fout} as a fifo.') os.unlink(fout) os.mkfifo(fout) if wants_fifo: logger_interaction.info('Fifo detected. Opening will block until a reader appears.') make_sure_dir_exists(fout) fo = open(fout, 'wb', buffering=0) if wants_fifo: logger_interaction.info('Reader has connected to my fifo') return fo
zuper-nodes
/zuper-nodes-2.0.3.tar.gz/zuper-nodes-2.0.3/src/zuper_nodes_wrapper/streams.py
streams.py
from dataclasses import dataclass from typing import * from zuper_nodes import InteractionProtocol @dataclass class SetConfig: key: str value: Any @dataclass class ConfigDescription: config: type current: Any @dataclass class NodeDescription: description: str @dataclass class BuildDescription: pass @dataclass class ProtocolDescription: data: InteractionProtocol meta: InteractionProtocol @dataclass class CommsHealth: # ignored because not compatible ignored: Dict[str, int] # unexpected topics unexpected: Dict[str, int] # malformed data malformed: Dict[str, int] # if we are completely lost unrecoverable_protocol_error: bool @dataclass class NodeHealth: # there is a critical error that makes it useless to continue critical: bool # severe problem but we can continue severe: bool # a minor problem to report minor: bool details: str LogEntry = str basic_protocol = InteractionProtocol( description="""\ Basic interaction protocol for nodes spoken by the node wrapper. """, inputs={ "describe_config": type(None), "set_config": SetConfig, "describe_protocol": type(None), "describe_node": type(None), "describe_build": type(None), "get_state": type(None), "set_state": Any, "get_logs": type(None), }, language="""\ ( (in:describe_config ; out:config_description) | (in:set_config ; (out:set_config_ack | out:set_config_error)) | (in:describe_protocol ; out:protocol_description) | (in:describe_node ; out:node_description) | (in:describe_build ; out:build_description) | (in:get_state ; out:node_state) | (in:set_state ; (out:set_state_ack| out:set_state_error) ) | (in:get_logs ; out:logs) | out:aborted )* """, outputs={ "config_description": ConfigDescription, 'set_config_ack': type(None), 'set_config_error': str, 'protocol_description': ProtocolDescription, 'node_description': NodeDescription, 'build_description': BuildDescription, 'node_state': Any, 'set_state_ack': type(None), 'set_state_error': str, 'logs': List[LogEntry], 'aborted': str, })
zuper-nodes
/zuper-nodes-2.0.3.tar.gz/zuper-nodes-2.0.3/src/zuper_nodes_wrapper/meta_protocol.py
meta_protocol.py
import os from io import BufferedReader from typing import * import cbor2 as cbor from zuper_commons.text import indent from zuper_json.ipce import object_to_ipce, ipce_to_object from zuper_json.json2cbor import read_next_cbor from zuper_nodes import InteractionProtocol, ExternalProtocolViolation from zuper_nodes.compatibility import check_compatible_protocol from zuper_nodes.structures import TimingInfo, RemoteNodeAborted, ExternalNodeDidNotUnderstand from zuper_nodes_wrapper.meta_protocol import ProtocolDescription, basic_protocol from zuper_nodes_wrapper.streams import wait_for_creation from zuper_nodes_wrapper.struct import MsgReceived, interpret_control_message, WireMessage from . import logger, logger_interaction from .constants import * class ComponentInterface: def __init__(self, fnin: str, fnout: str, expect_protocol: InteractionProtocol, nickname: str, timeout=None): self.nickname = nickname self._cc = None try: os.mkfifo(fnin) except BaseException as e: msg = f'Cannot create fifo {fnin}' raise Exception(msg) from e self.fpin = open(fnin, 'wb', buffering=0) wait_for_creation(fnout) self.fnout = fnout f = open(fnout, 'rb', buffering=0) # noinspection PyTypeChecker self.fpout = BufferedReader(f, buffer_size=1) self.nreceived = 0 self.expect_protocol = expect_protocol self.node_protocol = None self.data_protocol = None self.timeout = timeout def close(self): self.fpin.close() self.fpout.close() def cc(self, f): """ CC-s everything that is read or written to this file. """ self._cc = f def _get_node_protocol(self, timeout=None): self.my_capabilities = {'z2': {CAPABILITY_PROTOCOL_REFLECTION: True}} msg = {FIELD_CONTROL: CTRL_CAPABILITIES, FIELD_DATA: self.my_capabilities} j = self._serialize(msg) self._write(j) msgs = read_reply(self.fpout, timeout=timeout, waiting_for=f"Reading {self.nickname} capabilities", nickname=self.nickname) self.node_capabilities = msgs[0]['data'] logger.info('My capabilities: %s' % self.my_capabilities) logger.info('Found capabilities: %s' % self.node_capabilities) if 'z2' not in self.node_capabilities: msg = 'Incompatible node; capabilities %s' % self.node_capabilities raise ExternalProtocolViolation(msg) z = self.node_capabilities['z2'] if not z.get(CAPABILITY_PROTOCOL_REFLECTION, False): logger.info('Node does not support reflection.') if self.expect_protocol is None: msg = 'Node does not support reflection - need to provide protocol.' raise Exception(msg) else: ob: MsgReceived[ProtocolDescription] = \ self.write_topic_and_expect('wrapper.describe_protocol', expect='protocol_description', timeout=timeout) self.node_protocol = ob.data.data self.data_protocol = ob.data.meta if self.expect_protocol is not None: check_compatible_protocol(self.node_protocol, self.expect_protocol) def write_topic_and_expect(self, topic, data=None, with_schema=False, timeout=None, timing=None, expect=None) -> MsgReceived: timeout = timeout or self.timeout self._write_topic(topic, data=data, with_schema=with_schema, timing=timing) ob: MsgReceived = self.read_one(expect_topic=expect, timeout=timeout) return ob def write_topic_and_expect_zero(self, topic, data=None, with_schema=False, timeout=None, timing=None): timeout = timeout or self.timeout self._write_topic(topic, data=data, with_schema=with_schema, timing=timing) msgs = read_reply(self.fpout, timeout=timeout, nickname=self.nickname) if msgs: msg = 'Expecting zero, got %s' % msgs raise ExternalProtocolViolation(msg) def _write_topic(self, topic, data=None, with_schema=False, timing=None): suggest_type = None if self.node_protocol: if topic in self.node_protocol.inputs: suggest_type = self.node_protocol.inputs[topic] ipce = object_to_ipce(data, {}, with_schema=with_schema, suggest_type=suggest_type) # try to re-read if suggest_type: try: _ = ipce_to_object(ipce, {}, expect_type=suggest_type) except BaseException as e: msg = f'While attempting to write on topic "{topic}", cannot ' \ f'interpret the value as {suggest_type}.\nValue: {data}' raise Exception(msg) from e # XXX msg = {FIELD_COMPAT: [CUR_PROTOCOL], FIELD_TOPIC: topic, FIELD_DATA: ipce, FIELD_TIMING: timing} j = self._serialize(msg) self._write(j) # make sure we write the schema when we copy it if not with_schema: msg[FIELD_DATA] = object_to_ipce(data, {}, with_schema=True) j = self._serialize(msg) if self._cc: self._cc.write(j) self._cc.flush() logger_interaction.info(f'Written to topic "{topic}" >> {self.nickname}.') def _write(self, j): try: self.fpin.write(j) self.fpin.flush() except BrokenPipeError as e: msg = f'While attempting to write to node "{self.nickname}", ' \ f'I reckon that the pipe is closed and the node exited.' try: received = self.read_one(expect_topic=TOPIC_ABORTED) if received.topic == TOPIC_ABORTED: msg += '\n\nThis is the aborted message:' msg += '\n\n' + indent(received.data, ' |') except BaseException as e2: msg += f'\n\nI could not read any aborted message: {e2}' raise RemoteNodeAborted(msg) from e def _serialize(self, msg) -> bytes: j = cbor.dumps(msg) return j def read_one(self, expect_topic=None, timeout=None) -> MsgReceived: timeout = timeout or self.timeout try: if expect_topic: waiting_for = f'Expecting topic "{expect_topic}" << {self.nickname}.' else: waiting_for = None msgs = read_reply(self.fpout, timeout=timeout, waiting_for=waiting_for, nickname=self.nickname) if len(msgs) == 0: msg = f'Expected one message from node "{self.nickname}". Got zero.' if expect_topic: msg += f'\nExpecting topic "{expect_topic}".' raise ExternalProtocolViolation(msg) if len(msgs) > 1: msg = f'Expected only one message. Got {msgs}' raise ExternalProtocolViolation(msg) msg = msgs[0] if FIELD_TOPIC not in msg: m = f'Invalid message does not contain the field "{FIELD_TOPIC}".' m += f'\n {msg}' raise ExternalProtocolViolation(m) topic = msg[FIELD_TOPIC] if expect_topic: if topic != expect_topic: msg = f'I expected topic "{expect_topic}" but received "{topic}".' raise ExternalProtocolViolation(msg) if topic in basic_protocol.outputs: klass = basic_protocol.outputs[topic] else: if self.node_protocol: if topic not in self.node_protocol.outputs: msg = f'Cannot find topic "{topic}" in outputs of detected node protocol.' msg += '\nI know: %s' % sorted(self.node_protocol.outputs) raise ExternalProtocolViolation(msg) else: klass = self.node_protocol.outputs[topic] else: if not topic in self.expect_protocol.outputs: msg = f'Cannot find topic "{topic}".' raise ExternalProtocolViolation(msg) else: klass = self.expect_protocol.outputs[topic] data = ipce_to_object(msg[FIELD_DATA], {}, expect_type=klass) if self._cc: msg[FIELD_DATA] = object_to_ipce(data, {}, with_schema=True) msg_b = self._serialize(msg) self._cc.write(msg_b) self._cc.flush() if FIELD_TIMING not in msg: timing = TimingInfo() else: timing = ipce_to_object(msg[FIELD_TIMING], {}, expect_type=TimingInfo) self.nreceived += 1 return MsgReceived[klass](topic, data, timing) except StopIteration as e: msg = 'EOF detected on %s after %d messages.' % (self.fnout, self.nreceived) if expect_topic: msg += f' Expected topic "{expect_topic}".' raise StopIteration(msg) from e except TimeoutError as e: msg = 'Timeout detected on %s after %d messages.' % (self.fnout, self.nreceived) if expect_topic: msg += f' Expected topic "{expect_topic}".' raise TimeoutError(msg) from e def read_reply(fpout, nickname: str, timeout=None, waiting_for=None, ) -> List: """ Reads a control message. Returns if it is CTRL_UNDERSTOOD. Raises: TimeoutError RemoteNodeAborted ExternalNodeDidNotUnderstand ExternalProtocolViolation otherwise. """ try: wm: WireMessage = read_next_cbor(fpout, timeout=timeout, waiting_for=waiting_for) # logger.debug(f'{nickname} sent {wm}') except StopIteration: msg = 'Remote node closed communication (%s)' % waiting_for raise RemoteNodeAborted(msg) from None cm = interpret_control_message(wm) if cm.code == CTRL_UNDERSTOOD: others = read_until_over(fpout, timeout=timeout, nickname=nickname) return others elif cm.code == CTRL_ABORTED: msg = f'The remote node "{nickname}" aborted with the following error:' msg += '\n\n' + indent(cm.msg, "|", f"error in {nickname} |") # others = self.read_until_over() raise RemoteNodeAborted(msg) elif cm.code == CTRL_NOT_UNDERSTOOD: _others = read_until_over(fpout, timeout=timeout, nickname=nickname) msg = f'The remote node "{nickname}" reports that it did not understand the message:' msg += '\n\n' + indent(cm.msg, "|", f"reported by {nickname} |") raise ExternalNodeDidNotUnderstand(msg) else: msg = 'Remote node raised unknown code %s: %s' % (cm, cm.code) raise ExternalProtocolViolation(msg) def read_until_over(fpout, timeout, nickname) -> List[WireMessage]: """ Raises RemoteNodeAborted, TimeoutError """ res = [] waiting_for = f'Reading reply of {nickname}.' while True: try: wm: WireMessage = read_next_cbor(fpout, timeout=timeout, waiting_for=waiting_for) if wm.get(FIELD_CONTROL, '') == CTRL_ABORTED: m = f'External node "{nickname}" aborted:' m += '\n\n' + indent(wm.get(FIELD_DATA, None), "|", f"error in {nickname} |") raise RemoteNodeAborted(m) if wm.get(FIELD_CONTROL, '') == CTRL_OVER: # logger.info(f'Node "{nickname}" concluded output of %s messages.' % len(res)) break # logger.info(f'Node "{nickname}" sent %s.' % len(wm)) except StopIteration: msg = f'External node "{nickname}" closed communication.' raise RemoteNodeAborted(msg) from None except TimeoutError: msg = f'Timeout while reading output of node "{nickname}".' raise TimeoutError(msg) from None res.append(wm) return res
zuper-nodes
/zuper-nodes-2.0.3.tar.gz/zuper-nodes-2.0.3/src/zuper_nodes_wrapper/wrapper_outside.py
wrapper_outside.py
import select import time from typing import * from zuper_commons.text import indent from zuper_json.json2cbor import read_next_cbor from zuper_nodes.structures import ExternalTimeout from zuper_nodes_wrapper.struct import interpret_control_message, RawTopicMessage, ControlMessage from . import logger from .constants import * M = Union[RawTopicMessage, ControlMessage] def inputs(f, give_up: Optional[float] = None, waiting_for: str = None) -> Iterator[M]: last = time.time() intermediate_timeout = 3.0 intermediate_timeout_multiplier = 1.5 while True: readyr, readyw, readyx = select.select([f], [], [f], intermediate_timeout) if readyr: try: parsed = read_next_cbor(f, waiting_for=waiting_for) except StopIteration: return if not isinstance(parsed, dict): msg = f'Expected a dictionary, obtained {parsed!r}' logger.error(msg) continue if FIELD_CONTROL in parsed: m = interpret_control_message(parsed) yield m elif FIELD_TOPIC in parsed: if not FIELD_COMPAT in parsed: msg = f'Could not find field "compat" in structure "{parsed}".' logger.error(msg) continue l = parsed[FIELD_COMPAT] if not isinstance(l, list): msg = f'Expected a list for compatibility value, found {l!r}' logger.error(msg) continue if not CUR_PROTOCOL in parsed[FIELD_COMPAT]: msg = f'Skipping message because could not find {CUR_PROTOCOL} in {l}.' logger.warn(msg) continue rtm = RawTopicMessage(parsed[FIELD_TOPIC], parsed.get(FIELD_DATA, None), parsed.get(FIELD_TIMING, None)) yield rtm elif readyx: logger.warning('Exceptional condition on input channel %s' % readyx) else: delta = time.time() - last if give_up is not None and (delta > give_up): msg = f'I am giving up after %.1f seconds.' % delta raise ExternalTimeout(msg) else: intermediate_timeout *= intermediate_timeout_multiplier msg = f'Input channel not ready after %.1f seconds. Will re-try.' % delta if waiting_for: msg += '\n' + indent(waiting_for, '> ') msg = 'I will warn again in %.1f seconds.' % intermediate_timeout logger.warning(msg)
zuper-nodes
/zuper-nodes-2.0.3.tar.gz/zuper-nodes-2.0.3/src/zuper_nodes_wrapper/reading.py
reading.py
import argparse import dataclasses import json import subprocess import sys from dataclasses import dataclass from io import BytesIO, BufferedReader import cbor2 import yaml from zuper_nodes import InteractionProtocol from zuper_nodes_wrapper.meta_protocol import BuildDescription, NodeDescription, ConfigDescription, ProtocolDescription from contracts import indent from zuper_json import read_cbor_or_json_objects from zuper_json.ipce import ipce_to_object from . import logger def identify_main(): usage = None parser = argparse.ArgumentParser(usage=usage) parser.add_argument('--image', default=None) parser.add_argument('--command', default=None) parsed = parser.parse_args() image = parsed.image if image is not None: ni: NodeInfo = identify_image2(image) elif parsed.command is not None: command = parsed.command.split() ni: NodeInfo = identify_command(command) else: msg = 'Please specify either --image or --command' logger.error(msg) sys.exit(1) print('\n\n') print(indent(describe_nd(ni.nd), '', 'desc: ')) print('\n\n') print(indent(describe_bd(ni.bd), '', 'build: ')) print('\n\n') print(indent(describe_cd(ni.cd), '', 'config: ')) print('\n\n') print(indent(describe(ni.pd.data), '', 'data: ')) print('\n\n') print(indent(describe(ni.pd.meta), '', 'meta: ')) def describe_nd(nd: NodeDescription): return str(nd.description) def describe_bd(nd: BuildDescription): return str(nd) def describe_cd(nd: ConfigDescription): s = [] for f in dataclasses.fields(nd.config): # for k, v in nd.config.__annotations__.items(): s.append('%20s: %s = %s' % (f.name, f.type, f.default)) if not s: return 'No configuration switches available.' if hasattr(nd.config, '__doc__'): s.insert(0, nd.config.__doc__) return "\n".join(s) def describe(ip: InteractionProtocol): s = "InteractionProtocol" s += '\n\n' + '* Description:' s += '\n\n' + indent(ip.description.strip(), ' ') s += '\n\n' + '* Inputs:' for name, type_ in ip.inputs.items(): s += '\n %25s: %s' % (name, type_) s += '\n\n' + '* Outputs:' for name, type_ in ip.outputs.items(): s += '\n %25s: %s' % (name, type_) s += '\n\n' + '* Language:' s += '\n\n' + ip.language return s @dataclass class NodeInfo: pd: ProtocolDescription nd: NodeDescription bd: BuildDescription cd: ConfigDescription def identify_command(command) -> NodeInfo: d = [{'topic': 'wrapper.describe_protocol'}, {'topic': 'wrapper.describe_config'}, {'topic': 'wrapper.describe_node'}, {'topic': 'wrapper.describe_build'} ] to_send = b'' for p in d: p['compat'] = ['aido2'] # to_send += (json.dumps(p) + '\n').encode('utf-8') to_send += cbor2.dumps(p) cp = subprocess.run(command, input=to_send, capture_output=True) s = cp.stderr.decode('utf-8') sys.stderr.write(indent(s.strip(), '|', ' stderr: |') + '\n\n') # noinspection PyTypeChecker f = BufferedReader(BytesIO(cp.stdout)) stream = read_cbor_or_json_objects(f) res = stream.__next__() logger.debug(yaml.dump(res)) pd: ProtocolDescription = ipce_to_object(res['data'], {}, {}, expect_type=ProtocolDescription) res = stream.__next__() logger.debug(yaml.dump(res)) cd: ConfigDescription = ipce_to_object(res['data'], {}, {}, expect_type=ConfigDescription) res = stream.__next__() logger.debug(yaml.dump(res)) nd: NodeDescription = ipce_to_object(res['data'], {}, {}, expect_type=NodeDescription) res = stream.__next__() logger.debug(yaml.dump(res)) bd: BuildDescription = ipce_to_object(res['data'], {}, {}, expect_type=BuildDescription) logger.debug(yaml.dump(res)) return NodeInfo(pd, nd, bd, cd) def identify_image2(image) -> NodeInfo: cmd = ['docker', 'run', '--rm', '-i', image] return identify_command(cmd) # def identify_image(image): # import docker # client = docker.from_env() # # # container: Container = client.containers.create(image, detach=True, stdin_open=True) # print(container) # # time.sleep(4) # # attach to the container stdin socket # container.start() # # s = container.exec_run() # s: SocketIO = container.attach_socket(params={'stdin': 1, 'stream': 1, 'stderr': 0, 'stdout': 0}) # s_out: SocketIO = container.attach_socket(params={ 'stream': 1, 'stdout': 1, 'stderr': 0, 'stdin': 0}) # s_stderr: SocketIO = container.attach_socket(params={'stream': 1, 'stdout': 0, 'stderr': 1, 'stdin': 0}) # print(s.__dict__) # print(s_out.__dict__) # # send text # # s.write(j) # os.write(s._sock.fileno(), j) # os.close(s._sock.fileno()) # s._sock.close() # # s.close() # # f = os.fdopen(s_out._sock.fileno(), 'rb') # # there is some garbage: b'\x01\x00\x00\x00\x00\x00\x1e|{ # f.read(8) # # for x in read_cbor_or_json_objects(f): # print(x) # print(f.read(10)) # # print(os.read(s_out._sock.fileno(), 100)) # # print(os.read(s_stderr._sock.fileno(), 100)) # # close, stop and disconnect # s.close()
zuper-nodes
/zuper-nodes-2.0.3.tar.gz/zuper-nodes-2.0.3/src/zuper_nodes_wrapper/identify.py
identify.py
Nodes should be able to specify components simulator_protocol = InteractionProtocol( description="""\ Interface to be implemented by a simulator. ```python language="(in:image ; out:image_out)*" components={ 'sub1': filter1, 'sub2': filter1, } inputs={ } connections=[ '(image) -> |sub1| -> |sub2| -> (image_out)' ] ``` def on_image_received(self, context, data): context.send('sub1', 'image', data) context.send('sub2', 'image', data) inputs={ "pwm_commands": PWMCommands, # Seed random number generator "seed": int, # Reset request "reset": type(None), # Render request - produces image "render_image": type(None), # Step physics "step_physics": float, # Dump state information "dump_state": float, }, outputs={ "image": JPGImage, "state_dump": Any, "reset_ack": type(None), "step_physics_ack": type(None), "episode_start": EpisodeStart, } ```
zuper-nodes
/zuper-nodes-2.0.3.tar.gz/zuper-nodes-2.0.3/docs/idea-composition.md
idea-composition.md
## Time representation * Reference clock frame: "epoch", "simulation episode" clock: hostname ## Uncertainty Optionally you can specify a second time instant, successive to the first, which defines the upper bound of the time. ## Type of timing info For sensor data: * "Last acquisition time": timestamp of the last acquired data * "Computed time": when this data was computed. * "Received" ## Wire representation ```json { "topic": "topic", "data": "data", "timing": { "acquired": { "obstopic1": {}, "obstopic2": {}, }, "computed": { "node1": {}, "node2": {}, "node3": {}, }, "received": { "frame": "sim", "time": {'s': 0, 'us': 1111}, "clock": "host1" }, } } ``` ## Advancing time ## API In Python: ```python from typing import * class Timestamp: s: int us: int class TimeSpec: time: Timestamp time2: Optional[Timestamp] frame: str clock: str class TimingInfo: acquired: Optional[Dict[str, TimeSpec]] processed: Optional[Dict[str, TimeSpec]] received: Optional[TimeSpec] def on_received_topicname(self, context, data, timing: TimingInfo): pass ```
zuper-nodes
/zuper-nodes-2.0.3.tar.gz/zuper-nodes-2.0.3/docs/idea-timestamping.md
idea-timestamping.md
# AIDO Nodes Protocol {#part:aido-protocol status=ready} This document describes the rationale and design for the AIDO protocol. <div id="toc"></div> # Goals and non-goals {status=ready} ## Goals ### Long shelf life We want to obtain a library of modules that have a long "shelf life". For example, it should be easy to run "the line detector from 2018" in 2021. This also suggests that modules should be independent of middle-ware as much as possible. ### Flexibility It should be possible to easily use a module in at least these scenarios: * On the robot in real-time. * Called as part of other modules ("module decorator"). * In a simulation, with the simulator both local (same host) or remote. * In "batch mode", where the data is supplied from logs. It should be possible to run two instances of the same module / system on the same host. ### Deterministic replay It should be possible to apply the same module to the same data and obtain the same output. Example violation: current Slimremote protocol runs simulation while it "waits" for the connection from the client. The result is then dependent on the network status. ### Deterministic uncertainty. There should be a clear way for modules to access a seed to use for their random number generators. ### Protocol checks It should be explicit what protocol a module uses, and it should be easy to check to avoid incompatibilities. Example: Understanding whether I can pipe `p1` into `p2`. ### Resource limitation Should be possible to give hard constraints on memory/cpu for each node. ### Protocol extendability The protocols should support a notion of extension; so that we can say that not only `p1` is different from `p2`, but also that any agent using `p1` would work with `p2`. ### Meta information Nice to have some meta information in the module (who wrote, the description, etc.) ## Non-goals {status=ready} ### Ultimate speed. We are OK in accepting a performance hit. (Note: did you know it takes 20ms to deserialize the line segment messages with ROS?) ## Why ROS is not a solution "Using ROS" is not a solution, due to the following problems. ### Network trouble ROS insists on having two processes need to know the other hosts not only by IP, but also by hostname. This causes a bunch of problems. ### Incompatibility ROS 1 does not allow Python 3. ### Non-compositionality It is not possible to run two ROS independent instances of a system on the same machine. # AIDO Nodes {status=ready} ## Overview We go back to the UNIX philosophy. "AIDO Nodes" or simply "nodes" are executable that read and write to `stdin` and `stdout`. The nodes are likely packaged in a Docker container. From our point of view, it does not matter whether we are running a naked executable or a containerized executable. In either case, there will be a standard input / standard output to write to. The data that is moved across these sockets is encoded as JSON-L: each line is a well-formed JSON message. JSON also allows to add binary data, encoded as a base64 string. AIDO Nodes interact according to well-defined protocols that are formally specified. There are two levels of formalization: 1. Describe which messages are valid messages. For this, we use JSON Schema. 2. Describe what is a valid interaction or sequence of messages. For this, we use a regular language. ## Individual JSON messages The messages are of the form: ```json {"topic": ![topic name], "data": ![data]} ``` A newline delimiter separates the JSON messages. The "topic name" has the same semantics as in ROS: while there is only one pipe for stdin/stdout, there are different logical streams of data that are labeled with a topic name. ## Formalizing the protocol To define a protocol, we need to specify: 1. What are the input and output channels. 2. For each channel, what is the data format. 3. What valid sequence of messages are accepted. Examples: * An agent of type P1 accepts a sequence of images and outputs a series of commands ("left", "right" velocity signals). * An agent of type P2 accepts intrinsic and extrinsic image calibration data followed a sequence of images and outputs a series of commands ("left", "right" velocity signals). * An agent of type P3 accepts intrinsic and extrinsic image calibration data, a kinematic calibration file, followed a sequence of images and outputs a series of commands ("left", "right" PWM signals). * An agent of type P4 accepts extrinsic image calibration data, a kinematic calibration file, followed a sequence of *rectified* images and outputs a series of commands ("left", "right" PWM signals). All of these are slighly different and failure of distinguishing between those caused much pain. Note that once we have these formalized, we can also do automatic conversion of protocols. ("If you have an agent of type P1, you can create an agent of type P2 by..."".) ## Language describing the interaction One way to formalize the interaction protocols are via regular languages. We use this syntax: * Define `in:![channel]` as denoting the event "a message was received on channel `![channel]`". * Define `out:![channel]` as denoting the event "a message was produced on channel `![channel]`". * Define `L*` as "Zero or more repetitions of `L`". * Define `L?` as "Zero or one repetitions of `L`". * Define `L+` as "One or more repetitions of `L`". * Define `A;B;C` as "`A` followed by `B` followed by `C`" * Define `A|B|C` as "either `A` or `B` or `C`" For example, consider the following protocol: "An agent that follows the protocol `LaneFilter` accepts one CameraCalibration message on the channel `calibration`, followed by any number of images on the channel `image`, and to each image it will reply with a pose estimate on channel `estimate`." As a formal language this can be written as: ``` LaneFilterLanguage := in:calibration (in:image ; out:estimate)* ``` This is then a formal description of the protocol; not only the data format, but also of the behavior of the component. ## User APIs Much of the complexity is hidden for the user. ### Defining protocols using `InteractionProtocol` Use the class `InterctionProtocol`. See `aido_nodes.protocols` for the currently defined protocols. Here is an example: ```python from zuper_nodes import InteractionProtocol from aido_schemas import JPGImage protocol_image_filter = InteractionProtocol( description="""Takes an image, returns an image.""", inputs={"image": JPGImage}, outputs={"transformed": JPGImage}, language=" (in:image ; out:transformed)*" ) ``` Above, `JPGImage` is a regular Python dataclass. The JSON schema description will be generated from the Python dataclass annotations. ### Creating nodes that follow the protocol There is an API that allows to easily create a node that follows the protocol while hiding all the complexity of JSON decoding/encoding. A minimal "image filter" can be realized as follows: ```python from aido_schemas import JPGImage, protocol_image_filter, wrap_direct class DummyFilter: protocol = protocol_image_filter def on_received_image(self, context, data: JPGImage): transformed = data # compute here context.write("transformed", transformed) if __name__ == '__main__': node = DummyFilter() wrap_direct(node=node, protocol=node.protocol) ``` The user must implement for each input channel `![channel name]` the function `on_received_![channel name]`. This function will be called with parameters `data`, containing the data received (already translated from JSON), and an object `context`. The object `context` provides the methods: ```python # write to the given output channel context.write('channel', data) # log something context.log('log string') ``` If the node implements it, the API will also call the function `init()` at the beginning and `finish()` at the end. ### Guarantees The node can assume that the sequence of calls will respect the protocol. For example, if the protocol is: ```in:calibration ; (in:image ; out:estimate)``` the node can assume that there is going to be a call to `on_received_calibration` before any call to `on_received_image`. On the other hand, note that the node itself must respect the protocol that has been declared. ## Dockerization examples See the folder `minimal` in this repository for the minimal implementation of the protocols so far defined. ## Extra features: configuration handling If the node has an attribute called `config`, then the API automatically exposes that configuration. For example, suppose the node is the following: ```python from aido_nodes import protocol_image_filter, JPGImage class MyConfig: num_frames: int = 3 class MyFilter: config: MyConfig = MyConfig() protocol = protocol_image_filter def on_received_image(self, context, data: JPGImage): ... def on_updated_config(self, context, key, value): context.log(f'Config was updated: {key} = {value!r}') ``` Then the node will also respond to "control" messages in the channel "`wrapper.set_config`" of the form: ```json {"topic": "wrapper.set_config", "data": {"key": "![config key]", "value": ![config value]}} ``` For example, in this case we can send a message like: ```json {"topic": "wrapper.set_config", "data": {"key": "num_frames", "value": 2}} ``` The API will automatically update the field `node.config.num_frames`. Then it will call (if defined) the function `on_updated_config()`; useful if something needs to be re-initialized. ## More complicated example of language Consider the protocol called `aido_nodes.protocol_image_source`: ```python protocol_image_source = InteractionProtocol( inputs={"next_image": type(None), # ask for the next image "next_episode": type(None)}, # ask for the next episode outputs={"image": JPGImage, # the output data "episode_start": EpisodeStart, # marks the start of episode "no_more_images": type(None), "no_more_episodes": type(None)}, interaction=parse_language(""" ( in:next_episode ; ( out:no_more_episodes | (out:episode_start ; (in:next_image ; (out:image | out:no_more_images))*) ) )* """), ) ``` `type(None)` means that those messages do not carry any payload. The informal description is: 1) First, the node expects to receive a `next_episode` message to start the episode. 2) To this, it can respond either with `no_more_episodes` or `episode_start`. 3) Then it will expect messages `next_image` to which it will reply either with an `image` or with `no_more_images`. <!-- The nondeterministic finite automaton for the language is parsed as in [](#example_language1): <figure id='example_language1'> <img src="aido-protocol.assets/example_language1.svg"/> <figcaption> In this diagram, "always" corresponds to an automatic transition. </figcaption> </figure> --> ## Gains from formal definition {status=beta} We can then use the usual machinery of the field of formal languages to reason about composition and extendability. ### Extending interaction protocol For example, we can describe backward-compatibility extensions of protocols. Imagine that there is a lane filter who can also accept IMU data. But not always it will provide an updated pose from the IMU data. Its language would be: ``` LaneFilterLanguage2 := in:calibration ( (in:image out:estimate) | (in:IMU out:estimate? ))* ``` It is possible (with some assumptions) to reason that LaneFilterLanguage1 is a sublanguage of LaneFilterLanguage2, so that an aidonode that implements the second can be used where the first would be used. ### Extending messages Another possibility is where the data type is extended. Already from JSON schema we have a notion of partial order. For example imagine a message with two fields: ```json {"field1": ..., "field2": ...} ``` Adding a field should be a backward compatible change (we did this a few times with AIDO). ```json {"field1": ..., "field2": ..., "extra_field": ...} ``` Here is how it looks like in JSON Schema. Note that JSON Schema also allows defining various constraints (apart from the type, also minimum/maximum values etc.) The first schema is: ```json { "title": "Message v1", "description": "First version of the messages", "type": "object", "fields": { "field1": { "type": "integer", "exclusiveMinimum": 0, }, "field2": { "type": "string" } } } ``` The second schema is: ```json { "title": "Message v1", "description": "First version of the messages", "type": "object", "fields": { "field1": { "type": "integer", "exclusiveMinimum": 0, }, "field2": { "type": "string" }, "extra_field": { "type": "string" } } } ``` ## More detailed architecture {status=draft} ### ROS wrapper <figure id="fig:wrapper"> <img src="aido-protocol.assets/image-20190210152739118.png"/> </figure> ### Batch processing <figure id="fig:batch"> <img src="aido-protocol.assets/image-20190210153222688.png"/> </figure> <style> img { max-width: 100%; } </style>
zuper-nodes
/zuper-nodes-2.0.3.tar.gz/zuper-nodes-2.0.3/docs/protocol.md
protocol.md
import timeit import cbor2 import cbor import numpy as np import pybase64 as base64 import ujson as json def bytes_to_json(jpg_bytes: bytes) -> str: data = { 'jpg_bytes': base64.b64encode(jpg_bytes).decode('ascii') } return json.dumps(data).encode('utf-8') def bytes_to_cbor(jpg_bytes: bytes) -> bytes: data = { 'jpg_bytes': jpg_bytes, } return cbor.dumps(data) def bytes_to_cbor_b64(jpg_bytes: bytes) -> bytes: data = { 'jpg_bytes': base64.b64encode(jpg_bytes).decode('ascii') } return cbor.dumps(data) def bytes_to_cbor2(jpg_bytes: bytes) -> bytes: data = { 'jpg_bytes': jpg_bytes, } return cbor2.dumps(data) def bytes_to_cbor2_b64(jpg_bytes: bytes) -> bytes: data = { 'jpg_bytes': base64.b64encode(jpg_bytes).decode('ascii') } return cbor2.dumps(data) def get_jpg_image(shape) -> bytes: H, W = shape values = (128 + np.random.randn(H, W, 3) * 60).astype('uint8') jpg_data = bgr2jpg(values) return jpg_data def bgr2jpg(image_cv) -> bytes: import cv2 # noinspection PyUnresolvedReferences compress = cv2.imencode('.jpg', image_cv)[1] jpg_data = np.array(compress).tostring() return jpg_data N = 3 shape = (480 * N, 640 * N) test_image: bytes = get_jpg_image(shape) # f = open('stream.bin', 'wb') def test1(): """ JSON with base64""" res = bytes_to_json(test_image) def test2(): """ CBOR with base64""" res = bytes_to_cbor_b64(test_image) def test3(): """ CBOR with built-in bytes""" res = bytes_to_cbor(test_image) def test4(): """ CBOR2 with base64""" res = bytes_to_cbor2_b64(test_image) def test5(): """ CBOR2 with built-in bytes""" res = bytes_to_cbor2(test_image) number = 800 for f in [test3, test2, test4, test5, test1,]: f() # warmup duration = timeit.timeit(f, number=number) latency_ms = duration / number * 1000 size = '%d KB' % (len(test_image) / 1024) print(f'{f.__doc__}: shape {shape} ({size}) latency = {latency_ms} ms') # # duration = timeit.timeit(test2, number=number) # # latency_ms = duration / number * 1000 # size = '%d KB' % (len(test_image) / 1024) # print(f'CBOR encoding: shape {shape} ({size}) latency = {latency_ms} ms') # # with open('test_vector.jpg', 'wb') as f: # f.write(test_image)
zuper-nodes
/zuper-nodes-2.0.3.tar.gz/zuper-nodes-2.0.3/docs/performance.py
performance.py
Minimal node protocol ==================== The node must support the following. ## Basic protocol The wires contain a sequence of CBOR messages. Each message is a dictionary. ## Basic control mechanism To every message the node responds with one of the two messages "understood", or "not understood". If understood: ```yaml control: understood ``` If not understood: ```yaml control: not-understood data: optional message string ``` In this case, the other party should not expect any result. Then there is a sequence of messages, terminated with a sequence marker: ```yaml control: over ``` ## Get capabilities The node might receive a `capabilities` message, whose `data` dictionary contains a dictionary. The semantics of these depend on the interaction. ```yaml control: capabilities data: z2: protocol-reflection: true ``` The node must respond with the sequence: ```yaml - control: understood - control: capabilities data: z2: protocol-reflection: true - control: over ```
zuper-nodes
/zuper-nodes-2.0.3.tar.gz/zuper-nodes-2.0.3/docs/protocol-hs.md
protocol-hs.md
from collections import defaultdict from typing import Callable, TypeVar, Set, Dict, Any from .utils import Generic, dataclass # from zuper_schemas.computation import AbstractFunctionCall from .computation import AbstractFunctionCall, FunctionResult # from zuper_schemas.core import FunctionResult from .crypto import Signed, PublicKey from mypy_extensions import NamedArg """ If we want to cache this by result FC we would have CachingService: thing_nature: @SFR key: {fr: fc} """ T = TypeVar('T') K = TypeVar('K') # accept_interface = Callable[[NamedArg(T, 'candidate')], bool] # index_interface = Callable[[NamedArg(T, 'candidate')], K] accept_interface = Any index_interface = Any @dataclass class CachingCriteria(Generic[T, K]): accept: accept_interface indexby: index_interface # store_interface = Callable[[NamedArg(T, 'candidate')], bool] # query_interface = Callable[[NamedArg(K, 'key')], Set[T]] store_interface = query_interface = Any @dataclass class CachingService(Generic[T, K]): criteria: CachingCriteria[T, K] # how we are going to get it? owner: PublicKey store: store_interface query: query_interface def accept_all_SFR(*, candidate: Signed[FunctionResult]) -> bool: return True def index_by_function_call(*, candidate: Signed[FunctionResult]) -> AbstractFunctionCall: return candidate.data.fc fc_caching_criteria = CachingCriteria[Signed[FunctionResult], AbstractFunctionCall]( accept=accept_all_SFR, indexby=index_by_function_call) class ConcreteCachingService(Generic[T, K]): def __init__(self, criteria: CachingCriteria): self.values: Dict[K, Set[T]] = defaultdict(set) self.owner = None self.criteria = criteria def store(self, *, candidate: T): if self.criteria.accept(candidate=candidate): k = self.criteria.indexby(candidate=candidate) self.values[k].add(candidate) def query(self, *, key: K): return self.values[key] @classmethod def examples(cls, self): fc_concrete_service = ConcreteCachingService[Signed[FunctionResult], AbstractFunctionCall](fc_caching_criteria) """ I provide function caching service for command results for $1 / query. ~CodesignProblem: requires: ~RTuple: transfer: ~TransferTo: value: 1 USD dest: $identity provides: ~FTuple: service: ~FunctionCachingService: caching_service: accumulation_channel: query_channel: ~CachingService: thing_nature: @FunctionCall key: ~KeyMultiple: identifier: fr child: ~KeySingle: fc """ """ A cache of CachingServices """
zuper-schemas
/zuper-schemas-3.0.3.tar.gz/zuper-schemas-3.0.3/src/zuper_schemas/indexing.py
indexing.py
from .utils import dataclass, Generic # @dataclass # class ConcreteResult: # no jobs in side # content: Any # # # @dataclass # class ConcreteCallable: # pass # # # @dataclass # class LocalPythonFunction(ConcreteCallable): # python_function: str # # # @dataclass # class FunctionCall: # callable: FunctionDefinition # parameters: Dict[str, Any] # # def __call__(self, **kwargs): # callable = ExpectFunctionDefinition(implementations={}, function_call=self) # return FunctionCall(callable=callable, parameters=kwargs) # # # # @dataclass # class ExpectFunctionDefinition(FunctionDefinition): # function_call: FunctionCall # # @dataclass # class Node: # pass # # @dataclass # class CurrentNode(Node): # pass # # @dataclass # class Context: # node: Node # time: float # # # def lookup_from_context(*, context: Context, identifier: str) -> Context: # pass # # # def F(f): # assert isinstance(f, Callable), f # f0 = FunctionDefinition(implementations={'python': LocalPythonFunction(python_function=f.__name__)}) # # def f2(*args, **kwargs): # if args: # msg = 'Cannot call this with positional arguments: %s %s' % (f, args) # raise TypeError(msg) # return FunctionCall(callable=f0, parameters=kwargs) # # return f2 # # # def zuper_link_resolve(*, context: Context, link: IPDELink) -> Any: # if '/' in link: # i = link.index('/') # first = link[:i] # rest = link[i + 1] # else: # first = link # rest = IPDELink('') # # context2 = F(lookup_from_context)(context=context, identifier=first) # # if rest: # return F(zuper_link_resolve)(context=context2, link=rest) # else: # return context2 # # # class DNS: # pass # # # def lookup(*, context: Context, first: Identifier, rest: str = None): # rest = rest or [] # dns_lookup = F(zuper_link_resolve)(context=context, link=IPDELink("@Instance/api/dns/lookup")) # resolved = dns_lookup(domain=first, record="txt") # return F(zuper_link_resolve)(context=resolved, link=rest) # # def zm_resolve_callable(link) -> Callable: # pass # # # class LookupInterface: # def __call__(self, domain: Domain, record: str) -> Optional[str]: # return '' # # def lookup(domain: Domain, origin: Node, time: Timespec ): # dns_lookup: LookupInterface = zm_resolve_callable("@Instance/api/dns/lookup") # # record = dns_lookup(domain=domain, record='txt') # # # # class Root: # ipde = 0 # @Executable: # # @Executable/Python: # # @Executable/Program: # docker: @DockerExecution # # # @Alert: # message: # location?: # # @Alert/Warning: # # @Alert/Error: # # # @JobResult: # job: @Job # warnings: @list(@Warning) # # console_output: @ConsoleOutput # # @ConsoleOutput: # stderr: @ConsoleOutputStream # stdout: @ConsoleOutputStream # # @ConsoleOutputStream: # previous?: @ConsoleOutputStream # line: @bytes # # # @JobResult/EvaluationFailure: # # # @JobResult/Success: # result: @ # # @JobResult/Failure: # errors: @list(@Errors) # # @JobResult/Failure/PartialFailure: # partial_result: @ ####### # #@TypedData: # size: @int # mime_type: @string # encoding: @string ########### # # @IPCLSegment: # # @IPCLSegment:Resolution: # # # @IPCLSegment:IPNSSegment: # ipns: @multihash # # @IPCL: # elements: @list(IPCLSegment) # # @Link: # # @Link/ZuperLink: # Cid: @cid # IsData: @bool # IsMeta: @bool # IsHistory: @bool # CurrentMetaSize: @int # HistoryMetaSize: @int # CurrentDataSize: @int # HistoryDataSize: @int # # @Link:LinkToIPCL: # ipcl: @IPCL # type: # # @Link:LinkToVersion: # entity: @Entity # value: @ # # @Link:LinkToJob: # job: @Job # expect-shape: @Shape # # @Link:LinkToJobResult: # job_result: @JobResult # expect-shape: @Shape # # @HashResult: # algorithm: @string # results: @bytes # # @AES_Encrypted: # payload: @TypedData # with mime=der # key-hash: @HashResult # # @SecretSharedKey: # key-hash: @HashResult # plain: @bytes # # @EncryptedFor: # dest: @PublicKey # payload: @bytes # # @PublicKey: # content: @TypedData # private?: @PrivateKey # # @PrivateKey: # content: @TypedData # # @SignedEnvelope: # data: @ # signature: @Signature # # @Signature: # key: @PublicKey # result: @bytes # # # @ClockReference: # # # # # published at public key # @ArbiterInfo: # keys: @dict(QueueInfo) # # @QueueInfo: # last: @VersionInfo # link to last version # queues: @list(Queue) # # @Queue:Pubsub: # topic: @string # # @Queue:Websocket: # url: @url #
zuper-schemas
/zuper-schemas-3.0.3.tar.gz/zuper-schemas-3.0.3/src/zuper_schemas/core.py
core.py
from typing import ClassVar, Optional, Any, List, Dict, Union from .utils import dataclass @dataclass class JSONSchema: _dollar_schema: ClassVar[str] = "http://json-schema.org/schema#" title: Optional[str] description: Optional[str] default: Optional[Any] examples: List[Any] enum: Optional[List] const: Optional[Any] definitions: Optional[Dict[str, 'JSONSchema']] @dataclass class JSONSchemaInt(JSONSchema): _type: ClassVar[str] = "int" multipleOf: int @dataclass class JSONSchemaBool(JSONSchema): _type: ClassVar[str] = "boolean" @dataclass class JSONSchemaNull(JSONSchema): _type: ClassVar[str] = "null" @dataclass class JSONSchemaNumber(JSONSchema): _type: ClassVar[str] = "number" multipleOf: float minimum: Optional[float] maximum: Optional[float] exclusiveMinimum: Optional[bool] exclusiveMaximum: Optional[bool] pattern = str @dataclass class JSONSchemaArray(JSONSchema): _type: ClassVar[str] = "array" items: Optional[Union[JSONSchema, List[JSONSchema]]] contains: Optional[JSONSchema] additionalItems: Optional[bool] minItems: Optional[int] maxItems: Optional[int] uniqueItems: Optional[bool] @dataclass class JSONSchemaString(JSONSchema): _type: ClassVar[str] = "string" pattern: Optional[pattern] maxLength: Optional[int] minLength: Optional[int] format: Optional[str] @dataclass class JSONSchemaObject(JSONSchema): _type: ClassVar[str] = "object" required: List[str] properties: Dict[str, JSONSchema] propertyNames: Optional[JSONSchemaString] additionalProperties: Optional[Union[bool, JSONSchema]] # XXX minProperties: Optional[int] maxProperties: Optional[int] dependencies: Optional[Dict[str, List[str]]] patternProperties: Optional[Dict[pattern, JSONSchema]] @dataclass class JSONSchemaAnyOf(JSONSchema): anyOf: List[JSONSchema] @dataclass class JSONSchemaAllOf(JSONSchema): allOf: List[JSONSchema] @dataclass class JSONSchemaOneOf(JSONSchema): oneOf: List[JSONSchema] @dataclass class JSONSchemaNot(JSONSchema): _not: List[JSONSchema] @dataclass class JSONSchemaRef(JSONSchema): _dollar_ref: str
zuper-schemas
/zuper-schemas-3.0.3.tar.gz/zuper-schemas-3.0.3/src/zuper_schemas/json_schema.py
json_schema.py
import typing from dataclasses import dataclass from typing import Optional, Any, List, Union from zuper_json.zeneric2 import resolve_types from .crypto import PublicKey, Signed from .utils import Generic @dataclass class SecurityModel: # guid: Any owner: PublicKey writer: PublicKey arbiter: PublicKey X = typing.TypeVar('X') M = typing.TypeVar('M') N = typing.TypeVar('N') Y = typing.TypeVar('Y') W = typing.TypeVar('W') Z = typing.TypeVar('Z') @dataclass class Entity(Generic[X]): guid: str security_model: SecurityModel forked: 'Optional[Entity[X]]' = None parent: 'Optional[Entity[Any]]' = None resolve_types(Entity) # # @dataclass # class User: # name: str # born: int # # # class Y(Entity[User]): # @classmethod # def get_examples(cls, seed=None): # pks = PublicKey.get_examples(seed=seed) # # while True: # _, pk1 = pks.__next__() # _, pk2 = pks.__next__() # # security_model = SecurityModel(owner=pk1, arbiter=pk2) # guid = "guid" + str(random.randint(100, 1000)) # data0 = User(name='John', born=1990) # e = Y(guid=guid, # data0=data0, # security_model=security_model) # yield guid, e # setattr(X, 'get_examples', get_examples) # remember_created_class(Y) @dataclass class EntityVersion(Generic[M]): entity: Entity[M] value: M previous: 'Optional[EntityVersion[M]]' = None # resolve_types(EntityVersion, locals()) # contains the chain of operations @dataclass class EntityOperationSetKey: key: str value: Any EntityOperation = Union[EntityOperationSetKey] def apply_operation_inplace(value, operation: EntityOperation): if isinstance(operation, EntityOperationSetKey): setattr(value, operation.key, operation.value) else: raise NotImplementedError(operation) def apply_operation(value: Any, operation: EntityOperation) -> Any: import copy if isinstance(operation, EntityOperationSetKey): value2 = copy.deepcopy(value) setattr(value2, operation.key, operation.value) return value2 else: raise NotImplementedError(operation) @dataclass class VersionChain(Generic[N]): operations: List[EntityOperation] version: EntityVersion[N] previous: 'Optional[VersionChain[N]]' = None @dataclass class EntityUpdateProposal(Generic[Y]): base: EntityVersion[Y] operations: List[EntityOperation] # consistent: bool depends: 'Optional[EntityUpdateProposal[Y]]' = None @dataclass class VersionChainWithAuthors(Generic[Z]): version: VersionChain[Z] signed_proposals: List[Signed[EntityUpdateProposal[Z]]] previous: 'Optional[VersionChainWithAuthors[Z]]' = None @dataclass class EntityState(Generic[W]): data: W v: EntityVersion[W] vc: VersionChain[W] vca: VersionChainWithAuthors[W] # # @dataclass # class Rejection: # operation: EntityUpdateProposal # conflicts: Optional[EntityUpdateProposal] # # # @dataclass # class EntityMerge: # entity: Entity # previous: Optional['EntityMerge'] # accepted: List[EntityUpdateProposal] # rejected: List[Rejection] # # @EntityOperation:AddOwner: # owner: @PublicKey # # @EntityOperation:RemoveOwner: # owner: @PublicKey # # @EntityOperation:AddArbiter: # owner: @PublicKey # # @EntityOperation:RemoveArbiter: # owner: @PublicKey # # @EntityOperation:AddWriter: # owner: @PublicKey # # @EntityOperation:RemoveWriter: # owner: @PublicKey # # @EntityOperation:AddReader: # owner: @PublicKey # # @EntityOperation:RemoveReader: # owner: @PublicKey
zuper-schemas
/zuper-schemas-3.0.3.tar.gz/zuper-schemas-3.0.3/src/zuper_schemas/chain.py
chain.py
from abc import abstractmethod, ABCMeta from typing import Generic, TypeVar, Any, Dict, Callable, NewType, List from mypy_extensions import NamedArg from .chain import Entity # from .2 import Computes, X, ComputeContext, ComputableDict from .identity import Identity from .meta import Nature from .utils import dataclass, Identifier X = TypeVar('X') Y = TypeVar('Y') T = TypeVar('T') ParameterTypes = Dict[Identifier, Nature] @dataclass class SideInfo: assumptions: Dict depth: int @dataclass class ComputationResult(Generic[T]): value: T side_info: SideInfo class ComputeContext: def resolve_abstract_function(self, abstract_function) -> ComputationResult[Callable]: pass def with_placeholders(self): pass class Computes(Generic[T], metaclass=ABCMeta): @abstractmethod def compute(self, context: ComputeContext) -> ComputationResult[T]: pass def dictmap(f, d): return {k: f(v) for k, v in d.items()} def dictval(f, d): return [f(v) for v in d.values()] def side_info_merge(sides: List[SideInfo]) -> SideInfo: pass CD = Dict[Identifier, Any] @dataclass class ComputableDict(Computes[CD]): data: Dict[Identifier, Computes[Any]] def compute(self, context: ComputeContext) -> ComputationResult[CD]: res = dictmap(lambda _: _.compute(context), self.data) values = dictmap(lambda _: _.value, res) side = dictval(lambda _: _.side_info, res) return ComputationResult[CD](value=values, side_info=side_info_merge(side)) @dataclass class FunctionSignature: parameters: ParameterTypes return_type: Nature volatile: bool side_effects: bool @dataclass class AbstractFunction: signature: FunctionSignature owner: Identity guid: str # whatever the owner decides it is appropriate @dataclass class ComputingAssumptions: semantics: str @dataclass class EntityStateAssumptions: entity_state: Dict[Entity, Any] @dataclass class Assumptions: entity_state_assumptions: EntityStateAssumptions computing_assumptions: ComputingAssumptions ParametersToUse = NewType('ParametersToUse', Dict[Identifier, Any]) class AbstractFunctionCall(Computes[X]): abstract_function: AbstractFunction parameters: ComputableDict assume: ComputingAssumptions def compute(self, context: ComputeContext) -> ComputationResult[X]: crf: ComputationResult[Callable[..., X]] = context.resolve_abstract_function(self.abstract_function) crp: ComputationResult[CD] = self.parameters.compute(context) f = crf.value p: Dict[Identifier, Any] = crp.value y = f(**p) cr = side_info_merge([crf.side_info, crp.side_info]) return ComputationResult(value=y, side_info=cr) @dataclass class FunctionResult: fc: AbstractFunctionCall data: object assume: ComputingAssumptions from .utils import dataclass, Identifier @dataclass class Constant(Computes[T]): value: T def compute(self, context: ComputeContext) -> ComputationResult[T]: side_info = SideInfo({}, 0) return ComputationResult(value=self.value, side_info=side_info) @dataclass class IfThenElse(Computes[X]): """ Constraints: IfThenElse(true, a, b) = a IfThenElse(false, a, b) = a """ expr: Computes[bool] a: Computes[X] b: Computes[X] def compute(self, context: ComputeContext) -> ComputationResult[X]: eval_expr = self.expr.compute(context=context) if eval_expr.value: eb = self.a.compute(context=context) else: eb = self.b.compute(context=context) return ComputationResult(eb.value, side_info_merge([eb.side_info, eval_expr.side_info])) @dataclass class SelectAttribute(Computes[X], Generic[X, Y]): attribute: Identifier what: Computes[Y] def compute(self, context: ComputeContext) -> ComputationResult[X]: cr = self.what.compute(context) value = getattr(cr.value, self.attribute) return ComputationResult(value, cr.side_info) @dataclass class SelectEntry(Computes[X]): key: Identifier what: Computes[Dict[Identifier, X]] def compute(self, context: ComputeContext) -> ComputationResult[X]: cr = self.what.compute(context) value = cr.value[self.key] return ComputationResult(value, cr.side_info) K = TypeVar('K') V = TypeVar('V') W = TypeVar('W') # f = Callable[[NamedArg(V, name='element')], W] @dataclass class DictMap(Computes[Dict[K, W]], Generic[K, V, W]): """ Semantics: E{ DictMap(f, x) } = E{ {k: f(v) for k, f in x.items()} } For all f, x: GetAttribute(att, DictMap(f, x)) = f(GetAttribute(att, x)) """ f: Computes[Callable[[V], W]] data: Dict[K, Computes[V]] def compute(self, context) -> ComputationResult[Dict[K, W]]: fres = f.compute(context) def apply(v): fres res = dictmap(lambda _: _.compute(context), self.data) values = dictmap(lambda _: _.value, res) side = dictval(lambda _: _.side_info, res) return ComputationResult[CD](value=values, side_info=side_info_merge(side)) return {k: self.f(v.compute(context)) for k, v in self.data.items()} placeholder_guid = NewType('placeholder_guid', str) @dataclass class Placeholder(Computes[X]): name: Identifier guid: placeholder_guid def compute(self, context) -> X: return context.get_guid(self.guid) # TemplateParameters = NewType('TemplateParameters', Dict[Identifier, TemplatePlaceholder]) class SpecializeTemplate(Computes[X]): """ # Sub(Template(res, param_spec), parameters) # = # Template(res / parameters, param_spec - parameters) # # ## Simplification # # Template(x, {}) = x """ x: type pattern: ComputableDict parameters: Dict[Placeholder, Computes[Any]] def compute(self, context) -> X: context.add(self.parameters) atts = self.pattern.compute(context) Xi = type(self).__args__[0] return Xi(**atts) # #
zuper-schemas
/zuper-schemas-3.0.3.tar.gz/zuper-schemas-3.0.3/src/zuper_schemas/computation.py
computation.py
from typing import Any, cast, ClassVar, Dict, List, Set, Tuple, Type, TypeVar from zuper_typing.aliases import TypeLike from .annotations_tricks import ( get_Dict_args, get_Dict_name_K_V, get_FixedTupleLike_args, get_List_arg, get_Set_arg, get_Set_name_V, is_Dict, is_FixedTupleLike, is_List, is_Set, name_for_type_like, ) _V = TypeVar("_V") _K = TypeVar("_K") _X = TypeVar("_X") _Y = TypeVar("_Y") _Z = TypeVar("_Z") class CustomSet(set): __set_type__: ClassVar[type] def __hash__(self) -> Any: try: return self._cached_hash except AttributeError: try: h = self._cached_hash = hash(tuple(sorted(self))) except TypeError: # pragma: no cover h = self._cached_hash = hash(tuple(self)) return h class CustomList(list): __list_type__: ClassVar[type] def __hash__(self) -> Any: # pragma: no cover try: return self._cached_hash except AttributeError: # pragma: no cover h = self._cached_hash = hash(tuple(self)) return h class CustomTuple(tuple): __tuple_types__: ClassVar[Tuple[type, ...]] def __hash__(self) -> Any: # pragma: no cover try: return self._cached_hash except AttributeError: # pragma: no cover h = self._cached_hash = hash(tuple(self)) return h class CustomDict(dict): __dict_type__: ClassVar[Tuple[type, type]] def __hash__(self) -> Any: try: return self._cached_hash except AttributeError: try: h = self._cached_hash = hash(tuple(sorted(self.items()))) except TypeError: # pragma: no cover h = self._cached_hash = hash(tuple(self.items())) return h def copy(self: _X) -> _X: return type(self)(self) def get_CustomSet_arg(x: Type[CustomSet]) -> TypeLike: assert is_CustomSet(x), x return x.__set_type__ def get_CustomList_arg(x: Type[CustomList]) -> TypeLike: assert is_CustomList(x), x return x.__list_type__ def get_CustomDict_args(x: Type[CustomDict]) -> Tuple[TypeLike, TypeLike]: assert is_CustomDict(x), x return x.__dict_type__ def get_CustomTuple_args(x: Type[CustomTuple]) -> Tuple[TypeLike, ...]: assert is_CustomTuple(x), x return x.__tuple_types__ def is_CustomSet(x: TypeLike) -> bool: return isinstance(x, type) and issubclass(x, CustomSet) def is_CustomList(x: TypeLike) -> bool: return isinstance(x, type) and issubclass(x, CustomList) def is_CustomDict(x: TypeLike) -> bool: return isinstance(x, type) and issubclass(x, CustomDict) def is_CustomTuple(x: TypeLike) -> bool: return isinstance(x, type) and issubclass(x, CustomTuple) def is_SetLike(x: TypeLike) -> bool: return (x is set) or is_Set(x) or is_CustomSet(x) def is_ListLike(x: TypeLike) -> bool: return (x is list) or is_List(x) or is_CustomList(x) def is_DictLike(x: TypeLike) -> bool: return (x is dict) or is_Dict(x) or is_CustomDict(x) def is_ListLike_canonical(x: Type[List]) -> bool: return is_CustomList(x) def is_DictLike_canonical(x: Type[Dict]) -> bool: return is_CustomDict(x) def is_SetLike_canonical(x: Type[Set]) -> bool: return is_CustomSet(x) def get_SetLike_arg(x: Type[Set[_V]]) -> Type[_V]: if x is set: return Any if is_Set(x): return get_Set_arg(x) if is_CustomSet(x): x = cast(Type[CustomSet], x) return get_CustomSet_arg(x) assert False, x def get_ListLike_arg(x: Type[List[_V]]) -> Type[_V]: if x is list: return Any if is_List(x): return get_List_arg(x) if is_CustomList(x): # noinspection PyTypeChecker return get_CustomList_arg(x) assert False, x def get_DictLike_args(x: Type[Dict[_K, _V]]) -> Tuple[Type[_K], Type[_V]]: assert is_DictLike(x), x if is_Dict(x): return get_Dict_args(x) elif is_CustomDict(x): x = cast(Type[CustomDict], x) return get_CustomDict_args(x) elif x is dict: return Any, Any else: assert False, x def get_DictLike_name(T: Type[Dict]) -> str: assert is_DictLike(T) K, V = get_DictLike_args(T) return get_Dict_name_K_V(K, V) def get_ListLike_name(x: Type[List]) -> str: V = get_ListLike_arg(x) return "List[%s]" % name_for_type_like(V) def get_SetLike_name(x: Type[Set]) -> str: v = get_SetLike_arg(x) return "Set[%s]" % name_for_type_like(v) Q_ = TypeVar("Q_") K_ = TypeVar("K_") V_ = TypeVar("V_") class Caches: use_cache = True make_set_cache: Dict[Type[Q_], Type[CustomSet]] = {} make_list_cache: Dict[Type[Q_], Type[CustomList]] = {} make_dict_cache: Dict[Tuple[Type[K_], Type[V_]], Type[CustomDict]] = {} make_tuple_cache: Dict[Tuple[TypeLike, ...], Type[CustomTuple]] = {} def assert_good_typelike(x: TypeLike) -> None: if isinstance(x, type): return # if is_dataclass(type(x)): # n = type(x).__name__ # if n in ["Constant"]: # raise AssertionError(x) def make_list(V_: Type[_X]) -> Type[List[Type[_X]]]: if Caches.use_cache: if V_ in Caches.make_list_cache: return Caches.make_list_cache[V_] assert_good_typelike(V_) class MyType(type): def __eq__(self, other) -> bool: V2 = getattr(self, "__list_type__") if is_List(other): return V2 == get_List_arg(other) res2 = ( isinstance(other, type) and issubclass(other, CustomList) and other.__list_type__ == V2 ) return res2 def __hash__(cls) -> Any: # pragma: no cover return 1 # XXX # logger.debug(f'here ___eq__ {self} {other} {issubclass(other, CustomList)} = {res}') def copy(self: _X) -> _X: return type(self)(self) attrs = {"__list_type__": V_, "copy": copy} # name = get_List_name(V) name = "List[%s]" % name_for_type_like(V_) res = MyType(name, (CustomList,), attrs) setattr(res, "EMPTY", res([])) Caches.make_list_cache[V_] = res # noinspection PyTypeChecker return res def make_CustomTuple(Vs: Tuple[TypeLike, ...]) -> Type[Tuple]: if Caches.use_cache: if Vs in Caches.make_tuple_cache: return Caches.make_tuple_cache[Vs] for _ in Vs: assert_good_typelike(_) ATT_TUPLE_TYPES = "__tuple_types__" class MyTupleType(type): def __eq__(self, other) -> bool: V2 = getattr(self, ATT_TUPLE_TYPES) if is_FixedTupleLike(other): return V2 == get_FixedTupleLike_args(other) res2 = ( isinstance(other, type) and issubclass(other, CustomTuple) and getattr(other, ATT_TUPLE_TYPES) == V2 ) return res2 def __hash__(cls) -> Any: # pragma: no cover return 1 # XXX # logger.debug(f'here ___eq__ {self} {other} {issubclass(other, CustomList)} = {res}') def copy(self: _X) -> _X: return type(self)(self) attrs = {ATT_TUPLE_TYPES: Vs, "copy": copy} # name = get_List_name(V) s = ",".join(name_for_type_like(_) for _ in Vs) name = "Tuple[%s]" % s res = MyTupleType(name, (CustomTuple,), attrs) # setattr(res, "EMPTY", res()) Caches.make_tuple_cache[V_] = res # noinspection PyTypeChecker return res def make_set(V: TypeLike) -> Type[CustomSet]: if Caches.use_cache: if V in Caches.make_set_cache: return Caches.make_set_cache[V] assert_good_typelike(V) class MyType(type): def __eq__(self, other) -> bool: V2 = getattr(self, "__set_type__") if is_Set(other): return V2 == get_Set_arg(other) res2 = ( isinstance(other, type) and issubclass(other, CustomSet) and other.__set_type__ == V2 ) return res2 def __hash__(cls) -> Any: # pragma: no cover return 1 # XXX def copy(self: _X) -> _X: return type(self)(self) attrs = {"__set_type__": V, "copy": copy} name = get_Set_name_V(V) res = MyType(name, (CustomSet,), attrs) setattr(res, "EMPTY", res([])) Caches.make_set_cache[V] = res # noinspection PyTypeChecker return res # from . import logger # def make_dict(K: Type[X], V: Type[Y]) -> Type[Dict[Type[X], Type[Y]]]: def make_dict(K: TypeLike, V: TypeLike) -> type: # Type[CustomDict]: key = (K, V) if Caches.use_cache: if key in Caches.make_dict_cache: return Caches.make_dict_cache[key] assert_good_typelike(K) assert_good_typelike(V) class MyType(type): def __eq__(self, other) -> bool: K2, V2 = getattr(self, "__dict_type__") if is_Dict(other): K1, V1 = get_Dict_args(other) return K2 == K1 and V2 == V1 res2 = ( isinstance(other, type) and issubclass(other, CustomDict) and other.__dict_type__ == (K2, V2) ) return res2 def __hash__(cls) -> Any: # pragma: no cover return 1 # XXX if isinstance(V, str): # pragma: no cover msg = f"Trying to make dict with K = {K!r} and V = {V!r}; I need types, not strings." raise ValueError(msg) # warnings.warn('Creating dict', stacklevel=2) attrs = {"__dict_type__": (K, V)} name = get_Dict_name_K_V(K, V) res = MyType(name, (CustomDict,), attrs) setattr(res, "EMPTY", res({})) Caches.make_dict_cache[key] = res # noinspection PyUnresolvedReferences import zuper_typing.my_dict zuper_typing.my_dict.__dict__[res.__name__] = res # noinspection PyTypeChecker return res
zuper-typing-z5
/zuper-typing-z5-5.3.0.tar.gz/zuper-typing-z5-5.3.0/src/zuper_typing/my_dict.py
my_dict.py
from dataclasses import dataclass, field, is_dataclass from decimal import Decimal from typing import Any, cast, Dict, Iterable, List, Optional, Set, Tuple, Type, Sequence from zuper_commons.text import indent from zuper_typing.aliases import TypeLike from zuper_typing.literal import get_Literal_args, is_Literal from zuper_typing.type_algebra import Matches from zuper_typing.uninhabited import is_Uninhabited from .annotations_tricks import ( get_ForwardRef_arg, get_Iterable_arg, get_NewType_arg, get_Optional_arg, get_Sequence_arg, get_tuple_types, get_TypeVar_name, get_Union_args, is_Any, is_Callable, is_ForwardRef, is_Iterable, is_List, is_Optional, is_Sequence, is_Tuple, is_TypeVar, is_Union, is_ClassVar, ) from .constants import ANNOTATIONS_ATT, BINDINGS_ATT from .my_dict import ( get_DictLike_args, get_ListLike_arg, get_SetLike_arg, is_DictLike, is_ListLike, is_SetLike, ) from .my_intersection import is_Intersection, get_Intersection_args @dataclass class CanBeUsed: result: bool why: str M: Matches matches: Optional[Dict[str, type]] = None reasons: "Dict[str, CanBeUsed]" = field(default_factory=dict) def __post_init__(self): assert isinstance(self.M, Matches), self self.matches = self.M.get_matches() def __bool__(self): return self.result verbose = False can_be_used_cache = {} def can_be_used_as2( T1: TypeLike, T2: TypeLike, matches: Optional[Matches] = None, assumptions0: Tuple[Tuple[Any, Any], ...] = (), ) -> CanBeUsed: if matches is None: matches = Matches() if is_Any(T2): return CanBeUsed(True, "Any", matches) if is_Any(T1): return CanBeUsed(True, "Any", matches) if is_Uninhabited(T1): return CanBeUsed(True, "Empty", matches) assert isinstance(matches, Matches), matches if (T1, T2) in assumptions0: return CanBeUsed(True, "By assumption", matches) if (T1 is T2) or (T1 == T2): return CanBeUsed(True, "equal", matches) if is_Any(T1) or is_Any(T2): return CanBeUsed(True, "Any ignores everything", matches) if T2 is object: return CanBeUsed(True, "object is the top", matches) # cop out for the easy cases if is_Literal(T1): v1 = get_Literal_args(T1) if is_Literal(T2): v2 = get_Literal_args(T2) included = all(any(x1 == x2 for x2 in v2) for x1 in v1) if included: return CanBeUsed(True, "included", matches) else: return CanBeUsed(False, "not included", matches) raise NotImplementedError((T1, T2)) assumptions = assumptions0 + ((T1, T2),) # logger.info(f'can_be_used_as\n {T1} {T2}\n {assumptions0}') if T1 is type(None): if is_Optional(T2): return CanBeUsed(True, "", matches) elif T2 is type(None): return CanBeUsed(True, "", matches) else: msg = f"Needs type(None), got {T2}" return CanBeUsed(False, msg, matches) if is_Union(T1): if is_Union(T2): if get_Union_args(T1) == get_Union_args(T2): return CanBeUsed(True, "same", matches) # can_be_used(Union[A,B], C) # == can_be_used(A,C) and can_be_used(B,C) for t in get_Union_args(T1): can = can_be_used_as2(t, T2, matches, assumptions) # logger.info(f'can_be_used_as t = {t} {T2}') if not can.result: msg = f"Cannot match {t}" return CanBeUsed(False, msg, matches) return CanBeUsed(True, "", matches) if is_Union(T2): reasons = [] for t in get_Union_args(T2): can = can_be_used_as2(T1, t, matches, assumptions) if can.result: return CanBeUsed(True, f"union match with {t} ", can.M) reasons.append(f"- {t}: {can.why}") msg = f"Cannot use {T1} as any of {T2}:\n" + "\n".join(reasons) return CanBeUsed(False, msg, matches) if is_TypeVar(T2): n2 = get_TypeVar_name(T2) if is_TypeVar(T1): n1 = get_TypeVar_name(T1) if n1 == n2: # TODO: intersection of bounds return CanBeUsed(True, "", matches) else: matches = matches.must_be_subtype_of(n1, T2) # raise NotImplementedError((T1, T2)) matches = matches.must_be_supertype_of(n2, T1) return CanBeUsed(True, "", matches) # # if T2.__name__ not in matches: # matches = dict(matches) # matches[T2.__name__] = T1 # return CanBeUsed(True, "", matches) # else: # prev = matches[T2.__name__] # if prev == T1: # return CanBeUsed(True, "", matches) # else: # raise NotImplementedError((T1, T2, matches)) if is_Intersection(T1): if is_Intersection(T2): if get_Intersection_args(T1) == get_Intersection_args(T2): return CanBeUsed(True, "same", matches) # Int[a, b] <= Int[C, D] # = Int[a, b] <= C Int[a, b] <= D for t2 in get_Intersection_args(T2): can = can_be_used_as2(T1, t2, matches, assumptions) # logger.info(f'can_be_used_as t = {t} {T2}') if not can.result: msg = f"Cannot match {t2}" return CanBeUsed(False, msg, matches) return CanBeUsed(True, "", matches) if is_Intersection(T2): # a <= Int[C, D] # = a <= C and a <= D reasons = [] for t2 in get_Intersection_args(T2): can = can_be_used_as2(T1, t2, matches, assumptions) if not can.result: return CanBeUsed(False, f"no match {T1} {t2} ", can.M) msg = f"Cannot use {T1} as any of {T2}:\n" + "\n".join(reasons) return CanBeUsed(False, msg, matches) if is_TypeVar(T1): n1 = get_TypeVar_name(T1) matches = matches.must_be_subtype_of(n1, T2) return CanBeUsed(True, "Any", matches) # TODO: not implemented if is_Optional(T1): t1 = get_Optional_arg(T1) if is_Optional(T2): t2 = get_Optional_arg(T2) return can_be_used_as2(t1, t2, matches, assumptions) if T2 is type(None): return CanBeUsed(True, "", matches) return can_be_used_as2(t1, T2, matches, assumptions) if is_Optional(T2): t2 = get_Optional_arg(T2) if is_Optional(T1): t1 = get_Optional_arg(T1) return can_be_used_as2(t1, t2, matches, assumptions) return can_be_used_as2(T1, t2, matches, assumptions) if is_DictLike(T2): if not is_DictLike(T1): msg = f"Expecting a dictionary, got {T1}" return CanBeUsed(False, msg, matches) else: K1, V1 = get_DictLike_args(T1) K2, V2 = get_DictLike_args(T2) rk = can_be_used_as2(K1, K2, matches, assumptions) if not rk: return CanBeUsed(False, f"keys {K1} {K2}: {rk}", matches) rv = can_be_used_as2(V1, V2, rk.M, assumptions) if not rv: return CanBeUsed(False, f"values {V1} {V2}: {rv}", matches) return CanBeUsed(True, f"ok: {rk} {rv}", rv.M) else: if is_DictLike(T1): msg = "A Dict needs a dictionary" return CanBeUsed(False, msg, matches) assert not is_Union(T2) if is_dataclass(T2): # try: # if issubclass(T1, T2): # return True, '' # except: # pass if ( hasattr(T1, "__name__") and T1.__name__.startswith("Loadable") and hasattr(T1, BINDINGS_ATT) ): T1 = list(getattr(T1, BINDINGS_ATT).values())[0] if not is_dataclass(T1): if verbose: msg = ( f"Expecting dataclass to match to {T2}, got something that is not a " f"dataclass: {T1}" ) msg += f" union: {is_Union(T1)}" else: msg = "not dataclass" return CanBeUsed(False, msg, matches) # h1 = get_type_hints(T1) # h2 = get_type_hints(T2) key = (T1.__module__, T1.__qualname__, T2.__module__, T2.__qualname__) if key in can_be_used_cache: return can_be_used_cache[key] h1 = getattr(T1, ANNOTATIONS_ATT, {}) h2 = getattr(T2, ANNOTATIONS_ATT, {}) for k, v2 in h2.items(): if not k in h1: if verbose: msg = ( f'Type {T2}\n requires field "{k}" \n of type {v2} \n but {T1} does ' f"" f"not have it. " ) else: msg = k res = CanBeUsed(False, msg, matches) can_be_used_cache[key] = res return res v1 = h1[k] # XXX if is_ClassVar(v1): continue can = can_be_used_as2(v1, v2, matches, assumptions) if not can.result: if verbose: msg = ( f'Type {T2}\n requires field "{k}"\n of type\n {v2} \n but' + f" {T1}\n has annotated it as\n {v1}\n which cannot be used. " ) msg += "\n\n" + f"assumption: {assumptions}" msg += "\n\n" + indent(can.why, "> ") else: msg = "" res = CanBeUsed(False, msg, matches) can_be_used_cache[key] = res return res res = CanBeUsed(True, "dataclass", matches) can_be_used_cache[key] = res return res if T1 is int: if T2 is int: return CanBeUsed(True, "", matches) else: msg = "Need int" return CanBeUsed(False, msg, matches) if T1 is str: assert T2 is not str msg = "A string can only be used a string" return CanBeUsed(False, msg, matches) if is_Tuple(T1): assert not is_Union(T2) if not is_Tuple(T2): msg = "A tuple can only be used as a tuple" return CanBeUsed(False, msg, matches) else: T1 = cast(Type[Tuple], T1) T2 = cast(Type[Tuple], T2) for t1, t2 in zip(get_tuple_types(T1), get_tuple_types(T2)): can = can_be_used_as2(t1, t2, matches, assumptions) if not can.result: return CanBeUsed(False, f"{t1} {T2}", matches) matches = can.M return CanBeUsed(True, "", matches) if is_Tuple(T2): assert not is_Tuple(T1) return CanBeUsed(False, "", matches) if is_Any(T1): assert not is_Union(T2) if not is_Any(T2): msg = "Any is the top" return CanBeUsed(False, msg, matches) if is_ListLike(T2): if not is_ListLike(T1): msg = "A List can only be used as a List" return CanBeUsed(False, msg, matches) T1 = cast(Type[List], T1) T2 = cast(Type[List], T2) t1 = get_ListLike_arg(T1) t2 = get_ListLike_arg(T2) # print(f'matching List with {t1} {t2}') can = can_be_used_as2(t1, t2, matches, assumptions) if not can.result: return CanBeUsed(False, f"{t1} {T2}", matches) return CanBeUsed(True, "", can.M) if is_Callable(T2): if not is_Callable(T1): return CanBeUsed(False, "not callable", matches) raise NotImplementedError((T1, T2)) if is_ForwardRef(T1): n1 = get_ForwardRef_arg(T1) if is_ForwardRef(T2): n2 = get_ForwardRef_arg(T2) if n1 == n2: return CanBeUsed(True, "", matches) else: return CanBeUsed(False, "different name", matches) else: return CanBeUsed(False, "not fw ref", matches) if is_ForwardRef(T2): n2 = get_ForwardRef_arg(T2) if hasattr(T1, "__name__"): if T1.__name__ == n2: return CanBeUsed(True, "", matches) else: return CanBeUsed(False, "different name", matches) if is_Iterable(T2): T2 = cast(Type[Iterable], T2) t2 = get_Iterable_arg(T2) if is_Iterable(T1): T1 = cast(Type[Iterable], T1) t1 = get_Iterable_arg(T1) return can_be_used_as2(t1, t2, matches) if is_SetLike(T1): T1 = cast(Type[Set], T1) t1 = get_SetLike_arg(T1) return can_be_used_as2(t1, t2, matches) if is_ListLike(T1): T1 = cast(Type[List], T1) t1 = get_ListLike_arg(T1) return can_be_used_as2(t1, t2, matches) if is_DictLike(T1): T1 = cast(Type[Dict], T1) K, V = get_DictLike_args(T1) t1 = Tuple[K, V] return can_be_used_as2(t1, t2, matches) return CanBeUsed(False, "expect iterable", matches) if is_SetLike(T2): if not is_SetLike(T1): msg = "A Set can only be used as a Set" return CanBeUsed(False, msg, matches) t1 = get_SetLike_arg(T1) t2 = get_SetLike_arg(T2) # print(f'matching List with {t1} {t2}') can = can_be_used_as2(t1, t2, matches, assumptions) if not can.result: return CanBeUsed( False, f"Set argument fails", matches, reasons={"set_arg": can} ) return CanBeUsed(True, "", can.M) if is_Sequence(T1): T1 = cast(Type[Sequence], T1) t1 = get_Sequence_arg(T1) if is_ListLike(T2): T2 = cast(Type[List], T2) t2 = get_ListLike_arg(T2) can = can_be_used_as2(t1, t2, matches, assumptions) if not can.result: return CanBeUsed(False, f"{t1} {T2}", matches) return CanBeUsed(True, "", can.M) msg = f"Needs a Sequence[{t1}], got {T2}" return CanBeUsed(False, msg, matches) if isinstance(T1, type) and isinstance(T2, type): # NOTE: issubclass(A, B) == type(T2).__subclasscheck__(T2, T1) if type.__subclasscheck__(T2, T1): return CanBeUsed(True, f"type.__subclasscheck__ {T1} {T2}", matches) else: msg = f"Type {T1} ({id(T1)}) \n is not a subclass of {T2} ({id(T2)}) " msg += f"\n is : {T1 is T2}" return CanBeUsed(False, msg, matches) if is_List(T1): msg = f"Needs a List, got {T2}" return CanBeUsed(False, msg, matches) if T2 is type(None): msg = f"Needs type(None), got {T1}" return CanBeUsed(False, msg, matches) trivial = (int, str, bool, Decimal, datetime, float) if T2 in trivial: if T1 in trivial: raise NotImplementedError((T1, T2)) return CanBeUsed(False, "", matches) from .annotations_tricks import is_NewType if is_NewType(T1): n1 = get_NewType_arg(T1) if is_NewType(T2): n2 = get_NewType_arg(T2) if n1 == n2: return CanBeUsed(True, "", matches) else: raise NotImplementedError((T1, T2)) else: raise NotImplementedError((T1, T2)) # msg = f"{T1} ? {T2}" # pragma: no cover raise NotImplementedError((T1, T2)) from datetime import datetime
zuper-typing-z5
/zuper-typing-z5-5.3.0.tar.gz/zuper-typing-z5-5.3.0/src/zuper_typing/subcheck.py
subcheck.py
from dataclasses import dataclass, fields, is_dataclass from datetime import datetime from decimal import Decimal from typing import cast, Dict, Iterator, List, Optional, Set, Tuple, Type, Union from .aliases import TypeLike from .annotations_tricks import ( get_ClassVar_arg, get_fields_including_static, get_FixedTupleLike_args, get_NewType_arg, get_NewType_name, get_Optional_arg, get_Type_arg, get_TypeVar_name, get_Union_args, get_VarTuple_arg, is_Any, is_ClassVar, is_FixedTupleLike, is_NewType, is_Optional, is_Type, is_TypeLike, is_TypeVar, is_Union, is_VarTuple, ) from .exceptions import ZValueError from .my_dict import ( get_DictLike_args, get_ListLike_arg, get_SetLike_arg, is_DictLike, is_ListLike, is_SetLike, ) from .my_intersection import get_Intersection_args, is_Intersection from .uninhabited import is_Uninhabited @dataclass class Patch: __print_order = ["prefix_str", "value1", "value2"] prefix: Tuple[Union[str, int], ...] value1: object value2: Optional[object] prefix_str: Optional[str] = None def __post_init__(self): self.prefix_str = "/".join(map(str, self.prefix)) def assert_equivalent_objects(ob1: object, ob2: object): if is_TypeLike(ob1): ob1 = cast(TypeLike, ob1) ob2 = cast(TypeLike, ob2) assert_equivalent_types(ob1, ob2) else: patches = get_patches(ob1, ob2) if patches: msg = "The objects are not equivalent" raise ZValueError(msg, ob1=ob1, ob2=ob2, patches=patches) def get_patches(a: object, b: object) -> List[Patch]: patches = list(patch(a, b, ())) return patches def get_fields_values(x: dataclass) -> Dict[str, object]: res = {} for f in fields(type(x)): k = f.name v0 = getattr(x, k) res[k] = v0 return res def is_dataclass_instance(x: object) -> bool: return not isinstance(x, type) and is_dataclass(x) import numpy as np def patch(o1, o2, prefix: Tuple[Union[str, int], ...]) -> Iterator[Patch]: if isinstance(o1, np.ndarray): if np.all(o1 == o2): return else: yield Patch(prefix, o1, o2) if o1 == o2: return if is_TypeLike(o1) and is_TypeLike(o2): try: assert_equivalent_types(o1, o2) except NotEquivalentException: yield Patch(prefix, o1, o2) elif is_dataclass_instance(o1) and is_dataclass_instance(o2): fields1 = get_fields_values(o1) fields2 = get_fields_values(o2) if list(fields1) != list(fields2): yield Patch(prefix, o1, o2) for k in fields1: v1 = fields1[k] v2 = fields2[k] yield from patch(v1, v2, prefix + (k,)) elif isinstance(o1, dict) and isinstance(o2, dict): for k, v in o1.items(): if not k in o2: yield Patch(prefix + (k,), v, None) else: yield from patch(v, o2[k], prefix + (k,)) elif isinstance(o1, list) and isinstance(o2, list): for i, v in enumerate(o1): if i >= len(o2) - 1: yield Patch(prefix + (i,), v, None) else: yield from patch(o1[i], o2[i], prefix + (i,)) else: if o1 != o2: yield Patch(prefix, o1, o2) class NotEquivalentException(ZValueError): pass def assert_equivalent_types(T1: TypeLike, T2: TypeLike, assume_yes: set = None): if assume_yes is None: assume_yes = set() # debug(f'equivalent', T1=T1, T2=T2) key = (id(T1), id(T2)) if key in assume_yes: return assume_yes = set(assume_yes) assume_yes.add(key) try: # print(f'assert_equivalent_types({T1},{T2})') if T1 is T2: # logger.debug('same by equality') return # if hasattr(T1, '__dict__'): # debug('comparing', # T1=f'{T1!r}', # T2=f'{T2!r}', # T1_dict=T1.__dict__, T2_dict=T2.__dict__) # for these builtin we cannot set/get the attrs # if not isinstance(T1, typing.TypeVar) and (not isinstance(T1, ForwardRef)) and not is_Dict(T1): if is_dataclass(T1): if not is_dataclass(T2): raise NotEquivalentException(T1=T1, T2=T2) for k in ["__name__", "__module__", "__doc__"]: msg = f"Difference for {k} of {T1} ({type(T1)}) and {T2} ({type(T2)}" v1 = getattr(T1, k, ()) v2 = getattr(T2, k, ()) if v1 != v2: raise NotEquivalentException(msg, v1=v1, v2=v2) # assert_equal(, , msg=msg) fields1 = get_fields_including_static(T1) fields2 = get_fields_including_static(T2) if list(fields1) != list(fields2): msg = f"Different fields" raise NotEquivalentException(msg, fields1=fields1, fields2=fields2) ann1 = getattr(T1, "__annotations__", {}) ann2 = getattr(T2, "__annotations__", {}) # redundant with above # if list(ann1) != list(ann2): # msg = f'Different fields: {list(fields1)} != {list(fields2)}' # raise NotEquivalent(msg) for k in fields1: t1 = fields1[k].type t2 = fields2[k].type # debug( # f"checking the fields {k}", # t1=f"{t1!r}", # t2=f"{t2!r}", # t1_ann=f"{T1.__annotations__[k]!r}", # t2_ann=f"{T2.__annotations__[k]!r}", # ) try: assert_equivalent_types(t1, t2, assume_yes=assume_yes) except NotEquivalentException as e: msg = f"Could not establish the annotation {k!r} to be equivalent" raise NotEquivalentException( msg, t1=t1, t2=t2, t1_ann=T1.__annotations__[k], t2_ann=T2.__annotations__[k], t1_att=getattr(T1, k, "no attribute"), t2_att=getattr(T2, k, "no attribute"), ) from e d1 = fields1[k].default d2 = fields2[k].default try: assert_equivalent_objects(d1, d2) except ZValueError as e: raise NotEquivalentException(d1=d1, d2=d2) from e # if d1 != d2: # msg = f"Defaults for {k!r} are different." # raise NotEquivalentException(msg, d1=d1, d2=d2) # # d1 = fields1[k].default_factory # d2 = fields2[k].default # if d1 != d2: # msg = f"Defaults for {k!r} are different." # raise NotEquivalentException(msg, d1=d1, d2=d2) for k in ann1: t1 = ann1[k] t2 = ann2[k] try: assert_equivalent_types(t1, t2, assume_yes=assume_yes) except NotEquivalentException as e: msg = f"Could not establish the annotation {k!r} to be equivalent" raise NotEquivalentException( msg, t1=t1, t2=t2, t1_ann=T1.__annotations__[k], t2_ann=T2.__annotations__[k], t1_att=getattr(T1, k, "no attribute"), t2_att=getattr(T2, k, "no attribute"), ) from e # for k in ['__annotations__']: # assert_equivalent_types(getattr(T1, k, None), getattr(T2, k, None)) # if False: # if hasattr(T1, 'mro'): # if len(T1.mro()) != len(T2.mro()): # msg = pretty_dict('Different mros', dict(T1=T1.mro(), T2=T2.mro())) # raise AssertionError(msg) # # for m1, m2 in zip(T1.mro(), T2.mro()): # if m1 is T1 or m2 is T2: continue # assert_equivalent_types(m1, m2, assume_yes=set()) elif is_ClassVar(T1): if not is_ClassVar(T2): raise NotEquivalentException(T1=T1, T2=T2) t1 = get_ClassVar_arg(T1) t2 = get_ClassVar_arg(T2) assert_equivalent_types(t1, t2, assume_yes) elif is_Optional(T1): if not is_Optional(T2): raise NotEquivalentException(T1=T1, T2=T2) t1 = get_Optional_arg(T1) t2 = get_Optional_arg(T2) assert_equivalent_types(t1, t2, assume_yes) elif is_Union(T1): if not is_Union(T2): raise NotEquivalentException(T1=T1, T2=T2) ts1 = get_Union_args(T1) ts2 = get_Union_args(T2) for t1, t2 in zip(ts1, ts2): assert_equivalent_types(t1, t2, assume_yes) elif is_Intersection(T1): if not is_Intersection(T2): raise NotEquivalentException(T1=T1, T2=T2) ts1 = get_Intersection_args(T1) ts2 = get_Intersection_args(T2) for t1, t2 in zip(ts1, ts2): assert_equivalent_types(t1, t2, assume_yes) elif is_FixedTupleLike(T1): if not is_FixedTupleLike(T2): raise NotEquivalentException(T1=T1, T2=T2) ts1 = get_FixedTupleLike_args(T1) ts2 = get_FixedTupleLike_args(T2) for t1, t2 in zip(ts1, ts2): assert_equivalent_types(t1, t2, assume_yes) elif is_VarTuple(T1): if not is_VarTuple(T2): raise NotEquivalentException(T1=T1, T2=T2) t1 = get_VarTuple_arg(T1) t2 = get_VarTuple_arg(T2) assert_equivalent_types(t1, t2, assume_yes) elif is_SetLike(T1): T1 = cast(Type[Set], T1) if not is_SetLike(T2): raise NotEquivalentException(T1=T1, T2=T2) T2 = cast(Type[Set], T2) t1 = get_SetLike_arg(T1) t2 = get_SetLike_arg(T2) assert_equivalent_types(t1, t2, assume_yes) elif is_ListLike(T1): T1 = cast(Type[List], T1) if not is_ListLike(T2): raise NotEquivalentException(T1=T1, T2=T2) T2 = cast(Type[List], T2) t1 = get_ListLike_arg(T1) t2 = get_ListLike_arg(T2) assert_equivalent_types(t1, t2, assume_yes) elif is_DictLike(T1): T1 = cast(Type[Dict], T1) if not is_DictLike(T2): raise NotEquivalentException(T1=T1, T2=T2) T2 = cast(Type[Dict], T2) t1, u1 = get_DictLike_args(T1) t2, u2 = get_DictLike_args(T2) assert_equivalent_types(t1, t2, assume_yes) assert_equivalent_types(u1, u2, assume_yes) elif is_Any(T1): if not is_Any(T2): raise NotEquivalentException(T1=T1, T2=T2) elif is_TypeVar(T1): if not is_TypeVar(T2): raise NotEquivalentException(T1=T1, T2=T2) n1 = get_TypeVar_name(T1) n2 = get_TypeVar_name(T2) if n1 != n2: raise NotEquivalentException(n1=n1, n2=n2) elif T1 in (int, str, bool, Decimal, datetime, float, type): if T1 != T2: raise NotEquivalentException(T1=T1, T2=T2) elif is_NewType(T1): if not is_NewType(T2): raise NotEquivalentException(T1=T1, T2=T2) n1 = get_NewType_name(T1) n2 = get_NewType_name(T2) if n1 != n2: raise NotEquivalentException(T1=T1, T2=T2) o1 = get_NewType_arg(T1) o2 = get_NewType_arg(T2) assert_equivalent_types(o1, o2, assume_yes) elif is_Type(T1): if not is_Type(T2): raise NotEquivalentException(T1=T1, T2=T2) t1 = get_Type_arg(T1) t2 = get_Type_arg(T2) assert_equivalent_types(t1, t2, assume_yes) elif is_Uninhabited(T1): if not is_Uninhabited(T2): raise NotEquivalentException(T1=T1, T2=T2) else: raise NotImplementedError((T1, T2)) except NotEquivalentException as e: # logger.error(e) msg = f"Could not establish the two types to be equivalent." raise NotEquivalentException(msg, T1=T1, T2=T2) from e # assert T1 == T2 # assert_equal(T1.mro(), T2.mro())
zuper-typing-z5
/zuper-typing-z5-5.3.0.tar.gz/zuper-typing-z5-5.3.0/src/zuper_typing/get_patches_.py
get_patches_.py
from dataclasses import dataclass, field, Field, fields, is_dataclass, MISSING, replace from datetime import datetime from decimal import Decimal from typing import Any, Callable, cast, Dict, List, Optional, Tuple, Type, TypeVar import termcolor from frozendict import frozendict from zuper_commons.text import indent from zuper_commons.text.coloring import get_length_on_screen, remove_escapes from zuper_commons.text.table import format_table, Style from zuper_commons.types.exceptions import ZException from zuper_commons.ui.colors import ( color_constant, color_float, color_int, color_ops, color_par, color_synthetic_types, color_typename, color_typename2, colorize_rgb, ) from .aliases import TypeLike from .annotations_tricks import ( get_Callable_info, get_ClassVar_arg, get_fields_including_static, get_FixedTupleLike_args, get_Optional_arg, get_Type_arg, get_TypeVar_bound, get_Union_args, get_VarTuple_arg, is_Any, is_Callable, is_ClassVar, is_Dict, is_FixedTupleLike, is_ForwardRef, is_Iterable, is_Iterator, is_List, is_NewType, is_Optional, is_Sequence, is_Set, is_Type, is_TypeLike, is_TypeVar, is_Union, is_VarTuple, name_for_type_like, ) from .monkey_patching_typing import ( DataclassHooks, debug_print_bytes, debug_print_date, debug_print_str, ) from .my_dict import ( CustomDict, CustomList, CustomSet, get_CustomDict_args, get_CustomList_arg, get_CustomSet_arg, is_CustomDict, is_CustomList, is_CustomSet, ) from .my_intersection import get_Intersection_args, is_Intersection from .uninhabited import is_Uninhabited __all__ = ["debug_print"] @dataclass class DPOptions: obey_print_order: bool = True do_special_EV: bool = True do_not_display_defaults: bool = True compact: bool = False abbreviate: bool = False # |│┃┆ default_border_left = "│ " # <-- note box-drawing id_gen: Callable[[object], object] = id # cid_if_known max_initial_levels: int = 20 omit_type_if_empty: bool = True omit_type_if_short: bool = True ignores: List[Tuple[str, str]] = field(default_factory=list) other_decoration_dataclass: Callable[[object], str] = lambda _: "" abbreviate_zuper_lang: bool = False ignore_dunder_dunder: bool = False def get_default_dpoptions() -> DPOptions: ignores = [] id_gen = id return DPOptions(ignores=ignores, id_gen=id_gen) def remove_color_if_no_support(f): def f2(*args, **kwargs): s = f(*args, **kwargs) from zuper_commons.types.exceptions import disable_colored if disable_colored(): # pragma: no cover s = remove_escapes(s) return s return f2 @remove_color_if_no_support def debug_print(x: object, opt: Optional[DPOptions] = None) -> str: if opt is None: opt = get_default_dpoptions() max_levels = opt.max_initial_levels already = {} stack = () return debug_print0(x, max_levels=max_levels, already=already, stack=stack, opt=opt) ZException.entries_formatter = debug_print def debug_print0( x: object, *, max_levels: int, already: Dict[int, str], stack: Tuple[int, ...], opt: DPOptions, ) -> str: if id(x) in stack: if hasattr(x, "__name__"): n = x.__name__ return color_typename2(n + "↑") # ↶' return "(recursive)" if opt.compact: if isinstance(x, type) and is_dataclass(x): return color_typename(x.__name__) # logger.info(f'stack: {stack} {id(x)} {type(x)}') stack2 = stack + (id(x),) args = dict(max_levels=max_levels, already=already, stack=stack2, opt=opt) dpa = lambda _: debug_print0(_, **args) opt_compact = replace(opt, compact=True) dp_compact = lambda _: debug_print0( _, max_levels=max_levels, already=already, stack=stack2, opt=opt_compact ) # abbreviate = True if not opt.abbreviate: prefix = "" else: if is_dataclass(x) and type(x).__name__ != "Constant": # noinspection PyBroadException try: h = opt.id_gen(x) except: prefix = termcolor.colored("!!!", "red") # except ValueError: # prefix = '!' else: if h is not None: if h in already: # from . import logger if isinstance(x, type): short = type(x).__name__ + "(...) " else: short = color_typename(type(x).__name__) + "(...) " res = short + termcolor.colored("$" + already[h], "green") # logger.info(f'ok already[h] = {res} already = {already}') return res else: already[h] = f"{len(already)}" prefix = termcolor.colored( "&" + already[h], "green", attrs=["dark"] ) else: prefix = "" else: prefix = "" postfix = " " + prefix if prefix else "" # prefix = prefix + f' L{max_levels}' if isinstance(x, int): return color_int(str(x)) if isinstance(x, float): return color_float(str(x)) if x is type: return color_ops("type") if x is BaseException: return color_ops("BaseException") if x is tuple: return color_ops("tuple") if x is object: return color_ops("object") if x is list: return color_ops("list") if x is dict: return color_ops("dict") if x is type(...): return color_ops("ellipsis") if x is int: return color_ops("int") if x is float: return color_ops("float") if x is bool: return color_ops("bool") if x is str: return color_ops("str") if x is bytes: return color_ops("bytes") if x is set: return color_ops("set") if x is slice: return color_ops("slice") if x is datetime: return color_ops("datetime") if x is Decimal: return color_ops("Decimal") if not isinstance(x, str): if is_TypeLike(x): x = cast(TypeLike, x) return debug_print_typelike(x, dp_compact, dpa, opt, prefix, args) if isinstance(x, bytes): return debug_print_bytes(x) if isinstance(x, str): return debug_print_str(x, prefix=prefix) if isinstance(x, Decimal): return color_ops("Dec") + " " + color_float(str(x)) if isinstance(x, datetime): return debug_print_date(x, prefix=prefix) if isinstance(x, set): return debug_print_set(x, prefix=prefix, **args) if isinstance(x, (dict, frozendict)): return debug_print_dict(x, prefix=prefix, **args) if isinstance(x, tuple): return debug_print_tuple(x, prefix=prefix, **args) if isinstance(x, list): return debug_print_list(x, prefix=prefix, **args) if isinstance(x, (bool, type(None))): return color_ops(str(x)) + postfix if not isinstance(x, type) and is_dataclass(x): return debug_print_dataclass_instance(x, prefix=prefix, **args) if "Expr" in type(x).__name__: return f"{x!r}\n{x}" r = f"instance of {type(x).__name__}:\n{x!r}" # assert not 'typing.Union' in r, (r, x, is_Union(x)) return r cst = color_synthetic_types def debug_print_typelike(x: TypeLike, dp_compact, dpa, opt, prefix, args) -> str: assert is_TypeLike(x), x if is_Any(x): s = name_for_type_like(x) return termcolor.colored(s, on_color="on_magenta") if is_Uninhabited(x): s = "Nothing" return termcolor.colored(s, on_color="on_magenta") if ( (x is type(None)) or is_List(x) or is_Dict(x) or is_Set(x) or is_ClassVar(x) # or is_Type(x) or is_Iterator(x) or is_Sequence(x) or is_Iterable(x) or is_NewType(x) or is_ForwardRef(x) or is_Uninhabited(x) ): return color_ops(name_for_type_like(x)) if is_TypeVar(x): assert isinstance(x, TypeVar), x name = x.__name__ bound = get_TypeVar_bound(x) covariant = getattr(x, "__covariant__") contravariant = getattr(x, "__contravariant__") if covariant: n = name + "+" elif contravariant: n = name + "-" else: n = name + "=" n = cst(n) if bound is not object: n += color_ops("<") + dp_compact(bound) return n if is_CustomDict(x): x = cast(Type[CustomDict], x) K, V = get_CustomDict_args(x) s = cst("Dict") + cst("[") + dp_compact(K) + cst(",") + dp_compact(V) + cst("]") return s if is_Type(x): V = get_Type_arg(x) s = cst("Type") + cst("[") + dp_compact(V) + cst("]") return s if is_ClassVar(x): V = get_ClassVar_arg(x) s = color_ops("ClassVar") + cst("[") + dp_compact(V) + cst("]") return s if is_CustomSet(x): x = cast(Type[CustomSet], x) V = get_CustomSet_arg(x) s = cst("Set") + cst("[") + dp_compact(V) + cst("]") return s if is_CustomList(x): x = cast(Type[CustomList], x) V = get_CustomList_arg(x) s = cst("List") + cst("[") + dp_compact(V) + cst("]") return s if is_Optional(x): V = get_Optional_arg(x) s0 = dp_compact(V) s = color_ops("Optional") + cst("[") + s0 + cst("]") return s if is_FixedTupleLike(x): ts = get_FixedTupleLike_args(x) ss = [] for t in ts: ss.append(dp_compact(t)) args = color_ops(",").join(ss) s = color_ops("Tuple") + cst("[") + args + cst("]") return s if is_VarTuple(x): x = cast(Type[Tuple], x) t = get_VarTuple_arg(x) s = color_ops("Tuple") + cst("[") + dp_compact(t) + ", ..." + cst("]") return s if is_Union(x): Ts = get_Union_args(x) if opt.compact or len(Ts) <= 3: ss = list(dp_compact(v) for v in Ts) inside = color_ops(",").join(ss) s = color_ops("Union") + cst("[") + inside + cst("]") else: ss = list(dpa(v) for v in Ts) s = color_ops("Union") for v in ss: s += "\n" + indent(v, "", color_ops(f"* ")) return s if is_Intersection(x): Ts = get_Intersection_args(x) if opt.compact or len(Ts) <= 3: ss = list(dp_compact(v) for v in Ts) inside = color_ops(",").join(ss) s = color_ops("Intersection") + cst("[") + inside + cst("]") else: ss = list(dpa(v) for v in Ts) s = color_ops("Intersection") for v in ss: s += "\n" + indent(v, "", color_ops(f"* ")) return s if is_Callable(x): info = get_Callable_info(x) def ps(k, v): if k.startswith("__"): return dp_compact(v) else: return f"NamedArg({dp_compact(v)},{k!r})" params = color_ops(",").join( ps(k, v) for k, v in info.parameters_by_name.items() ) ret = dp_compact(info.returns) return ( color_ops("Callable") + cst("[[") + params + color_ops("],") + ret + cst("]") ) if isinstance(x, type) and is_dataclass(x): return debug_print_dataclass_type(x, prefix=prefix, **args) return repr(x) DataclassHooks.dc_str = debug_print def clipped(): return " " + termcolor.colored("...", "blue", on_color="on_yellow") def debug_print_dict( x: dict, *, prefix, max_levels: int, already: Dict, stack: Tuple[int], opt: DPOptions, ): dpa = lambda _: debug_print0( _, max_levels=max_levels - 1, already=already, stack=stack, opt=opt ) opt_compact = replace(opt, compact=True) dps = lambda _: debug_print0( _, max_levels=max_levels, already={}, stack=stack, opt=opt_compact ) ps = " " + prefix if prefix else "" if len(x) == 0: if opt.omit_type_if_empty: return color_ops("{}") + ps else: return dps(type(x)) + " " + color_ops("{}") + ps # s = color_ops(type(x).__name__) + postfix s = dps(type(x)) + ps if max_levels == 0: return s + clipped() r = {} for k, v in x.items(): if isinstance(k, str): if k.startswith("zd"): k = "zd..." + k[-4:] k = termcolor.colored(k, "yellow") else: k = dpa(k) # ks = debug_print(k) # if ks.startswith("'"): # ks = k r[k] = dpa(v) ss = [k + ": " + v for k, v in r.items()] nlines = sum(_.count("\n") for _ in ss) tlen = sum(get_length_on_screen(_) for _ in ss) if nlines == 0 and tlen < 50: # x = "," if len(x) == 1 else "" res = color_ops("{") + color_ops(", ").join(ss) + color_ops("}") + ps if opt.omit_type_if_short: return res else: return dps(type(x)) + " " + res leftmargin = color_ops(opt.default_border_left) return pretty_dict_compact(s, r, leftmargin=leftmargin, indent_value=0) def debug_print_dataclass_type( x: Type[dataclass], prefix: str, max_levels: int, already: Dict, stack: Tuple, opt: DPOptions, ) -> str: dpa = lambda _: debug_print0( _, max_levels=max_levels - 1, already=already, stack=stack, opt=opt ) ps = " " + prefix if prefix else "" # ps += f" {id(x)} {type(x)}" # note breaks string equality if opt.abbreviate_zuper_lang: if x.__module__.startswith("zuper_lang."): return color_constant(x.__name__) more = "" if x.__name__ != x.__qualname__: more += f" ({x.__qualname__})" mod = x.__module__ + "." s = ( color_ops("dataclass") + " " + mod + color_typename(x.__name__) + more + ps ) # + f' {id(x)}' cells = {} # FIXME: what was the unique one ? seen_fields = set() row = 0 all_fields: Dict[str, Field] = get_fields_including_static(x) for name, f in all_fields.items(): T = f.type if opt.ignore_dunder_dunder: if f.name.startswith("__"): continue cells[(row, 0)] = color_ops("field") cells[(row, 1)] = f.name cells[(row, 2)] = color_ops(":") cells[(row, 3)] = dpa(T) if f.default != MISSING: cells[(row, 4)] = color_ops("=") cells[(row, 5)] = dpa(f.default) elif f.default_factory != MISSING: cells[(row, 4)] = color_ops("=") cells[(row, 5)] = f"factory {dpa(f.default_factory)}" if is_ClassVar(T): if not hasattr(T, name): cells[(row, 6)] = "no attribute set" else: v = getattr(T, name) # cells[(row, 4)] = color_ops("=") cells[(row, 6)] = dpa(v) seen_fields.add(f.name) row += 1 # for k, ann in x.__annotations__.items(): # if k in seen_fields: # continue # if not is_ClassVar(ann): # continue # T = get_ClassVar_arg(ann) # # cells[(row, 0)] = color_ops("classvar") # cells[(row, 1)] = k # cells[(row, 2)] = color_ops(':') # cells[(row, 3)] = dpa(T) # # if hasattr(x, k): # cells[(row, 4)] = color_ops('=') # cells[(row, 5)] = dpa(getattr(x, k)) # else: # cells[(row, 5)] = '(no value)' # # row += 1 if not cells: return s + ": (no fields)" align_right = Style(halign="right") col_style = {0: align_right, 1: align_right} res = format_table(cells, style="spaces", draw_grid_v=False, col_style=col_style) return s + "\n" + res # indent(res, ' ') def debug_print_list( x: list, prefix: str, max_levels: int, already: Dict, stack: Tuple, opt: DPOptions ) -> str: dpa = lambda _: debug_print0( _, max_levels=max_levels - 1, already=already, stack=stack, opt=opt ) dps = lambda _: debug_print0( _, opt=opt, max_levels=max_levels, already={}, stack=stack ) ps = " " + prefix if prefix else "" s = dps(type(x)) + ps if max_levels <= 0: return s + clipped() if len(x) == 0: if opt.omit_type_if_empty: return color_ops("[]") + ps else: return dps(type(x)) + " " + color_ops("[]") + ps ss = [dpa(v) for v in x] nlines = sum(_.count("\n") for _ in ss) tlen = sum(get_length_on_screen(_) for _ in ss) if nlines == 0 and tlen < 50: # x = "," if len(x) == 1 else "" res = color_ops("[") + color_ops(", ").join(ss) + color_ops("]") + ps return res for i, si in enumerate(ss): # s += '\n' + indent(debug_print(v), '', color_ops(f'#{i} ')) s += "\n" + indent(si, "", color_ops(f"#{i} ")) return s def debug_print_set( x: set, *, prefix: str, max_levels: int, already: Dict, stack: Tuple, opt: DPOptions ) -> str: dpa = lambda _: debug_print0( _, max_levels=max_levels - 1, already=already, stack=stack, opt=opt ) dps = lambda _: debug_print0( _, max_levels=max_levels, already={}, stack=stack, opt=opt ) ps = " " + prefix if prefix else "" if len(x) == 0: if opt.omit_type_if_empty: return color_ops("∅") + ps else: return dps(type(x)) + " " + color_ops("∅") + ps s = dps(type(x)) + ps if max_levels <= 0: return s + clipped() ss = [dpa(v) for v in x] nlines = sum(_.count("\n") for _ in ss) tlen = sum(get_length_on_screen(_) for _ in ss) if nlines == 0 and tlen < 50: res = color_ops("{") + color_ops(", ").join(ss) + color_ops("}") + ps if opt.omit_type_if_short: return res else: return dps(type(x)) + " " + res for vi in ss: # s += '\n' + indent(debug_print(v), '', color_ops(f'#{i} ')) s += "\n" + indent(dpa(vi), "", color_ops(f"* ")) return s def debug_print_tuple( x: tuple, prefix: str, max_levels: int, already: Dict, stack: Tuple, opt: DPOptions ) -> str: dpa = lambda _: debug_print0( _, max_levels=max_levels - 1, already=already, stack=stack, opt=opt ) dps = lambda _: debug_print0( _, max_levels=max_levels, already={}, stack=stack, opt=opt ) ps = " " + prefix if prefix else "" if len(x) == 0: if opt.omit_type_if_empty: return color_ops("()") + ps else: return dps(type(x)) + " " + color_ops("()") + ps s = dps(type(x)) + ps if max_levels <= 0: return s + clipped() ss = [dpa(v) for v in x] tlen = sum(get_length_on_screen(_) for _ in ss) nlines = sum(_.count("\n") for _ in ss) if nlines == 0 and tlen < 50: x = "," if len(x) == 1 else "" res = color_ops("(") + color_ops(", ").join(ss) + x + color_ops(")") + ps if opt.omit_type_if_short: return res else: return dps(type(x)) + " " + res for i, si in enumerate(ss): s += "\n" + indent(si, "", color_ops(f"#{i} ")) return s def debug_print_dataclass_instance( x: dataclass, prefix: str, max_levels: int, already: Dict, stack: Tuple, opt: DPOptions, ) -> str: assert is_dataclass(x) fields_x = fields(x) dpa = lambda _: debug_print0( _, max_levels=max_levels - 1, already=already, stack=stack, opt=opt ) # noinspection PyArgumentList other = opt.other_decoration_dataclass(x) CN = type(x).__name__ special_colors = { "EV": "#77aa77", "ZFunction": "#ffffff", "ArgRef": "#00ffff", "ZArg": "#00ffff", "ATypeVar": "#00ffff", "MakeProcedure": "#ffffff", "IF": "#fafaaf", } if CN in special_colors: cn = colorize_rgb(CN, special_colors[CN]) else: cn = color_typename(CN) ps = " " + prefix if prefix else "" s = cn + ps + other if max_levels <= 0: return s + clipped() if opt.obey_print_order and hasattr(x, "__print_order__"): options = x.__print_order__ else: options = [] for f in fields_x: options.append(f.name) if opt.do_not_display_defaults: same = [] for f in fields_x: att = getattr(x, f.name) if f.default != MISSING: if f.default == att: same.append(f.name) elif f.default_factory != MISSING: default = f.default_factory() if default == att: same.append(f.name) to_display = [_ for _ in options if _ not in same] else: to_display = options r = {} dpa_result = {} for k in to_display: # for k, v in x.__annotations__.items(): # v = x.__annotations__[k] if k == "expect": att = getattr(x, k) # logger.info(f'CN {CN} k {k!r} {getattr(att, "val", None)}') if CN == "EV" and k == "expect" and getattr(att, "val", None) is type: expects_type = True continue if not k in to_display: continue if k.startswith("__"): # TODO: make configurable continue if (CN, k) in opt.ignores: continue # r[color_par(k)] = "(non visualized)" else: att = getattr(x, k) r[color_par(k)] = dpa_result[k] = dpa(att) # r[(k)] = debug_print(att) expects_type = False if len(r) == 0: return cn + f"()" + prefix + other if type(x).__name__ == "Constant": s0 = dpa_result["val"] if not "\n" in s0: # 「 」‹ › return color_constant("⟬") + s0 + color_constant("⟭") else: l = color_constant("│ ") # ║") f = color_constant("C ") return indent(s0, l, f) if type(x).__name__ == "QualifiedName": module_name = x.module_name qual_name = x.qual_name return ( color_typename("QN") + " " + module_name + "." + color_typename(qual_name) ) if type(x).__name__ == "ATypeVar": if len(r) == 1: # only if no other stuff return color_synthetic_types(x.typevar_name) if CN == "EV" and opt.do_special_EV: if len(r) == 1: res = list(r.values())[0] else: res = pretty_dict_compact("", r, leftmargin="") if x.pr is not None: color_to_use = x.pr.get_color() else: color_to_use = "#f0f0f0" def colorit(_: str) -> str: return colorize_rgb(_, color_to_use) if expects_type: F = "ET " else: F = "E " l = colorit("┋ ") f = colorit(F) return indent(res, l, f) if len(r) == 1: k0 = list(r)[0] v0 = r[k0] if not "\n" in v0 and not "(" in v0: return cn + f"({k0}={v0.rstrip()})" + prefix + other ss = list(r.values()) tlen = sum(get_length_on_screen(_) for _ in ss) nlines = sum(_.count("\n") for _ in ss) # npars = sum(_.count("(") for _ in ss) if nlines == 0 and tlen < 70: # ok, we can do on one line if type(x).__name__ == "MakeUnion": assert len(r) == 1 ts = x.utypes v = [dpa(_) for _ in ts] return "(" + color_ops(" ∪ ").join(v) + ")" if type(x).__name__ == "MakeIntersection": assert len(r) == 1 ts = x.inttypes v = [dpa(_) for _ in ts] return "(" + color_ops(" ∩ ").join(v) + ")" contents = ", ".join(k + "=" + v for k, v in r.items()) res = cn + "(" + contents + ")" + ps return res if CN == "MakeProcedure": M2 = "┇ " else: M2 = opt.default_border_left if CN in special_colors: leftmargin = colorize_rgb(M2, special_colors[CN]) else: leftmargin = color_typename(M2) return pretty_dict_compact(s, r, leftmargin=leftmargin, indent_value=0) # # def debug_print_dataclass_compact( # x, max_levels: int, already: Dict, stack: Tuple, # opt: DPOptions # ): # dpa = lambda _: debug_print0(_, max_levels=max_levels - 1, already=already, stack=stack, opt=opt) # # dps = lambda _: debug_print(_, max_levels, already={}, stack=stack) # s = color_typename(type(x).__name__) + color_par("(") # ss = [] # for k, v in x.__annotations__.items(): # att = getattr(x, k) # ss.append(f'{color_par(k)}{color_par("=")}{dpa(att)}') # # s += color_par(", ").join(ss) # s += color_par(")") # return s def pretty_dict_compact( head: Optional[str], d: Dict[str, Any], leftmargin="│", indent_value: int = 0 ): # | <-- note box-making if not d: return head + ": (empty dict)" if head else "(empty dict)" s = [] # n = max(get_length_on_screen(str(_)) for _ in d) ordered = list(d) # ks = sorted(d) for k in ordered: v = d[k] heading = str(k) + ":" # if isinstance(v, TypeVar): # # noinspection PyUnresolvedReferences # v = f'TypeVar({v.__name__}, bound={v.__bound__})' # if isinstance(v, dict): # v = pretty_dict_compact("", v) # vs = v if "\n" in v: vs = indent(v, " " * indent_value) s.append(heading) s.append(vs) else: s.append(heading + " " + v) # s.extend(.split('\n')) # return (head + ':\n' if head else '') + indent("\n".join(s), '| ') indented = indent("\n".join(s), leftmargin) return (head + "\n" if head else "") + indented
zuper-typing-z5
/zuper-typing-z5-5.3.0.tar.gz/zuper-typing-z5-5.3.0/src/zuper_typing/debug_print_.py
debug_print_.py
import dataclasses import typing from datetime import datetime from typing import Dict, Generic, TypeVar import termcolor from zuper_commons.text.boxing import box from zuper_commons.text.text_sidebyside import side_by_side from .constants import ( ANNOTATIONS_ATT, DEPENDS_ATT, monkey_patch_dataclass, monkey_patch_Generic, PYTHON_36, ) from .my_dict import make_dict from .zeneric2 import resolve_types, ZenericFix if PYTHON_36: # pragma: no cover from typing import GenericMeta previous_getitem = GenericMeta.__getitem__ else: from typing import _GenericAlias previous_getitem = _GenericAlias.__getitem__ class Alias1: def __getitem__(self, params): if self is typing.Dict: K, V = params if K is not str: return make_dict(K, V) # noinspection PyArgumentList return previous_getitem(self, params) def original_dict_getitem(a): # noinspection PyArgumentList return previous_getitem(Dict, a) if monkey_patch_Generic: # pragma: no cover if PYTHON_36: # pragma: no cover GenericMeta.__getitem__ = ZenericFix.__getitem__ else: Generic.__class_getitem__ = ZenericFix.__class_getitem__ _GenericAlias.__getitem__ = Alias1.__getitem__ Dict.__getitem__ = Alias1.__getitem__ def _cmp_fn_loose(name, op, self_tuple, other_tuple, *args, **kwargs): body = [ "if other.__class__.__name__ == self.__class__.__name__:", f" return {self_tuple}{op}{other_tuple}", "return NotImplemented", ] fn = dataclasses._create_fn(name, ("self", "other"), body) fn.__doc__ = """ This is a loose comparison function. Instead of comparing: self.__class__ is other.__class__ we compare: self.__class__.__name__ == other.__class__.__name__ """ return fn dataclasses._cmp_fn = _cmp_fn_loose def typevar__repr__(self): if self.__covariant__: prefix = "+" elif self.__contravariant__: prefix = "-" else: prefix = "~" s = prefix + self.__name__ if self.__bound__: if isinstance(self.__bound__, type): b = self.__bound__.__name__ else: b = str(self.__bound__) s += f"<{b}" return s setattr(TypeVar, "__repr__", typevar__repr__) NAME_ARG = "__name_arg__" # need to have this otherwise it's not possible to say that two types are the same class Reg: already = {} def MyNamedArg(T, name: str): try: int(name) except: pass else: msg = f"Tried to create NamedArg with name = {name!r}." raise ValueError(msg) key = f"{T} {name}" if key in Reg.already: return Reg.already[key] class CNamedArg: pass setattr(CNamedArg, NAME_ARG, name) setattr(CNamedArg, "original", T) Reg.already[key] = CNamedArg return CNamedArg import mypy_extensions setattr(mypy_extensions, "NamedArg", MyNamedArg) from dataclasses import dataclass as original_dataclass from typing import Tuple class RegisteredClasses: # klasses: Dict[str, type] = {} klasses: Dict[Tuple[str, str], type] = {} def get_remembered_class(module_name: str, qual_name: str) -> type: k = (module_name, qual_name) return RegisteredClasses.klasses[k] def remember_created_class(res: type, msg: str = ""): k = (res.__module__, res.__qualname__) # logger.info(f"Asked to remember {k}: {msg}") if k in RegisteredClasses.klasses: pass # logger.info(f"Asked to remember again {k}: {msg}") RegisteredClasses.klasses[k] = res # noinspection PyShadowingBuiltins def my_dataclass( _cls=None, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, ): def wrap(cls): # logger.info(f'called my_dataclass for {cls} with bases {_cls.__bases__}') # if cls.__name__ == 'B' and len(cls.__bases__) == 1 and cls.__bases__[0].__name__ # == 'object' and len(cls.__annotations__) != 2: # assert False, (cls, cls.__bases__, cls.__annotations__) res = my_dataclass_( cls, init=init, repr=repr, eq=eq, order=order, unsafe_hash=unsafe_hash, frozen=frozen, ) # logger.info(f'called my_dataclass for {cls} with bases {_cls.__bases__}, ' # f'returning {res} with bases {res.__bases__} and annotations { # _cls.__annotations__}') remember_created_class(res, "my_dataclass") return res # See if we're being called as @dataclass or @dataclass(). if _cls is None: # We're called with parens. return wrap # We're called as @dataclass without parens. return wrap(_cls) def get_all_annotations(cls: type) -> Dict[str, type]: """ Gets all the annotations including the parents. """ res = {} for base in cls.__bases__: annotations = getattr(base, ANNOTATIONS_ATT, {}) res.update(annotations) # logger.info(f'name {cls.__name__} bases {cls.__bases__} mro {cls.mro()} res {res}') return res # noinspection PyShadowingBuiltins def my_dataclass_( _cls, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False ): original_doc = getattr(_cls, "__doc__", None) # logger.info(_cls.__dict__) unsafe_hash = True if hasattr(_cls, "nominal"): # logger.info('nominal for {_cls}') nominal = True else: nominal = False # # if the class does not have a metaclass, add one # We copy both annotations and constants. This is needed for cases like: # # @dataclass # class C: # a: List[] = field(default_factory=list) # # # if Generic in _cls.__bases__: msg = f"There are problems with initialization: class {_cls.__name__} inherits from Generic: {_cls.__bases__}" raise Exception(msg) if type(_cls) is type: old_annotations = get_all_annotations(_cls) from .zeneric2 import StructuralTyping old_annotations.update(getattr(_cls, ANNOTATIONS_ATT, {})) attrs = {ANNOTATIONS_ATT: old_annotations} for k in old_annotations: if hasattr(_cls, k): attrs[k] = getattr(_cls, k) class Base(metaclass=StructuralTyping): pass _cls2 = type(_cls.__name__, (_cls, Base) + _cls.__bases__, attrs) _cls2.__module__ = _cls.__module__ _cls2.__qualname__ = _cls.__qualname__ _cls = _cls2 else: old_annotations = get_all_annotations(_cls) old_annotations.update(getattr(_cls, ANNOTATIONS_ATT, {})) setattr(_cls, ANNOTATIONS_ATT, old_annotations) k = "__" + _cls.__name__.replace("[", "_").replace("]", "_") if nominal: # # annotations = getattr(K, '__annotations__', {}) old_annotations[k] = bool # typing.Optional[bool] setattr(_cls, k, True) if "__hash__" in _cls.__dict__: unsafe_hash = False # print(_cls.__dict__) # _cls.__dict__['__hash__']= None res = original_dataclass( _cls, init=init, repr=repr, eq=eq, order=order, unsafe_hash=unsafe_hash, frozen=frozen, ) # assert dataclasses.is_dataclass(res) refs = getattr(_cls, DEPENDS_ATT, ()) resolve_types(res, refs=refs) def __repr__(self) -> str: return DataclassHooks.dc_repr(self) def __str__(self): return DataclassHooks.dc_str(self) setattr(res, "__repr__", __repr__) setattr(res, "__str__", __str__) setattr(res, "__doc__", original_doc) if nominal: setattr(_cls, k, True) return res def nice_str(self): return DataclassHooks.dc_repr(self) def blue(x): return termcolor.colored(x, "blue") def nice_repr(self): s = termcolor.colored(type(self).__name__, "red") s += blue("(") ss = [] annotations = getattr(type(self), "__annotations__", {}) for k in annotations: a = getattr(self, k) a_s = debug_print_compact(a) eq = blue("=") k = termcolor.colored(k, attrs=["dark"]) ss.append(f"{k}{eq}{a_s}") s += blue(", ").join(ss) s += blue(")") return s def debug_print_compact(x): if isinstance(x, str): return debug_print_str(x, prefix="") if isinstance(x, bytes): return debug_print_bytes(x) if isinstance(x, datetime): return debug_print_date(x, prefix="") return f"{x!r}" def debug_print_str(x: str, *, prefix: str): if type(x) is not str: return type(x).__name__ + " - " + debug_print_str(str(x), prefix=prefix) if x == "\n": return "`\\n`" if x.startswith("Qm"): x2 = "Qm..." + x[-4:] + " " + prefix return termcolor.colored(x2, "magenta") # if x.startswith("zd"): # x2 = "zd..." + x[-4:] + " " + prefix # return termcolor.colored(x2, "magenta") if x.startswith("-----BEGIN"): s = "PEM key" + " " + prefix return termcolor.colored(s, "yellow") if x.startswith("Traceback"): lines = x.split("\n") colored = [termcolor.colored(_, "red") for _ in lines] if colored: colored[0] += " " + prefix s = "\n".join(colored) return s ps = " " + prefix if prefix else "" lines = x.split("\n") if len(lines) > 1: try: res = box(x, color="yellow", attrs=["dark"]) return side_by_side([res, ps]) except: # print(traceback.format_exc()) return "?" if x.startswith("zdpu"): return termcolor.colored(x, "yellow") return "`" + x + "`" + ps # return x.__repr__() + ps def debug_print_date(x: datetime, *, prefix: str): s = x.isoformat()[:19] s = s.replace("T", " ") return termcolor.colored(s, "yellow") + (" " + prefix if prefix else "") def debug_print_bytes(x: bytes): s = f"{len(x)} bytes " + x[:10].__repr__() return termcolor.colored(s, "yellow") class DataclassHooks: dc_repr = nice_repr dc_str = nice_str if monkey_patch_dataclass: setattr(dataclasses, "dataclass", my_dataclass)
zuper-typing-z5
/zuper-typing-z5-5.3.0.tar.gz/zuper-typing-z5-5.3.0/src/zuper_typing/monkey_patching_typing.py
monkey_patching_typing.py
from dataclasses import dataclass, field, is_dataclass from datetime import datetime from decimal import Decimal from functools import reduce from typing import cast, Dict, List, Optional, Set, Tuple, Type from zuper_typing.aliases import TypeLike from zuper_typing.annotations_tricks import ( get_FixedTupleLike_args, get_Optional_arg, get_TypeVar_name, get_Union_args, get_VarTuple_arg, is_FixedTupleLike, is_Optional, is_TypeVar, is_Union, is_VarTuple, make_Tuple, make_Union, make_VarTuple, ) from zuper_typing.exceptions import ZValueError from zuper_typing.my_dict import ( get_DictLike_args, get_ListLike_arg, get_SetLike_arg, is_DictLike, is_ListLike, is_SetLike, make_dict, make_list, make_set, ) from zuper_typing.my_intersection import ( get_Intersection_args, is_Intersection, make_Intersection, ) from zuper_typing.uninhabited import is_Uninhabited, make_Uninhabited def unroll_union(a: TypeLike) -> Tuple[TypeLike, ...]: if is_Union(a): return get_Union_args(a) elif is_Optional(a): return (get_Optional_arg(a), type(None)) else: return (a,) def unroll_intersection(a: TypeLike) -> Tuple[TypeLike, ...]: if is_Intersection(a): return get_Intersection_args(a) else: return (a,) def type_sup(a: TypeLike, b: TypeLike) -> TypeLike: assert a is not None assert b is not None assert not isinstance(a, tuple), a assert not isinstance(b, tuple), b if a is b or (a == b): return a if a is object or b is object: return object if is_Uninhabited(a): return b if is_Uninhabited(b): return a if a is type(None): if is_Optional(b): return b else: return Optional[b] if b is type(None): if is_Optional(a): return a else: return Optional[a] if is_Optional(a): return type_sup(type(None), type_sup(get_Optional_arg(a), b)) if is_Optional(b): return type_sup(type(None), type_sup(get_Optional_arg(b), a)) # if is_Union(a) and is_Union(b): # XXX # r = [] # r.extend(unroll_union(a)) # r.extend(unroll_union(b)) # return reduce(type_sup, r) # if is_Union(a) and is_Union(b): ta = unroll_union(a) tb = unroll_union(b) tva, oa = get_typevars(ta) tvb, ob = get_typevars(tb) tv = tuple(set(tva + tvb)) oab = oa + ob if not oab: return make_Union(*tv) else: other = reduce(type_sup, oa + ob) os = unroll_union(other) return make_Union(*(tv + os)) if (a, b) in [(bool, int), (int, bool)]: return int if is_ListLike(a) and is_ListLike(b): a = cast(Type[List], a) b = cast(Type[List], b) A = get_ListLike_arg(a) B = get_ListLike_arg(b) u = type_sup(A, B) return make_list(u) if is_SetLike(a) and is_SetLike(b): a = cast(Type[Set], a) b = cast(Type[Set], b) A = get_SetLike_arg(a) B = get_SetLike_arg(b) u = type_sup(A, B) return make_set(u) if is_DictLike(a) and is_DictLike(b): a = cast(Type[Dict], a) b = cast(Type[Dict], b) KA, VA = get_DictLike_args(a) KB, VB = get_DictLike_args(b) K = type_sup(KA, KB) V = type_sup(VA, VB) return make_dict(K, V) if is_VarTuple(a) and is_VarTuple(b): a = cast(Type[Tuple], a) b = cast(Type[Tuple], b) VA = get_VarTuple_arg(a) VB = get_VarTuple_arg(b) V = type_sup(VA, VB) return make_VarTuple(V) if is_FixedTupleLike(a) and is_FixedTupleLike(b): a = cast(Type[Tuple], a) b = cast(Type[Tuple], b) tas = get_FixedTupleLike_args(a) tbs = get_FixedTupleLike_args(b) ts = tuple(type_sup(ta, tb) for ta, tb in zip(tas, tbs)) return make_Tuple(*ts) if is_dataclass(a) and is_dataclass(b): return type_sup_dataclass(a, b) if is_TypeVar(a) and is_TypeVar(b): if get_TypeVar_name(a) == get_TypeVar_name(b): return a return make_Union(a, b) # raise NotImplementedError(a, b) def type_inf_dataclass(a: Type[dataclass], b: Type[dataclass]) -> Type[dataclass]: from zuper_typing.monkey_patching_typing import my_dataclass ann_a = a.__annotations__ ann_b = b.__annotations__ all_keys = set(ann_a) | set(ann_b) res = {} for k in all_keys: if k in ann_a and k not in ann_b: R = ann_a[k] elif k not in ann_a and k in ann_b: R = ann_b[k] else: VA = ann_a[k] VB = ann_b[k] R = type_inf(VA, VB) if is_Uninhabited(R): return R res[k] = R name = f"Int_{a.__name__}_{b.__name__}" T2 = my_dataclass( type(name, (), {"__annotations__": res, "__module__": "zuper_typing"}) ) return T2 def type_sup_dataclass(a: Type[dataclass], b: Type[dataclass]) -> Type[dataclass]: from zuper_typing.monkey_patching_typing import my_dataclass ann_a = a.__annotations__ ann_b = b.__annotations__ common_keys = set(ann_a) & set(ann_b) res = {} for k in common_keys: if k in ann_a and k not in ann_b: R = ann_a[k] elif k not in ann_a and k in ann_b: R = ann_b[k] else: VA = ann_a[k] VB = ann_b[k] R = type_sup(VA, VB) res[k] = R name = f"Join_{a.__name__}_{b.__name__}" T2 = my_dataclass( type(name, (), {"__annotations__": res, "__module__": "zuper_typing"}) ) return T2 def type_inf(a: TypeLike, b: TypeLike) -> TypeLike: try: res = type_inf0(a, b) except ZValueError as e: raise raise ZValueError("problem", a=a, b=b) from e if isinstance(res, tuple): raise ZValueError(a=a, b=b, res=res) return res def get_typevars(a: Tuple[TypeLike, ...]) -> Tuple[Tuple, Tuple]: tv = [] ts = [] for _ in a: if is_TypeVar(_): tv.append(_) else: ts.append(_) return tuple(tv), tuple(ts) def type_inf0(a: TypeLike, b: TypeLike) -> TypeLike: assert a is not None assert b is not None if isinstance(a, tuple): raise ZValueError(a=a, b=b) if isinstance(b, tuple): raise ZValueError(a=a, b=b) if a is b or (a == b): return a if a is object: return b if b is object: return a if is_Uninhabited(a): return a if is_Uninhabited(b): return b if is_Optional(a): if b is type(None): return b if is_Optional(b): if a is type(None): return a if is_Optional(a) and is_Optional(b): x = type_inf(get_Optional_arg(a), get_Optional_arg(b)) if is_Uninhabited(x): return type(None) return Optional[x] # if not is_Intersection(a) and is_Intersection(b): # r = (a,) + unroll_intersection(b) # return reduce(type_inf, r) if is_Intersection(a) or is_Intersection(b): ta = unroll_intersection(a) tb = unroll_intersection(b) tva, oa = get_typevars(ta) tvb, ob = get_typevars(tb) tv = tuple(set(tva + tvb)) oab = oa + ob if not oab: return make_Intersection(tv) else: other = reduce(type_inf, oa + ob) os = unroll_intersection(other) return make_Intersection(tv + os) if is_Union(b): # A ^ (C u D) # = A^C u A^D r = [] for t in get_Union_args(b): r.append(type_inf(a, t)) return reduce(type_sup, r) # if is_Intersection(a) and not is_Intersection(b): # res = [] # for aa in get_Intersection_args(a): # r = type_inf(aa) # r.extend(unroll_intersection(a)) # r.extend(unroll_intersection(b)) # put first! # return reduce(type_inf, r) if (a, b) in [(bool, int), (int, bool)]: return bool if is_TypeVar(a) and is_TypeVar(b): if get_TypeVar_name(a) == get_TypeVar_name(b): return a if is_TypeVar(a) or is_TypeVar(b): return make_Intersection((a, b)) primitive = (bool, int, str, Decimal, datetime, float, bytes, type(None)) if a in primitive or b in primitive: return make_Uninhabited() if is_ListLike(a) ^ is_ListLike(b): return make_Uninhabited() if is_ListLike(a) & is_ListLike(b): a = cast(Type[List], a) b = cast(Type[List], b) A = get_ListLike_arg(a) B = get_ListLike_arg(b) u = type_inf(A, B) return make_list(u) if is_SetLike(a) ^ is_SetLike(b): return make_Uninhabited() if is_SetLike(a) and is_SetLike(b): a = cast(Type[Set], a) b = cast(Type[Set], b) A = get_SetLike_arg(a) B = get_SetLike_arg(b) u = type_inf(A, B) return make_set(u) if is_DictLike(a) ^ is_DictLike(b): return make_Uninhabited() if is_DictLike(a) and is_DictLike(b): a = cast(Type[Dict], a) b = cast(Type[Dict], b) KA, VA = get_DictLike_args(a) KB, VB = get_DictLike_args(b) K = type_inf(KA, KB) V = type_inf(VA, VB) return make_dict(K, V) if is_dataclass(a) ^ is_dataclass(b): return make_Uninhabited() if is_dataclass(a) and is_dataclass(b): return type_inf_dataclass(a, b) if is_VarTuple(a) and is_VarTuple(b): a = cast(Type[Tuple], a) b = cast(Type[Tuple], b) VA = get_VarTuple_arg(a) VB = get_VarTuple_arg(b) V = type_inf(VA, VB) return make_VarTuple(V) if is_FixedTupleLike(a) and is_FixedTupleLike(b): a = cast(Type[Tuple], a) b = cast(Type[Tuple], b) tas = get_FixedTupleLike_args(a) tbs = get_FixedTupleLike_args(b) ts = tuple(type_inf(ta, tb) for ta, tb in zip(tas, tbs)) return make_Tuple(*ts) if is_TypeVar(a) and is_TypeVar(b): if get_TypeVar_name(a) == get_TypeVar_name(b): return a return make_Intersection((a, b)) @dataclass class MatchConstraint: ub: type = None lb: type = None def impose_subtype(self, ub) -> "MatchConstraint": ub = type_sup(self.ub, ub) if self.ub is not None else ub return MatchConstraint(ub=ub, lb=self.lb) def impose_supertype(self, lb) -> "MatchConstraint": lb = type_inf(self.lb, lb) if self.lb is not None else lb return MatchConstraint(lb=lb, ub=self.ub) @dataclass class Matches: m: Dict[str, MatchConstraint] = field(default_factory=dict) def get_matches(self): res = {} for k, v in self.m.items(): if v.ub is not None: res[k] = v.ub return res def get_ub(self, k: str): if k not in self.m: return None return self.m[k].ub def get_lb(self, k: str): if k not in self.m: return None return self.m[k].lb def must_be_subtype_of(self, k: str, ub) -> "Matches": m2 = dict(self.m) if k not in m2: m2[k] = MatchConstraint() m2[k] = m2[k].impose_subtype(ub=ub) return Matches(m2) def must_be_supertype_of(self, k: str, lb) -> "Matches": m2 = dict(self.m) if k not in m2: m2[k] = MatchConstraint() m2[k] = m2[k].impose_supertype(lb=lb) return Matches(m2)
zuper-typing-z5
/zuper-typing-z5-5.3.0.tar.gz/zuper-typing-z5-5.3.0/src/zuper_typing/type_algebra.py
type_algebra.py
import sys import typing from abc import ABCMeta, abstractmethod from dataclasses import dataclass, fields, is_dataclass from datetime import datetime from decimal import Decimal from typing import Any, ClassVar, Dict, Tuple, cast from zuper_typing.exceptions import ZTypeError, ZValueError from .annotations_tricks import ( get_ClassVar_arg, get_Type_arg, is_ClassVar, is_NewType, is_Type, is_TypeLike, name_for_type_like, ) from .constants import ( BINDINGS_ATT, cache_enabled, DEPENDS_ATT, enable_type_checking, GENERIC_ATT2, MakeTypeCache, PYTHON_36, ZuperTypingGlobals, ) from .logging import logger from .recursive_tricks import ( get_name_without_brackets, NoConstructorImplemented, replace_typevars, TypeLike, ) from .subcheck import can_be_used_as2 def as_tuple(x) -> Tuple: return x if isinstance(x, tuple) else (x,) if PYTHON_36: # pragma: no cover from typing import GenericMeta # noinspection PyUnresolvedReferences old_one = GenericMeta.__getitem__ else: old_one = None if PYTHON_36: # pragma: no cover # logger.info('In Python 3.6') class ZMeta(type): def __getitem__(self, *params): # logger.info(f'ZMeta.__getitem__ {params} {self}') # pprint('P36', params=params, self=self) # if self is typing.Generic: return ZenericFix.__class_getitem__(*params) # # if self is typing.Dict: # K, V = params # if K is not str: # from zuper_typing.my_dict import make_dict # # return make_dict(K, V) # # # noinspection PyArgumentList # return old_one(self, *params) else: ZMeta = type class ZenericFix(metaclass=ZMeta): if PYTHON_36: # pragma: no cover def __getitem__(self, *params): # logger.info(f'P36 {params} {self}') if self is typing.Generic: return ZenericFix.__class_getitem__(*params) if self is Dict: K, V = params if K is not str: from .my_dict import make_dict return make_dict(K, V) # noinspection PyArgumentList return old_one(self, params) # noinspection PyMethodParameters @classmethod def __class_getitem__(cls0, params): # logger.info(f'ZenericFix.__class_getitem__ params = {params}') types = as_tuple(params) assert isinstance(types, tuple) for t in types: assert is_TypeLike(t), (t, types) # types = tuple(map(map_none_to_nonetype, types)) # logger.info(f'types {types}') if PYTHON_36: # pragma: no cover class FakeGenericMeta(MyABC): def __getitem__(self, params2): # logger.info(f'FakeGenericMeta {params2!r} {self}') # pprint('FakeGenericMeta.__getitem__', cls=cls, self=self, # params2=params2) types2 = as_tuple(params2) assert isinstance(types2, tuple), types2 for t in types2: assert is_TypeLike(t), (t, types2) if types == types2: return self bindings = {} for T, U in zip(types, types2): bindings[T] = U if T.__bound__ is not None and isinstance(T.__bound__, type): if not issubclass(U, T.__bound__): msg = ( f'For type parameter "{T.__name__}", expected a' f'subclass of "{T.__bound__.__name__}", found {U}.' ) raise ZTypeError(msg) return make_type(self, bindings) else: FakeGenericMeta = MyABC class GenericProxy(metaclass=FakeGenericMeta): @abstractmethod def need(self) -> None: """""" @classmethod def __class_getitem__(cls, params2) -> type: # logger.info(f'GenericProxy.__class_getitem__ params = {params2}') types2 = as_tuple(params2) bindings = {} for T, U in zip(types, types2): bindings[T] = U if T.__bound__ is not None and isinstance(T.__bound__, type): # logger.info(f"{U} should be usable as {T.__bound__}") # logger.info( # f" issubclass({U}, {T.__bound__}) =" # f" {issubclass(U, T.__bound__)}" # ) if not issubclass(U, T.__bound__): msg = ( f'For type parameter "{T.__name__}", expected a' f'subclass of "{T.__bound__.__name__}", found @U.' ) raise TypeError(msg) # , U=U) res = make_type(cls, bindings) from zuper_typing.monkey_patching_typing import remember_created_class remember_created_class(res, "__class_getitem__") return res name = "Generic[%s]" % ",".join(name_for_type_like(_) for _ in types) gp = type(name, (GenericProxy,), {GENERIC_ATT2: types}) setattr(gp, GENERIC_ATT2, types) return gp class StructuralTyping(type): def __subclasscheck__(self, subclass) -> bool: can = can_be_used_as2(subclass, self) return can.result def __instancecheck__(self, instance) -> bool: T = type(instance) if T is self: return True if not is_dataclass(T): return False i = super().__instancecheck__(instance) if i: return True # # loadable - To remove # if "Loadable" in T.__name__ and hasattr(instance, "T"): # pragma: no cover # if hasattr(instance, "T"): # T = getattr(instance, "T") # can = can_be_used_as2(T, self) # if can.result: # return True res = can_be_used_as2(T, self) return res.result class MyABC(StructuralTyping, ABCMeta): def __new__(mcs, name_orig, bases, namespace, **kwargs): # logger.info(f'----\nCreating name: {name}') # logger.info('namespace: %s' % namespace) # logger.info('bases: %s' % str(bases)) # if bases: # logger.info('bases[0]: %s' % str(bases[0].__dict__)) if GENERIC_ATT2 in namespace: spec = namespace[GENERIC_ATT2] elif bases and GENERIC_ATT2 in bases[0].__dict__: spec = bases[0].__dict__[GENERIC_ATT2] else: spec = {} if spec: name0 = get_name_without_brackets(name_orig) name = f"{name0}[%s]" % (",".join(name_for_type_like(_) for _ in spec)) else: name = name_orig # noinspection PyArgumentList cls = super().__new__(mcs, name, bases, namespace, **kwargs) qn = cls.__qualname__.replace(name_orig, name) setattr(cls, "__qualname__", qn) setattr(cls, "__module__", mcs.__module__) setattr(cls, GENERIC_ATT2, spec) return cls from typing import Optional class Fake: symbols: dict myt: type def __init__(self, myt, symbols: dict): self.myt = myt n = name_for_type_like(myt) self.name_without = get_name_without_brackets(n) self.symbols = symbols def __getitem__(self, item: type) -> type: n = name_for_type_like(item) complete = f"{self.name_without}[{n}]" if complete in self.symbols: return self.symbols[complete] # noinspection PyUnresolvedReferences return self.myt[item] def resolve_types( T, locals_=None, refs: Tuple = (), nrefs: Optional[Dict[str, Any]] = None ): if nrefs is None: nrefs = {} assert is_dataclass(T) # rl = RecLogger() if locals_ is None: locals_ = {} symbols = dict(locals_) for k, v in nrefs.items(): symbols[k] = v others = getattr(T, DEPENDS_ATT, ()) for t in (T,) + refs + others: n = name_for_type_like(t) symbols[n] = t # logger.info(f't = {t} n {n}') name_without = get_name_without_brackets(n) # if name_without in ['Union', 'Dict', ]: # # FIXME please add more here # continue if name_without not in symbols: symbols[name_without] = Fake(t, symbols) # else: # pass for x in getattr(T, GENERIC_ATT2, ()): if hasattr(x, "__name__"): symbols[x.__name__] = x # logger.debug(f'symbols: {symbols}') annotations: Dict[str, TypeLike] = getattr(T, "__annotations__", {}) for k, v in annotations.items(): if not isinstance(v, str) and is_ClassVar(v): continue # XXX v = cast(TypeLike, v) try: r = replace_typevars(v, bindings={}, symbols=symbols) # rl.p(f'{k!r} -> {v!r} -> {r!r}') annotations[k] = r except NameError: msg = ( f"resolve_type({T.__name__}):" f' Cannot resolve names for attribute "{k}" = {v!r}.' ) # msg += f'\n symbols: {symbols}' # msg += '\n\n' + indent(traceback.format_exc(), '', '> ') # raise NameError(msg) from e logger.warning(msg) continue except TypeError as e: # pragma: no cover msg = f'Cannot resolve type for attribute "{k}".' raise ZTypeError(msg) from e for f in fields(T): assert f.name in annotations # msg = f'Cannot get annotation for field {f.name!r}' # logger.warning(msg) # continue f.type = annotations[f.name] def type_check(type_self: type, k: str, T_expected: type, value_found: object): try: T_found = type(value_found) simple = T_found in [int, float, bool, str, bytes, Decimal, datetime] definitely_exclude = T_found in [dict, list, tuple] do_it = (not definitely_exclude) and ( ZuperTypingGlobals.enable_type_checking_difficult or simple ) if do_it: # fail = T_found.__name__ != T_expected.__name__ and not isinstance(value_found, T_expected) ok = can_be_used_as2(T_found, T_expected) if not ok: # pragma: no cover msg = f"The field is not of the expected value" # warnings.warn(msg, stacklevel=3) raise ZValueError( msg, type_self=type_self, field=k, expected_type=T_expected, found_type=T_found, found_value=value_found, why=ok, ) except TypeError as e: # pragma: no cover msg = f"Cannot judge annotation of {k} (supposedly {value_found}." if sys.version_info[:2] == (3, 6): # FIXME: warn return logger.error(msg) raise TypeError(msg) from e def make_type(cls: type, bindings, symbols=None) -> type: if symbols is None: symbols = {} symbols = dict(symbols) assert not is_NewType(cls) if not bindings: return cls cache_key = (str(cls), str(bindings)) if cache_enabled: if cache_key in MakeTypeCache.cache: # print(f'using cached value for {cache_key}') return MakeTypeCache.cache[cache_key] generic_att2 = getattr(cls, GENERIC_ATT2, ()) assert isinstance(generic_att2, tuple) recur = lambda _: replace_typevars(_, bindings=bindings, symbols=symbols) annotations = getattr(cls, "__annotations__", {}) name_without = get_name_without_brackets(cls.__name__) def param_name(x: type) -> str: x2 = recur(x) return name_for_type_like(x2) if generic_att2: name2 = "%s[%s]" % (name_without, ",".join(param_name(_) for _ in generic_att2)) else: name2 = name_without try: cls2 = type(name2, (cls,), {"need": lambda: None}) # logger.info(f'Created class {cls2} ({name2}) and set qualname {cls2.__qualname__}') except TypeError as e: # pragma: no cover msg = f'Cannot create derived class "{name2}" from {cls!r}' raise TypeError(msg) from e symbols[name2] = cls2 symbols[cls.__name__] = cls2 # also MyClass[X] should resolve to the same MakeTypeCache.cache[cache_key] = cls2 class Fake2: def __getitem__(self, item): n = name_for_type_like(item) complete = f"{name_without}[{n}]" if complete in symbols: return symbols[complete] # noinspection PyUnresolvedReferences return cls[item] if name_without not in symbols: symbols[name_without] = Fake2() for T, U in bindings.items(): symbols[T.__name__] = U if hasattr(U, "__name__"): # dict does not have name symbols[U.__name__] = U # first of all, replace the bindings in the generic_att generic_att2_new = tuple(recur(_) for _ in generic_att2) # logger.debug( # f"creating derived class {name2} with abstract method need() because # generic_att2_new = {generic_att2_new}") # rl.p(f' generic_att2_new: {generic_att2_new}') # pprint(f'\n\n{cls.__name__}') # pprint(f'binding', bindings=str(bindings)) # pprint(f'symbols', **symbols) new_annotations = {} # logger.info(f'annotations ({annotations}) ') for k, v0 in annotations.items(): v = recur(v0) # print(f'{v0!r} -> {v!r}') if is_ClassVar(v): s = get_ClassVar_arg(v) if is_Type(s): st = get_Type_arg(s) concrete = recur(st) # logger.info(f'is_Type ({s}) -> {concrete}') # concrete = st new_annotations[k] = ClassVar[type] setattr(cls2, k, concrete) else: s2 = recur(s) new_annotations[k] = ClassVar[s2] else: new_annotations[k] = v # logger.info(f'new_annotations {new_annotations}') # pprint(' new annotations', **new_annotations) original__post_init__ = getattr(cls, "__post_init__", None) if enable_type_checking: def __post_init__(self): # do it first (because they might change things around) if original__post_init__ is not None: original__post_init__(self) for k, T_expected in new_annotations.items(): if is_ClassVar(T_expected): continue if isinstance(T_expected, type): val = getattr(self, k) type_check(type(self), k=k, value_found=val, T_expected=T_expected) # important: do it before dataclass setattr(cls2, "__post_init__", __post_init__) cls2.__annotations__ = new_annotations # logger.info('new annotations: %s' % new_annotations) if is_dataclass(cls): # note: need to have set new annotations # pprint('creating dataclass from %s' % cls2) doc = getattr(cls2, "__doc__", None) cls2 = dataclass(cls2, unsafe_hash=True) setattr(cls2, "__doc__", doc) else: # noinspection PyUnusedLocal def init_placeholder(self, *args, **kwargs): if args or kwargs: msg = ( f"Default constructor of {cls2.__name__} does not know what to do with " f"" f"" f"arguments." ) msg += f"\nargs: {args!r}\nkwargs: {kwargs!r}" msg += f"\nself: {self}" msg += f"\nself: {dir(type(self))}" msg += f"\nself: {type(self)}" raise NoConstructorImplemented(msg) if cls.__init__ == object.__init__: setattr(cls2, "__init__", init_placeholder) cls2.__module__ = cls.__module__ setattr(cls2, "__name__", name2) qn = cls.__qualname__ qn0, sep, _ = qn.rpartition(".") if not sep: sep = "" setattr(cls2, "__qualname__", qn0 + sep + name2) setattr(cls2, BINDINGS_ATT, bindings) setattr(cls2, GENERIC_ATT2, generic_att2_new) MakeTypeCache.cache[cache_key] = cls2 # logger.info(f'started {cls}; hash is {cls.__hash__}') # logger.info(f'specialized {cls2}; hash is {cls2.__hash__}') # ztinfo("make_type", cls=cls, bindings=bindings, cls2=cls2) return cls2
zuper-typing-z5
/zuper-typing-z5-5.3.0.tar.gz/zuper-typing-z5-5.3.0/src/zuper_typing/zeneric2.py
zeneric2.py
import typing from dataclasses import dataclass as dataclass_orig, Field, is_dataclass from typing import ( Any, cast, Dict, Iterable, Iterator, List, Optional, Sequence, Set, Tuple, Type, TYPE_CHECKING, TypeVar, Union, ) from .aliases import TypeLike from .constants import NAME_ARG, PYTHON_36 paranoid = False def is_TypeLike(x: object) -> bool: if isinstance(x, type): return True else: # noinspection PyTypeChecker return ( is_SpecialForm(x) or is_ClassVar(x) or is_MyNamedArg(x) or is_Type(x) or is_TypeVar(x) ) def is_SpecialForm(x: TypeLike) -> bool: """ Does not include: ClassVar, NamedArg, Type, TypeVar Does include: ForwardRef, NewType, """ if ( is_Any(x) or is_Callable(x) or is_Dict(x) or is_Tuple(x) or is_ForwardRef(x) or is_Iterable(x) or is_Iterator(x) or is_List(x) or is_NewType(x) or is_Optional(x) or is_Sequence(x) or is_Set(x) or is_Tuple(x) or is_Union(x) ): return True return False # noinspection PyProtectedMember def is_Optional(x: TypeLike) -> bool: if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences return ( isinstance(x, typing._Union) and len(x.__args__) >= 2 and x.__args__[-1] is type(None) ) else: # noinspection PyUnresolvedReferences return ( isinstance(x, typing._GenericAlias) and (getattr(x, "__origin__") is Union) and len(x.__args__) >= 2 and x.__args__[-1] is type(None) ) X = TypeVar("X") def get_Optional_arg(x: Type[Optional[X]]) -> Type[X]: assert is_Optional(x) args = x.__args__ if len(args) == 2: return args[0] else: return make_Union(*args[:-1]) # return x.__args__[0] def is_Union(x: TypeLike) -> bool: """ Union[X, None] is not considered a Union""" if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences return not is_Optional(x) and isinstance(x, typing._Union) else: # noinspection PyUnresolvedReferences return ( not is_Optional(x) and isinstance(x, typing._GenericAlias) and (x.__origin__ is Union) ) def get_Union_args(x: TypeLike) -> Tuple[TypeLike, ...]: assert is_Union(x), x # noinspection PyUnresolvedReferences return tuple(x.__args__) def key_for_sorting_types(y: TypeLike) -> tuple: if is_TypeVar(y): return (1, get_TypeVar_name(y)) elif is_dataclass(y): return (2, name_for_type_like(y)) elif y is type(None): return (3, "") else: return (0, name_for_type_like(y)) def remove_duplicates(a: Tuple[TypeLike]) -> Tuple[TypeLike]: done = [] for _ in a: assert is_TypeLike(_), a if _ not in done: done.append(_) return tuple(done) def make_Union(*a: TypeLike) -> TypeLike: from zuper_typing.type_algebra import unroll_union r = () for _ in a: assert is_TypeLike(_), a r = r + unroll_union(_) a = r if len(a) == 0: raise ValueError("empty") a = remove_duplicates(a) if len(a) == 1: return a[0] # print(list(map(key_for_sorting_types, a))) if type(None) in a: others = tuple(_ for _ in a if _ is not type(None)) return Optional[make_Union(*others)] a = tuple(sorted(a, key=key_for_sorting_types)) if len(a) == 2: x = Union[a[0], a[1]] elif len(a) == 3: x = Union[a[0], a[1], a[2]] elif len(a) == 4: x = Union[a[0], a[1], a[2], a[3]] elif len(a) == 5: x = Union[a[0], a[1], a[2], a[3], a[4]] else: x = Union.__getitem__(tuple(a)) return x TUPLE_EMPTY_ATTR = "__empty__" class Caches: tuple_caches = {} def make_VarTuple(a: Type[X]) -> Type[Tuple[X, ...]]: args = (a, ...) res = make_Tuple(*args) return res class DummyForEmpty: pass def make_Tuple(*a: TypeLike) -> Type[Tuple]: for _ in a: if isinstance(_, tuple): raise ValueError(a) if a in Caches.tuple_caches: return Caches.tuple_caches[a] if len(a) == 0: x = Tuple[DummyForEmpty] setattr(x, TUPLE_EMPTY_ATTR, True) elif len(a) == 1: x = Tuple[a[0]] elif len(a) == 2: x = Tuple[a[0], a[1]] elif len(a) == 3: x = Tuple[a[0], a[1], a[2]] elif len(a) == 4: x = Tuple[a[0], a[1], a[2], a[3]] elif len(a) == 5: x = Tuple[a[0], a[1], a[2], a[3], a[4]] else: if PYTHON_36: # pragma: no cover x = Tuple[a] else: # NOTE: actually correct # noinspection PyArgumentList x = Tuple.__getitem__(tuple(a)) Caches.tuple_caches[a] = x return x def _check_valid_arg(x: Any) -> None: if not paranoid: return if isinstance(x, str): # pragma: no cover msg = f"The annotations must be resolved: {x!r}" raise ValueError(msg) def is_ForwardRef(x: TypeLike) -> bool: _check_valid_arg(x) if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences return isinstance(x, typing._ForwardRef) else: # noinspection PyUnresolvedReferences return isinstance(x, typing.ForwardRef) class CacheFor: cache = {} def make_ForwardRef(n: str) -> TypeLike: if n in CacheFor.cache: return CacheFor.cache[n] if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences res = typing._ForwardRef(n) else: # noinspection PyUnresolvedReferences res = typing.ForwardRef(n) CacheFor.cache[n] = res return res def get_ForwardRef_arg(x: TypeLike) -> str: assert is_ForwardRef(x) # noinspection PyUnresolvedReferences return x.__forward_arg__ def is_Any(x: TypeLike) -> bool: _check_valid_arg(x) if PYTHON_36: # pragma: no cover return x is Any else: # noinspection PyUnresolvedReferences return isinstance(x, typing._SpecialForm) and x._name == "Any" class CacheTypeVar: cache = {} if TYPE_CHECKING: make_TypeVar = TypeVar else: def make_TypeVar( name: str, *, bound: Optional[type] = None, contravariant: bool = False, covariant: bool = False, ) -> TypeVar: key = (name, bound, contravariant, covariant) if key in CacheTypeVar.cache: return CacheTypeVar.cache[key] # noinspection PyTypeHints res = TypeVar( name, bound=bound, contravariant=contravariant, covariant=covariant ) CacheTypeVar.cache[key] = res return res def is_TypeVar(x: TypeLike) -> bool: return isinstance(x, typing.TypeVar) def get_TypeVar_bound(x: TypeVar) -> TypeLike: assert is_TypeVar(x), x bound = x.__bound__ if bound is None: return object else: return bound def get_TypeVar_name(x: TypeVar) -> str: assert is_TypeVar(x), x return x.__name__ def is_ClassVar(x: TypeLike) -> bool: _check_valid_arg(x) if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences return isinstance(x, typing._ClassVar) else: # noinspection PyUnresolvedReferences return isinstance(x, typing._GenericAlias) and (x.__origin__ is typing.ClassVar) def get_ClassVar_arg(x: TypeLike) -> TypeLike: # cannot put ClassVar assert is_ClassVar(x), x if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences return x.__type__ else: # noinspection PyUnresolvedReferences return x.__args__[0] def get_ClassVar_name(x: TypeLike) -> str: # cannot put ClassVar assert is_ClassVar(x), x s = name_for_type_like(get_ClassVar_arg(x)) return f"ClassVar[{s}]" def is_Type(x: TypeLike) -> bool: _check_valid_arg(x) if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences return (x is typing.Type) or ( isinstance(x, typing.GenericMeta) and (x.__origin__ is typing.Type) ) else: # noinspection PyUnresolvedReferences return (x is typing.Type) or ( isinstance(x, typing._GenericAlias) and (x.__origin__ is type) ) def is_NewType(x: TypeLike) -> bool: _check_valid_arg(x) # if PYTHON_36: # pragma: no cover # # noinspection PyUnresolvedReferences # return (x is typing.Type) or (isinstance(x, typing.GenericMeta) and (x.__origin__ # is typing.Type)) # else: # return (x is typing.Type) or (isinstance(x, typing._GenericAlias) and (x.__origin__ is # type)) return hasattr(x, "__supertype__") def get_NewType_arg(x: TypeLike) -> TypeLike: assert is_NewType(x), x # noinspection PyUnresolvedReferences return x.__supertype__ def get_NewType_name(x: TypeLike) -> str: return x.__name__ def get_NewType_repr(x: TypeLike) -> str: n = get_NewType_name(x) p = get_NewType_arg(x) if is_Any(p) or p is object: return f"NewType({n!r})" else: sp = name_for_type_like(p) return f"NewType({n!r}, {sp})" def is_TupleLike(x: TypeLike) -> bool: from .my_dict import is_CustomTuple return is_Tuple(x) or x is tuple or is_CustomTuple(x) def is_FixedTupleLike(x: TypeLike) -> bool: from .my_dict import is_CustomTuple return is_FixedTuple(x) or is_CustomTuple(x) def is_Tuple(x: TypeLike) -> bool: _check_valid_arg(x) if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences return isinstance(x, typing.TupleMeta) else: # noinspection PyUnresolvedReferences return isinstance(x, typing._GenericAlias) and (x._name == "Tuple") def is_FixedTuple(x: TypeLike) -> bool: if not is_Tuple(x): return False x = cast(Type[Tuple], x) ts = get_tuple_types(x) # if len(ts) == 0: # return False if len(ts) == 2 and ts[-1] is ...: return False else: return True def is_VarTuple(x: TypeLike) -> bool: if x is tuple: return True if not is_Tuple(x): return False x = cast(Type[Tuple], x) ts = get_tuple_types(x) if len(ts) == 2 and ts[-1] is ...: return True else: return False def get_FixedTuple_args(x: Type[Tuple]) -> Tuple[TypeLike, ...]: assert is_FixedTuple(x), x return get_tuple_types(x) def get_FixedTupleLike_args(x: TypeLike) -> Tuple[TypeLike, ...]: assert is_FixedTupleLike(x), x if is_FixedTuple(x): x = cast(Type[Tuple], x) return get_tuple_types(x) from .my_dict import is_CustomTuple, get_CustomTuple_args, CustomTuple if is_CustomTuple(x): x = cast(Type[CustomTuple], x) return get_CustomTuple_args(x) assert False, x def is_VarTuple_canonical(x: Type[Tuple]) -> bool: return (x is not tuple) and (x is not Tuple) def is_FixedTuple_canonical(x: Type[Tuple]) -> bool: return (x is not tuple) and (x is not Tuple) def is_FixedTupleLike_canonical(x: Type[Tuple]) -> bool: return (x is not tuple) and (x is not Tuple) def get_VarTuple_arg(x: Type[Tuple[X, ...]]) -> Type[X]: if x is tuple: return Any assert is_VarTuple(x), x ts = get_tuple_types(x) # if len(ts) == 0: # pragma: no cover # return Any return ts[0] def is_generic_alias(x: TypeLike, name: str) -> bool: # noinspection PyUnresolvedReferences return isinstance(x, typing._GenericAlias) and (x._name == name) def is_List(x: TypeLike) -> bool: _check_valid_arg(x) if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences return ( x is typing.List or isinstance(x, typing.GenericMeta) and x.__origin__ is typing.List ) else: return is_generic_alias(x, "List") def is_Iterator(x: TypeLike) -> bool: _check_valid_arg(x) if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences return ( x is typing.Iterator or isinstance(x, typing.GenericMeta) and x.__origin__ is typing.Iterator ) else: return is_generic_alias(x, "Iterator") def is_Iterable(x: TypeLike) -> bool: _check_valid_arg(x) if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences return ( x is typing.Iterable or isinstance(x, typing.GenericMeta) and x.__origin__ is typing.Iterable ) else: return is_generic_alias(x, "Iterable") def is_Sequence(x: TypeLike) -> bool: _check_valid_arg(x) if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences return ( x is typing.Sequence or isinstance(x, typing.GenericMeta) and x.__origin__ is typing.Sequence ) else: return is_generic_alias(x, "Sequence") def is_placeholder_typevar(x: TypeLike) -> bool: return is_TypeVar(x) and get_TypeVar_name(x) in ["T", "T_co"] def get_Set_arg(x: Type[Set]) -> TypeLike: assert is_Set(x) if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences if x is typing.Set: return Any # noinspection PyUnresolvedReferences t = x.__args__[0] if is_placeholder_typevar(t): return Any return t def get_List_arg(x: Type[List[X]]) -> Type[X]: assert is_List(x), x if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences if x.__args__ is None: return Any # noinspection PyUnresolvedReferences t = x.__args__[0] if is_placeholder_typevar(t): return Any return t def is_List_canonical(x: Type[List]) -> bool: assert is_List(x), x if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences if x.__args__ is None: return False # noinspection PyUnresolvedReferences t = x.__args__[0] if is_placeholder_typevar(t): return False return True _K = TypeVar("_K") _V = TypeVar("_V") def get_Dict_args(T: Type[Dict[_K, _V]]) -> Tuple[Type[_K], Type[_V]]: assert is_Dict(T), T if T is Dict: return Any, Any # noinspection PyUnresolvedReferences K, V = T.__args__ if PYTHON_36: # pragma: no cover if is_placeholder_typevar(K): K = Any if is_placeholder_typevar(V): V = Any return K, V _X = TypeVar("_X") def get_Iterator_arg(x: TypeLike) -> TypeLike: # PyCharm has problems assert is_Iterator(x), x # noinspection PyUnresolvedReferences if x.__args__ is None: return Any # noinspection PyUnresolvedReferences t = x.__args__[0] if is_placeholder_typevar(t): return Any return t def get_Iterable_arg(x: TypeLike) -> TypeLike: # PyCharm has problems assert is_Iterable(x), x # noinspection PyUnresolvedReferences if x.__args__ is None: return Any # noinspection PyUnresolvedReferences t = x.__args__[0] if is_placeholder_typevar(t): return Any return t def get_Sequence_arg(x: Type[Sequence[_X]]) -> Type[_X]: assert is_Sequence(x), x # noinspection PyUnresolvedReferences if x.__args__ is None: return Any # noinspection PyUnresolvedReferences t = x.__args__[0] if is_placeholder_typevar(t): return Any return t def get_Type_arg(x: TypeLike) -> TypeLike: assert is_Type(x) if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences if x.__args__ is None: return type # noinspection PyUnresolvedReferences return x.__args__[0] def is_Callable(x: TypeLike) -> bool: _check_valid_arg(x) if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences return isinstance(x, typing.CallableMeta) else: return getattr(x, "_name", None) == "Callable" # return hasattr(x, '__origin__') and x.__origin__ is typing.Callable # return isinstance(x, typing._GenericAlias) and x.__origin__.__name__ == "Callable" def is_MyNamedArg(x: object) -> bool: return hasattr(x, NAME_ARG) def get_MyNamedArg_name(x: TypeLike) -> str: assert is_MyNamedArg(x), x return getattr(x, NAME_ARG) def is_Dict(x: TypeLike) -> bool: _check_valid_arg(x) if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences return ( x is Dict or isinstance(x, typing.GenericMeta) and x.__origin__ is typing.Dict ) else: return is_generic_alias(x, "Dict") def is_Set(x: TypeLike) -> bool: _check_valid_arg(x) if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences if x is typing.Set: return True # noinspection PyUnresolvedReferences return isinstance(x, typing.GenericMeta) and x.__origin__ is typing.Set else: return is_generic_alias(x, "Set") def get_Dict_name(T: Type[Dict]) -> str: assert is_Dict(T), T K, V = get_Dict_args(T) return get_Dict_name_K_V(K, V) def get_Dict_name_K_V(K: TypeLike, V: TypeLike) -> str: return "Dict[%s,%s]" % (name_for_type_like(K), name_for_type_like(V)) def get_Set_name_V(V: TypeLike) -> str: return "Set[%s]" % (name_for_type_like(V)) def get_Union_name(V: TypeLike) -> str: return "Union[%s]" % ",".join(name_for_type_like(_) for _ in get_Union_args(V)) def get_List_name(V: Type[List]) -> str: v = get_List_arg(V) return "List[%s]" % name_for_type_like(v) def get_Type_name(V: TypeLike) -> str: v = get_Type_arg(V) return "Type[%s]" % name_for_type_like(v) def get_Iterator_name(V: Type[Iterator]) -> str: # noinspection PyTypeChecker v = get_Iterator_arg(V) return "Iterator[%s]" % name_for_type_like(v) def get_Iterable_name(V: Type[Iterable[X]]) -> str: # noinspection PyTypeChecker v = get_Iterable_arg(V) return "Iterable[%s]" % name_for_type_like(v) def get_Sequence_name(V: Type[Sequence]) -> str: v = get_Sequence_arg(V) return "Sequence[%s]" % name_for_type_like(v) def get_Optional_name(V: TypeLike) -> str: # cannot use Optional as type arg v = get_Optional_arg(V) return "Optional[%s]" % name_for_type_like(v) def get_Set_name(V: Type[Set]) -> str: v = get_Set_arg(V) return "Set[%s]" % name_for_type_like(v) def get_Tuple_name(V: Type[Tuple]) -> str: return "Tuple[%s]" % ",".join(name_for_type_like(_) for _ in get_tuple_types(V)) def get_FixedTupleLike_name(V: Type[Tuple]) -> str: return "Tuple[%s]" % ",".join( name_for_type_like(_) for _ in get_FixedTupleLike_args(V) ) def get_tuple_types(V: Type[Tuple]) -> Tuple[TypeLike, ...]: if V is tuple: return Any, ... if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences if V.__args__ is None: return Any, ... # noinspection PyUnresolvedReferences args = V.__args__ # XXX if args == (DummyForEmpty,): return () if args == (): if hasattr(V, TUPLE_EMPTY_ATTR): return () else: return Any, ... else: return args def name_for_type_like(x: TypeLike) -> str: from .my_dict import is_DictLike, get_SetLike_name from .my_dict import is_SetLike from .my_dict import get_DictLike_name from .uninhabited import is_Uninhabited if is_Any(x): return "Any" elif isinstance(x, typing.TypeVar): return x.__name__ elif x is type(None): return "NoneType" elif is_Union(x): return get_Union_name(x) elif is_List(x): x = cast(Type[List], x) return get_List_name(x) elif is_Iterator(x): x = cast(Type[Iterator], x) # noinspection PyTypeChecker return get_Iterator_name(x) elif is_Iterable(x): x = cast(Type[Iterable], x) # noinspection PyTypeChecker return get_Iterable_name(x) elif is_Tuple(x): x = cast(Type[Tuple], x) return get_Tuple_name(x) elif is_Set(x): x = cast(Type[Set], x) return get_Set_name(x) elif is_SetLike(x): x = cast(Type[Set], x) return get_SetLike_name(x) elif is_Dict(x): x = cast(Type[Dict], x) return get_Dict_name(x) elif is_DictLike(x): x = cast(Type[Dict], x) return get_DictLike_name(x) elif is_Type(x): return get_Type_name(x) elif is_ClassVar(x): return get_ClassVar_name(x) elif is_Sequence(x): x = cast(Type[Sequence], x) return get_Sequence_name(x) elif is_Optional(x): return get_Optional_name(x) elif is_NewType(x): return get_NewType_repr(x) elif is_ForwardRef(x): a = get_ForwardRef_arg(x) return f"ForwardRef({a!r})" elif is_Uninhabited(x): return "!" elif is_Callable(x): info = get_Callable_info(x) # params = ','.join(name_for_type_like(p) for p in info.parameters_by_position) def ps(k, v): if k.startswith("__"): return name_for_type_like(v) else: return f"NamedArg({name_for_type_like(v)},{k!r})" params = ",".join(ps(k, v) for k, v in info.parameters_by_name.items()) ret = name_for_type_like(info.returns) return f"Callable[[{params}],{ret}]" elif x is typing.IO: return str(x) # TODO: should get the attribute elif hasattr(x, "__name__"): # logger.info(f'not matching __name__ {type(x)} {x!r}') return x.__name__ else: # logger.info(f'not matching {type(x)} {x!r}') return str(x) # do not make a dataclass class CallableInfo: parameters_by_name: Dict[str, TypeLike] parameters_by_position: Tuple[TypeLike, ...] ordering: Tuple[str, ...] returns: TypeLike def __init__(self, parameters_by_name, parameters_by_position, ordering, returns): for k, v in parameters_by_name.items(): assert not is_MyNamedArg(v), v for v in parameters_by_position: assert not is_MyNamedArg(v), v self.parameters_by_name = parameters_by_name self.parameters_by_position = parameters_by_position self.ordering = ordering self.returns = returns def __repr__(self) -> str: return ( f"CallableInfo({self.parameters_by_name!r}, {self.parameters_by_position!r}, " f"{self.ordering}, {self.returns})" ) def replace(self, f: typing.Callable[[Any], Any]) -> "CallableInfo": parameters_by_name = {k: f(v) for k, v in self.parameters_by_name.items()} parameters_by_position = tuple(f(v) for v in self.parameters_by_position) ordering = self.ordering returns = f(self.returns) return CallableInfo( parameters_by_name, parameters_by_position, ordering, returns ) def as_callable(self) -> typing.Callable: args = [] for k, v in self.parameters_by_name.items(): # if is_MyNamedArg(v): # # try: # v = v.original # TODO: add MyNamedArg args.append(v) # noinspection PyTypeHints return typing.Callable[args, self.returns] def get_Callable_info(x: Type[typing.Callable]) -> CallableInfo: assert is_Callable(x), x parameters_by_name = {} parameters_by_position = [] ordering = [] args = x.__args__ if args: returns = args[-1] rest = args[:-1] else: returns = Any rest = () for i, a in enumerate(rest): if is_MyNamedArg(a): name = get_MyNamedArg_name(a) t = a.original # t = a else: name = f"{i}" t = a parameters_by_name[name] = t ordering.append(name) parameters_by_position.append(t) return CallableInfo( parameters_by_name=parameters_by_name, parameters_by_position=tuple(parameters_by_position), ordering=tuple(ordering), returns=returns, ) def get_fields_including_static(x: Type[dataclass_orig]) -> Dict[str, Field]: """ returns the fields including classvars """ from dataclasses import _FIELDS fields = getattr(x, _FIELDS) return fields
zuper-typing-z5
/zuper-typing-z5-5.3.0.tar.gz/zuper-typing-z5-5.3.0/src/zuper_typing/annotations_tricks.py
annotations_tricks.py
from typing import Tuple from zuper_typing.aliases import TypeLike from zuper_typing.annotations_tricks import ( name_for_type_like, key_for_sorting_types, is_TypeLike, ) from .constants import INTERSECTION_ATT, PYTHON_36 if PYTHON_36: # pragma: no cover class IntersectionMeta(type): def __getitem__(self, params): return make_Intersection(params) class Intersection(metaclass=IntersectionMeta): pass else: class Intersection: @classmethod def __class_getitem__(cls, params): # return Intersection_item(cls, params) return make_Intersection(params) class IntersectionCache: use_cache = True make_intersection_cache = {} def make_Intersection(ts: Tuple[TypeLike, ...]) -> TypeLike: if len(ts) == 0: return object done = [] for t in ts: assert is_TypeLike(t), ts if t not in done: done.append(t) done = sorted(done, key=key_for_sorting_types) ts = tuple(done) if len(ts) == 1: return ts[0] if IntersectionCache.use_cache: if ts in IntersectionCache.make_intersection_cache: return IntersectionCache.make_intersection_cache[ts] class IntersectionBase(type): def __eq__(self, other): if is_Intersection(other): t1 = get_Intersection_args(self) t2 = get_Intersection_args(other) return set(t1) == set(t2) return False def __hash__(cls): # pragma: no cover return 1 # XXX # logger.debug(f'here ___eq__ {self} {other} {issubclass(other, CustomList)} = {res}') attrs = {INTERSECTION_ATT: ts} name = "Intersection[%s]" % ",".join(name_for_type_like(_) for _ in ts) res = IntersectionBase(name, (), attrs) IntersectionCache.make_intersection_cache[ts] = res return res def is_Intersection(T: TypeLike) -> bool: return hasattr(T, INTERSECTION_ATT) def get_Intersection_args(T: TypeLike) -> Tuple[TypeLike, ...]: assert is_Intersection(T) return getattr(T, INTERSECTION_ATT)
zuper-typing-z5
/zuper-typing-z5-5.3.0.tar.gz/zuper-typing-z5-5.3.0/src/zuper_typing/my_intersection.py
my_intersection.py
from datetime import datetime from decimal import Decimal from numbers import Number from typing import ( Any, cast, ClassVar, Dict, Iterator, List, Optional, Sequence, Set, Tuple, Type, Union, ) from zuper_typing.literal import is_Literal from .aliases import TypeLike from .annotations_tricks import ( get_Callable_info, get_ClassVar_arg, get_FixedTupleLike_args, get_ForwardRef_arg, get_Iterator_arg, get_List_arg, get_Optional_arg, get_Sequence_arg, get_Type_arg, get_TypeVar_name, get_Union_args, get_VarTuple_arg, is_Any, is_Callable, is_ClassVar, is_FixedTupleLike, is_FixedTupleLike_canonical, is_ForwardRef, is_Iterator, is_List, is_List_canonical, is_NewType, is_Optional, is_Sequence, is_Type, is_TypeVar, is_Union, is_VarTuple, is_VarTuple_canonical, make_Tuple, make_Union, make_VarTuple, ) from .my_dict import ( CustomList, get_CustomList_arg, get_DictLike_args, get_ListLike_arg, get_SetLike_arg, is_CustomList, is_DictLike, is_DictLike_canonical, is_ListLike, is_ListLike_canonical, is_SetLike, is_SetLike_canonical, make_dict, make_list, make_set, ) from .my_intersection import get_Intersection_args, is_Intersection, make_Intersection from .uninhabited import is_Uninhabited def get_name_without_brackets(name: str) -> str: if "[" in name: return name[: name.index("[")] else: return name class NoConstructorImplemented(TypeError): pass def get_default_attrs(): return dict( Any=Any, Optional=Optional, Union=Union, Tuple=Tuple, List=List, Set=Set, Dict=Dict, ) def canonical(typelike: TypeLike) -> TypeLike: return replace_typevars(typelike, bindings={}, symbols={}, make_canonical=True) def replace_typevars( cls: TypeLike, *, bindings: Dict[Any, TypeLike], symbols: Dict[str, TypeLike], make_canonical: bool = False, ) -> TypeLike: from .logging import logger r = lambda _: replace_typevars(_, bindings=bindings, symbols=symbols) if cls is type: return type if hasattr(cls, "__name__") and cls.__name__ in symbols: return symbols[cls.__name__] elif (isinstance(cls, str) or is_TypeVar(cls)) and cls in bindings: return bindings[cls] elif hasattr(cls, "__name__") and cls.__name__.startswith("Placeholder"): return cls elif is_TypeVar(cls): name = get_TypeVar_name(cls) for k, v in bindings.items(): if is_TypeVar(k) and get_TypeVar_name(k) == name: return v return cls # return bindings[cls] elif isinstance(cls, str): if cls in symbols: return symbols[cls] g = dict(get_default_attrs()) g.update(symbols) g0 = dict(g) try: return eval(cls, g) except NameError as e: msg = f"Cannot resolve {cls!r}\ng: {list(g0)}" # msg += 'symbols: {list(g0)' raise NameError(msg) from e elif is_NewType(cls): return cls elif is_Type(cls): x = get_Type_arg(cls) r = r(x) if x == r: return cls return Type[r] # return type elif is_DictLike(cls): cls = cast(Type[Dict], cls) is_canonical = is_DictLike_canonical(cls) K0, V0 = get_DictLike_args(cls) K = r(K0) V = r(V0) # logger.debug(f'{K0} -> {K}; {V0} -> {V}') if (K0, V0) == (K, V) and (is_canonical or not make_canonical): return cls res = make_dict(K, V) return res elif is_SetLike(cls): cls = cast(Type[Set], cls) is_canonical = is_SetLike_canonical(cls) V0 = get_SetLike_arg(cls) V = r(V0) if V0 == V and (is_canonical or not make_canonical): return cls return make_set(V) elif is_CustomList(cls): cls = cast(Type[CustomList], cls) V0 = get_CustomList_arg(cls) V = r(V0) if V0 == V: return cls return make_list(V) elif is_List(cls): cls = cast(Type[List], cls) arg = get_List_arg(cls) is_canonical = is_List_canonical(cls) arg2 = r(arg) if arg == arg2 and (is_canonical or not make_canonical): return cls return List[arg2] elif is_ListLike(cls): cls = cast(Type[List], cls) arg = get_ListLike_arg(cls) is_canonical = is_ListLike_canonical(cls) arg2 = r(arg) if arg == arg2 and (is_canonical or not make_canonical): return cls return make_list(arg2) # XXX NOTE: must go after CustomDict elif hasattr(cls, "__annotations__"): from zuper_typing.zeneric2 import make_type cls2 = make_type(cls, bindings=bindings, symbols=symbols) # ztinfo("replace_typevars", bindings=bindings, cls=cls, cls2=cls2) # logger.info(f'old cls: {cls.__annotations__}') # logger.info(f'new cls2: {cls2.__annotations__}') return cls2 elif is_ClassVar(cls): is_canonical = True # XXXis_ClassVar_canonical(cls) x = get_ClassVar_arg(cls) r = r(x) if x == r and (is_canonical or not make_canonical): return cls return ClassVar[r] elif is_Iterator(cls): is_canonical = True # is_Iterator_canonical(cls) # noinspection PyTypeChecker x = get_Iterator_arg(cls) r = r(x) if x == r and (is_canonical or not make_canonical): return cls return Iterator[r] elif is_Sequence(cls): is_canonical = True # is_Sequence_canonical(cls) cls = cast(Type[Sequence], cls) x = get_Sequence_arg(cls) r = r(x) if x == r and (is_canonical or not make_canonical): return cls return Sequence[r] elif is_Optional(cls): is_canonical = True # is_Optional_canonical(cls) x = get_Optional_arg(cls) x2 = r(x) if x == x2 and (is_canonical or not make_canonical): return cls return Optional[x2] elif is_Union(cls): # cls = cast(Type[Union], cls) cannot cast xs = get_Union_args(cls) is_canonical = True # is_Union_canonical(cls) ys = tuple(r(_) for _ in xs) if ys == xs and (is_canonical or not make_canonical): return cls return make_Union(*ys) elif is_Intersection(cls): xs = get_Intersection_args(cls) ys = tuple(r(_) for _ in xs) if ys == xs: return cls return make_Intersection(ys) elif is_VarTuple(cls): cls = cast(Type[Tuple], cls) is_canonical = is_VarTuple_canonical(cls) X = get_VarTuple_arg(cls) Y = r(X) if X == Y and (is_canonical or not make_canonical): return cls return make_VarTuple(Y) elif is_FixedTupleLike(cls): cls = cast(Type[Tuple], cls) is_canonical = is_FixedTupleLike_canonical(cls) xs = get_FixedTupleLike_args(cls) ys = tuple(r(_) for _ in xs) if ys == xs and (is_canonical or not make_canonical): return cls return make_Tuple(*ys) elif is_Callable(cls): cinfo = get_Callable_info(cls) cinfo2 = cinfo.replace(r) return cinfo2.as_callable() elif is_ForwardRef(cls): T = get_ForwardRef_arg(cls) if T in symbols: return r(symbols[T]) else: logger.warning(f"could not resolve {cls}") return cls elif cls in ( int, bool, float, Decimal, datetime, str, bytes, Number, type(None), object, ): return cls elif is_Any(cls): return cls elif is_Uninhabited(cls): return cls elif is_Literal(cls): return cls elif isinstance(cls, type): # logger.warning(f"extraneous class {cls}") return cls # elif is_Literal(cls): # return cls else: raise NotImplementedError(cls) # logger.debug(f'Nothing to do with {cls!r} {cls}') # return cls B = Dict[Any, Any] # bug in Python 3.6
zuper-typing-z5
/zuper-typing-z5-5.3.0.tar.gz/zuper-typing-z5-5.3.0/src/zuper_typing/recursive_tricks.py
recursive_tricks.py
from dataclasses import Field, fields, is_dataclass from typing import Dict, List, Optional, Set, Tuple, Type, TypeVar from zuper_commons.types import ZValueError from . import dataclass from .annotations_tricks import ( get_VarTuple_arg, is_VarTuple, ) from .dataclass_info import is_dataclass_instance from .annotations_tricks import ( get_DictLike_args, get_ListLike_arg, get_SetLike_arg, is_DictLike, is_ListLike, is_SetLike, is_FixedTupleLike, get_FixedTupleLike_args, ) __all__ = ["eq", "EqualityResult"] X = TypeVar("X") @dataclass class EqualityResult: result: bool why: "Dict[str, EqualityResult]" a: object b: object msg: Optional[str] = None def __bool__(self) -> bool: return self.result def eq(T: Type[X], a: X, b: X) -> EqualityResult: # logger.info("eq", T=T, a=a, b=b) # todo: tuples if is_dataclass(T): return eq_dataclass(T, a, b) elif is_ListLike(T): return eq_listlike(T, a, b) elif is_FixedTupleLike(T): return eq_tuplelike_fixed(T, a, b) elif is_VarTuple(T): return eq_tuplelike_var(T, a, b) elif is_DictLike(T): return eq_dictlike(T, a, b) elif is_SetLike(T): return eq_setlike(T, a, b) else: if not (a == b): return EqualityResult(result=False, a=a, b=b, why={}, msg="by equality") else: return EqualityResult(result=True, a=a, b=b, why={}) K = TypeVar("K") V = TypeVar("V") def eq_dictlike(T: Type[Dict[K, V]], a: Dict[K, V], b: Dict[K, V]) -> EqualityResult: k1 = set(a) k2 = set(b) if k1 != k2: return EqualityResult(result=False, a=a, b=b, why={}, msg="different keys") _, V = get_DictLike_args(T) why = {} for k in k1: va = a[k] vb = b[k] r = eq(V, va, vb) if not r.result: why[k] = r result = len(why) == 0 return EqualityResult(result=result, why=(why), a=a, b=b) def eq_listlike(T: Type[List[V]], a: List[V], b: List[V]) -> EqualityResult: k1 = len(a) k2 = len(b) if k1 != k2: return EqualityResult(result=False, a=a, b=b, why={}, msg="different length") V = get_ListLike_arg(T) why = {} for i in range(k1): va = a[i] vb = b[i] r = eq(V, va, vb) if not r.result: why[str(i)] = r result = len(why) == 0 return EqualityResult(result=result, why=why, a=a, b=b) def eq_setlike(T: Type[Set[V]], a: Set[V], b: Set[V]) -> EqualityResult: k1 = len(a) k2 = len(b) if k1 != k2: return EqualityResult(result=False, a=a, b=b, why={}, msg="different length") V = get_SetLike_arg(T) why = {} for i, va in enumerate(a): for vb in b: r = eq(V, va, vb) if r: break else: why["a" + str(i)] = EqualityResult(result=False, a=va, b=None, why={}, msg="Missing") for i, vb in enumerate(b): for va in a: r = eq(V, va, vb) if r: break else: why["b" + str(i)] = EqualityResult(result=False, a=None, b=vb, why={}, msg="Missing") result = len(why) == 0 return EqualityResult(result=result, why=why, a=a, b=b) def eq_tuplelike_fixed(T: Type[Tuple], a: Tuple, b: Tuple) -> EqualityResult: assert is_FixedTupleLike(T), T args = get_FixedTupleLike_args(T) n = len(args) k1 = len(a) k2 = len(b) if not (k1 == k2 == n): return EqualityResult(result=False, a=a, b=b, why={}, msg="different length") why = {} for i, V in enumerate(args): va = a[i] vb = b[i] r = eq(V, va, vb) if not r.result: why[str(i)] = r result = len(why) == 0 return EqualityResult(result=result, why=why, a=a, b=b) def eq_tuplelike_var(T: Type[Tuple], a: Tuple, b: Tuple) -> EqualityResult: assert is_VarTuple(T), T V = get_VarTuple_arg(T) k1 = len(a) k2 = len(b) if not (k1 == k2): return EqualityResult(result=False, a=a, b=b, why={}, msg="different length") why = {} for i in range(k1): va = a[i] vb = b[i] r = eq(V, va, vb) if not r.result: why[str(i)] = r result = len(why) == 0 return EqualityResult(result=result, why=why, a=a, b=b) def eq_dataclass(T, a, b): if not is_dataclass(T): # pragma: no cover raise ZValueError(T=T, a=a, b=b) if not is_dataclass_instance(a) or not is_dataclass_instance(b): return EqualityResult(result=False, why={}, a=a, b=b, msg="not even dataclasses") _fields: List[Field] = fields(T) why = {} for f in _fields: va = getattr(a, f.name) vb = getattr(b, f.name) res = eq(f.type, va, vb) if not res.result: why[f.name] = res result = len(why) == 0 return EqualityResult(result=result, why=dict(why), a=a, b=b)
zuper-typing-z6
/zuper-typing-z6-6.2.3.tar.gz/zuper-typing-z6-6.2.3/src/zuper_typing/structural_equalities.py
structural_equalities.py
import datetime from dataclasses import is_dataclass from decimal import Decimal from numbers import Number from typing import Callable, cast, ClassVar, Dict, List, NewType, Optional, Set, Tuple, Type import numpy as np from zuper_commons.types import ZAssertionError from .aliases import TypeLike from .annotations_tricks import ( get_Callable_info, get_ClassVar_arg, get_Dict_args, get_List_arg, get_NewType_arg, get_NewType_name, get_Optional_arg, get_Set_arg, get_Type_arg, get_Union_args, get_VarTuple_arg, is_Any, is_Callable, is_ClassVar, is_Dict, is_ForwardRef, is_List, is_NewType, is_Optional, is_Set, is_Type, is_TypeVar, is_Union, is_VarTuple, make_Tuple, make_Union, ) from .dataclass_info import DataclassInfo, get_dataclass_info, set_dataclass_info from .monkey_patching_typing import my_dataclass from .annotations_tricks import ( CustomDict, CustomList, CustomSet, get_CustomDict_args, get_CustomList_arg, get_CustomSet_arg, is_CustomDict, is_CustomList, is_CustomSet, is_TupleLike, make_dict, make_list, make_set, is_FixedTupleLike, get_FixedTupleLike_args, ) __all__ = ["recursive_type_subst", "check_no_placeholders_left"] def recursive_type_subst( T: TypeLike, f: Callable[[TypeLike], TypeLike], ignore: tuple = () ) -> TypeLike: if T in ignore: # logger.info(f'ignoring {T} in {ignore}') return T r = lambda _: recursive_type_subst(_, f, ignore + (T,)) if is_Optional(T): a = get_Optional_arg(T) a2 = r(a) if a == a2: return T # logger.info(f'Optional unchanged under {f.__name__}: {a} == {a2}') return Optional[a2] elif is_ForwardRef(T): return f(T) elif is_Union(T): ts0 = get_Union_args(T) ts = tuple(r(_) for _ in ts0) if ts0 == ts: # logger.info(f'Union unchanged under {f.__name__}: {ts0} == {ts}') return T return make_Union(*ts) elif is_TupleLike(T): T = cast(Type[Tuple], T) if is_VarTuple(T): X = get_VarTuple_arg(T) X2 = r(X) if X == X2: return T return Tuple[X2, ...] elif is_FixedTupleLike(T): argst = get_FixedTupleLike_args(T) ts = tuple(r(_) for _ in argst) if argst == ts: return T return make_Tuple(*ts) else: assert False elif is_Dict(T): T = cast(Type[Dict], T) K, V = get_Dict_args(T) K2, V2 = r(K), r(V) if (K, V) == (K2, V2): return T return Dict[K, V] # return original_dict_getitem((K, V)) elif is_CustomDict(T): T = cast(Type[CustomDict], T) K, V = get_CustomDict_args(T) K2, V2 = r(K), r(V) if (K, V) == (K2, V2): return T return make_dict(K2, V2) elif is_List(T): T = cast(Type[List], T) V = get_List_arg(T) V2 = r(V) if V == V2: return T return List[V2] elif is_CustomList(T): T = cast(Type[CustomList], T) V = get_CustomList_arg(T) V2 = r(V) if V == V2: return T return make_list(V2) elif is_Set(T): T = cast(Type[Set], T) V = get_Set_arg(T) V2 = r(V) if V == V2: return T return make_set(V2) elif is_CustomSet(T): T = cast(Type[CustomSet], T) V = get_CustomSet_arg(T) V2 = r(V) if V == V2: return T return make_set(V2) elif is_NewType(T): name = get_NewType_name(T) a = get_NewType_arg(T) a2 = r(a) if a == a2: return T return NewType(name, a2) elif is_ClassVar(T): V = get_ClassVar_arg(T) V2 = r(V) if V == V2: return T return ClassVar[V2] elif is_dataclass(T): return recursive_type_subst_dataclass(T, f, ignore) elif T in ( int, bool, float, Decimal, datetime.datetime, bytes, str, type(None), type, np.ndarray, Number, object, ): return f(T) elif is_TypeVar(T): return f(T) elif is_Type(T): V = get_Type_arg(T) V2 = r(V) if V == V2: return T return Type[V2] elif is_Any(T): return f(T) elif is_Callable(T): info = get_Callable_info(T) args = [] for k, v in info.parameters_by_name.items(): # if is_MyNamedArg(v): # # try: # v = v.original # TODO: add MyNamedArg args.append(f(v)) fret = f(info.returns) args = list(args) # noinspection PyTypeHints return Callable[args, fret] # noinspection PyTypeHints elif isinstance(T, type) and "Placeholder" in T.__name__: return f(T) else: # pragma: no cover # raise ZNotImplementedError(T=T) # FIXME return T def recursive_type_subst_dataclass(T, f: Callable[[TypeLike], TypeLike], ignore: tuple = ()): def r(_): return recursive_type_subst(_, f, ignore + (T,)) annotations = dict(getattr(T, "__annotations__", {})) annotations2 = {} nothing_changed = True for k, v0 in list(annotations.items()): v2 = r(v0) nothing_changed &= v0 == v2 annotations2[k] = v2 if nothing_changed: # logger.info(f'Union unchanged under {f.__name__}: {ts0} == {ts}') return T from .zeneric2 import GenericProxy class Base(GenericProxy): pass Base.__annotations__ = annotations2 Base.__module__ = T.__module__ T2 = my_dataclass(Base) for k in annotations: if hasattr(T, k): setattr(T2, k, getattr(T, k)) # always setattr(T2, "__doc__", getattr(T, "__doc__", None)) clsi = get_dataclass_info(T) # bindings2 = {r(k): r(v) for k, v in clsi.bindings.items()} # extra2 = tuple(r(_) for _ in clsi.extra) orig2 = tuple(r(_) for _ in clsi.orig) clsi2 = DataclassInfo(name="", orig=orig2) from .zeneric2 import get_name_for name2 = get_name_for(T.__name__, clsi2) clsi2.name = name2 setattr(T2, "__name__", name2) qualname = getattr(T, "__qualname__") qualname2 = qualname.replace(T.__name__, name2) setattr(T2, "__qualname__", qualname2) set_dataclass_info(T2, clsi2) return T2 def check_no_placeholders_left(T: type): """ Check that there is no Placeholder* left in the type. """ def f(x): if isinstance(x, type) and x.__name__.startswith("Placeholder"): msg = "Found Placeholder" raise ZAssertionError(msg, x=x) return x return recursive_type_subst(T, f)
zuper-typing-z6
/zuper-typing-z6-6.2.3.tar.gz/zuper-typing-z6-6.2.3/src/zuper_typing/assorted_recursive_type_subst.py
assorted_recursive_type_subst.py
from dataclasses import dataclass, field, is_dataclass from datetime import datetime from decimal import Decimal from functools import reduce from numbers import Number from typing import Any, cast, Dict, Iterable, List, Optional, Sequence, Set, Tuple, Type, TypeVar import numpy as np from zuper_commons.text import indent from zuper_commons.types import ( ZAssertionError, ZException, ZNotImplementedError, ZTypeError, ZValueError, ) from . import logger from .aliases import TypeLike from .annotations_tricks import ( get_DictLike_args, get_FixedTupleLike_args, get_ForwardRef_arg, get_Iterable_arg, get_ListLike_arg, get_NewType_arg, get_NewType_name, get_Optional_arg, get_Sequence_arg, get_SetLike_arg, get_tuple_types, get_Type_arg, get_TypeVar_name, get_Union_args, get_VarTuple_arg, is_Any, is_Callable, is_ClassVar, is_DictLike, is_FixedTupleLike, is_ForwardRef, is_Iterable, is_List, is_ListLike, is_Optional, is_Sequence, is_SetLike, is_TupleLike, is_Type, is_TypeVar, is_Union, is_VarTuple, make_dict, make_Tuple, MyStr, ) from .constants import ANNOTATIONS_ATT, ZuperTypingGlobals from .literal import get_Literal_args, is_Literal, make_Literal from .my_intersection import get_Intersection_args, is_Intersection from .type_algebra import Matches, type_sup from .uninhabited import is_Uninhabited __all__ = ["can_be_used_as2", "value_liskov", "CanBeUsed", "check_value_liskov", "type_liskov"] @dataclass class CanBeUsed: result: bool why: str M: Matches matches: Optional[Dict[str, type]] = None reasons: "Dict[str, CanBeUsed]" = field(default_factory=dict) def __post_init__(self): assert isinstance(self.M, Matches), self self.matches = self.M.get_matches() self.reasons = DictStrCan(self.reasons) def __bool__(self): return self.result DictStrCan = make_dict(str, CanBeUsed) class CanBeUsedCache: can_be_used_cache = {} from .annotations_tricks import is_NewType from .get_patches_ import is_placeholder def type_liskov( T1: TypeLike, T2: TypeLike, matches: Optional[Matches] = None, assumptions0: Tuple[Tuple[Any, Any], ...] = (), allow_is_shortcut: bool = True, ) -> CanBeUsed: if matches is None: matches = Matches() else: assert isinstance(matches, Matches), matches if is_placeholder(T1) or is_placeholder(T2): msg = "cannot compare classes with 'Placeholder' in the name (reserved internally)." raise ZValueError(msg, T1=T1, T2=T2) if is_Any(T2): return CanBeUsed(True, "Any", matches) if is_Any(T1): return CanBeUsed(True, "Any", matches) if is_Uninhabited(T1): return CanBeUsed(True, "Empty", matches) if (T1, T2) in assumptions0: return CanBeUsed(True, "By assumption", matches) if allow_is_shortcut: if (T1 is T2) or (T1 == T2): return CanBeUsed(True, "equal", matches) # redundant with above # if is_Any(T1) or is_Any(T2): # return CanBeUsed(True, "Any ignores everything", matches) if T2 is object: return CanBeUsed(True, "object is the top", matches) # cop out for the easy cases assumptions = assumptions0 + ((T1, T2),) if is_NewType(T1) and is_NewType(T2): # special case of same alias t1 = get_NewType_arg(T1) t2 = get_NewType_arg(T2) n1 = get_NewType_name(T1) n2 = get_NewType_name(T2) res = can_be_used_as2(t1, t2, matches, assumptions, allow_is_shortcut=allow_is_shortcut) if res: if n1 == n2: return res if is_NewType(T2): T2 = get_NewType_arg(T2) if is_Literal(T1): v1 = get_Literal_args(T1) if is_Literal(T2): v2 = get_Literal_args(T2) included = all(any(x1 == x2 for x2 in v2) for x1 in v1) if included: return CanBeUsed(True, "included", matches) else: return CanBeUsed(False, "not included", matches) else: t1 = type(v1[0]) return can_be_used_as2(t1, T2, matches, assumptions, allow_is_shortcut=allow_is_shortcut) # logger.info(f'can_be_used_as\n {T1} {T2}\n {assumptions0}') if is_Literal(T2): return CanBeUsed(False, "T1 not literal", matches) if T1 is type(None): if is_Optional(T2): return CanBeUsed(True, "", matches) # This never happens because it is caught by T1 is T2 elif T2 is type(None): return CanBeUsed(True, "", matches) else: msg = f"Needs type(None), got {T2}" return CanBeUsed(False, msg, matches) if is_Union(T1): if is_Union(T2): if get_Union_args(T1) == get_Union_args(T2): return CanBeUsed(True, "same", matches) # can_be_used(Union[A,B], C) # == can_be_used(A,C) and can_be_used(B,C) for t in get_Union_args(T1): can = can_be_used_as2(t, T2, matches, assumptions, allow_is_shortcut=allow_is_shortcut) # logger.info(f'can_be_used_as t = {t} {T2}') if not can.result: msg = f"Cannot match {t}" return CanBeUsed(False, msg, matches) return CanBeUsed(True, "", matches) if is_Union(T2): reasons = [] for t in get_Union_args(T2): can = can_be_used_as2(T1, t, matches, assumptions, allow_is_shortcut=allow_is_shortcut) if can.result: return CanBeUsed(True, f"union match with {t} ", can.M) reasons.append(f"- {t}: {can.why}") msg = f"Cannot use {T1} as any of {T2}:\n" + "\n".join(reasons) return CanBeUsed(False, msg, matches) if is_TypeVar(T2): n2 = get_TypeVar_name(T2) if is_TypeVar(T1): n1 = get_TypeVar_name(T1) if n1 == n2: # TODO: intersection of bounds return CanBeUsed(True, "", matches) else: matches = matches.must_be_subtype_of(n1, T2) # raise ZNotImplementedError(T1=T1,T2=T2) matches = matches.must_be_supertype_of(n2, T1) return CanBeUsed(True, "", matches) if is_Intersection(T1): if is_Intersection(T2): if get_Intersection_args(T1) == get_Intersection_args(T2): return CanBeUsed(True, "same", matches) # Int[a, b] <= Int[C, D] # = Int[a, b] <= C Int[a, b] <= D for t2 in get_Intersection_args(T2): can = can_be_used_as2(T1, t2, matches, assumptions, allow_is_shortcut=allow_is_shortcut) # logger.info(f'can_be_used_as t = {t} {T2}') if not can.result: msg = f"Cannot match {t2}" return CanBeUsed(False, msg, matches) return CanBeUsed(True, "", matches) if is_Intersection(T2): # a <= Int[C, D] # = a <= C and a <= D reasons = [] for t2 in get_Intersection_args(T2): can = can_be_used_as2(T1, t2, matches, assumptions, allow_is_shortcut=allow_is_shortcut) if not can.result: return CanBeUsed(False, f"no match {T1} {t2} ", can.M) msg = f"Cannot use {T1} as any of {T2}:\n" + "\n".join(reasons) return CanBeUsed(False, msg, matches) if is_TypeVar(T1): n1 = get_TypeVar_name(T1) matches = matches.must_be_subtype_of(n1, T2) return CanBeUsed(True, "Any", matches) # TODO: not implemented if is_Optional(T1): t1 = get_Optional_arg(T1) if is_Optional(T2): t2 = get_Optional_arg(T2) return can_be_used_as2(t1, t2, matches, assumptions, allow_is_shortcut=allow_is_shortcut) if T2 is type(None): return CanBeUsed(True, "", matches) return can_be_used_as2(t1, T2, matches, assumptions, allow_is_shortcut=allow_is_shortcut) if is_Optional(T2): t2 = get_Optional_arg(T2) if is_Optional(T1): t1 = get_Optional_arg(T1) return can_be_used_as2(t1, t2, matches, assumptions, allow_is_shortcut=allow_is_shortcut) return can_be_used_as2(T1, t2, matches, assumptions, allow_is_shortcut=allow_is_shortcut) # ---- concrete if T1 is MyStr: if T2 in (str, MyStr): return CanBeUsed(True, "str ~ MyStr", matches) else: return CanBeUsed(False, "MyStr wants str", matches) if T2 is MyStr: if T1 in (str, MyStr): return CanBeUsed(True, "str ~ MyStr", matches) else: return CanBeUsed(False, "MyStr wants str", matches) trivial = (int, str, bool, Decimal, datetime, float, Number) if T1 in trivial: if T2 not in trivial: return CanBeUsed(False, "A trivial cannot be a subclass of non-trivial", matches) if T2 in trivial: if T1 in trivial + (np.float32, np.float64): return CanBeUsed(issubclass(T1, T2), "trivial subclass", matches) # raise ZNotImplementedError(T1=T1, T2=T2) return CanBeUsed(False, f"Not a trivial type (T1={T1}, T2={T2})", matches) if is_DictLike(T2): if not is_DictLike(T1): msg = f"Expecting a dictionary, got {T1}" return CanBeUsed(False, msg, matches) else: T1 = cast(Type[Dict], T1) T2 = cast(Type[Dict], T2) K1, V1 = get_DictLike_args(T1) K2, V2 = get_DictLike_args(T2) rk = can_be_used_as2(K1, K2, matches, assumptions, allow_is_shortcut=allow_is_shortcut) if not rk: return CanBeUsed(False, f"keys {K1} {K2}: {rk}", matches) rv = can_be_used_as2(V1, V2, rk.M, assumptions, allow_is_shortcut=allow_is_shortcut) if not rv: return CanBeUsed(False, f"values {V1} {V2}: {rv}", matches) return CanBeUsed(True, f"ok: {rk} {rv}", rv.M) else: if is_DictLike(T1): msg = "A Dict needs a dictionary" return CanBeUsed(False, msg, matches) assert not is_Union(T2) if is_dataclass(T1): if not is_dataclass(T2): msg = "Second is not dataclass " return CanBeUsed(False, msg, matches) from .zeneric2 import StructuralTyping if isinstance(T2, StructuralTyping): if not isinstance(T1, StructuralTyping): msg = "Not structural typing" return CanBeUsed(False, msg, matches) if is_dataclass(T2): if not is_dataclass(T1): if ZuperTypingGlobals.verbose: msg = f"Expecting dataclass to match to {T2}, got something that is not a " f"dataclass: {T1}" msg += f" union: {is_Union(T1)}" else: # pragma: no cover msg = "not dataclass" return CanBeUsed(False, msg, matches) # h1 = get_type_hints(T1) # h2 = get_type_hints(T2) key = (T1.__module__, T1.__qualname__, T2.__module__, T2.__qualname__) if key in CanBeUsedCache.can_be_used_cache: return CanBeUsedCache.can_be_used_cache[key] h1 = getattr(T1, ANNOTATIONS_ATT, {}) h2 = getattr(T2, ANNOTATIONS_ATT, {}) for k, v2 in h2.items(): if not k in h1: if ZuperTypingGlobals.verbose: msg = ( f'Type {T2}\n requires field "{k}" \n of type {v2} \n but {T1} does ' f"not have it. " ) else: # pragma: no cover msg = k res = CanBeUsed(False, msg, matches) CanBeUsedCache.can_be_used_cache[key] = res return res v1 = h1[k] # XXX if is_ClassVar(v1): continue can = can_be_used_as2(v1, v2, matches, assumptions, allow_is_shortcut=allow_is_shortcut) if not can.result: if ZuperTypingGlobals.verbose: msg = ( f'Type {T2}\n requires field "{k}"\n of type\n {v2} \n but' + f" {T1}\n has annotated it as\n {v1}\n which cannot be used. " ) msg += "\n\n" + f"assumption: {assumptions}" msg += "\n\n" + indent(can.why, "> ") else: # pragma: no cover msg = "" res = CanBeUsed(False, msg, matches) CanBeUsedCache.can_be_used_cache[key] = res return res res = CanBeUsed(True, "dataclass", matches) CanBeUsedCache.can_be_used_cache[key] = res return res if is_FixedTupleLike(T1): T1 = cast(Type[Tuple], T1) if not is_TupleLike(T2): msg = "A tuple can only be used as a tuple" return CanBeUsed(False, msg, matches) T2 = cast(Type[Tuple], T2) if is_FixedTupleLike(T2): t1s = get_tuple_types(T1) t2s = get_tuple_types(T2) if len(t1s) != len(t2s): msg = "Different length" return CanBeUsed(False, msg, matches) for i, (t1, t2) in enumerate(zip(t1s, t2s)): can = can_be_used_as2(t1, t2, matches, assumptions, allow_is_shortcut=allow_is_shortcut) if not can: return CanBeUsed(False, f"{t1} {t2}", matches, reasons={str(i): can}) matches = can.M return CanBeUsed(True, "", matches) elif is_VarTuple(T2): t1s = get_tuple_types(T1) if len(t1s) == 0: return CanBeUsed(True, "Empty tuple counts as var tuple", matches) T = get_VarTuple_arg(T2) tmax = reduce(type_sup, t1s) can = can_be_used_as2(tmax, T, matches, assumptions, allow_is_shortcut=allow_is_shortcut) if not can: msg = "The sup of the types in T1 is not a sub of T" return CanBeUsed(False, msg, matches, reasons={"": can}) return CanBeUsed(True, "", matches) else: raise ZAssertionError(T1=T1, T2=T2) if is_VarTuple(T1): T1 = cast(Type[Tuple], T1) if not is_VarTuple(T2): msg = "A var tuple can only be used as a var tuple" return CanBeUsed(False, msg, matches) T2 = cast(Type[Tuple], T2) t1 = get_VarTuple_arg(T1) t2 = get_VarTuple_arg(T2) can = can_be_used_as2(t1, t2, matches, assumptions, allow_is_shortcut=allow_is_shortcut) if not can: return CanBeUsed(False, f"{t1} {t2}", matches, reasons={"": can}) else: return CanBeUsed(True, "", matches) if is_TupleLike(T2): assert not is_TupleLike(T1) return CanBeUsed(False, f"Not a tuple type T1={T1} T2={T2}", matches) if is_Any(T1): assert not is_Union(T2) if not is_Any(T2): msg = "Any is the top" return CanBeUsed(False, msg, matches) if is_ListLike(T2): if not is_ListLike(T1): msg = "A List can only be used as a List" return CanBeUsed(False, msg, matches) T1 = cast(Type[List], T1) T2 = cast(Type[List], T2) t1 = get_ListLike_arg(T1) t2 = get_ListLike_arg(T2) # print(f'matching List with {t1} {t2}') can = can_be_used_as2(t1, t2, matches, assumptions, allow_is_shortcut=allow_is_shortcut) if not can.result: return CanBeUsed(False, f"{t1} {T2}", matches) return CanBeUsed(True, "", can.M) if is_Callable(T2): if not is_Callable(T1): return CanBeUsed(False, "not callable", matches) raise ZNotImplementedError(T1=T1, T2=T2) if is_ForwardRef(T1): n1 = get_ForwardRef_arg(T1) if is_ForwardRef(T2): n2 = get_ForwardRef_arg(T2) if n1 == n2: return CanBeUsed(True, "", matches) else: return CanBeUsed(False, "different name", matches) else: return CanBeUsed(False, "not fw ref", matches) if is_ForwardRef(T2): n2 = get_ForwardRef_arg(T2) if hasattr(T1, "__name__"): if T1.__name__ == n2: return CanBeUsed(True, "", matches) else: return CanBeUsed(False, "different name", matches) if is_Iterable(T2): T2 = cast(Type[Iterable], T2) t2 = get_Iterable_arg(T2) if is_Iterable(T1): T1 = cast(Type[Iterable], T1) t1 = get_Iterable_arg(T1) return can_be_used_as2(t1, t2, matches, allow_is_shortcut=allow_is_shortcut) if is_SetLike(T1): T1 = cast(Type[Set], T1) t1 = get_SetLike_arg(T1) return can_be_used_as2(t1, t2, matches, allow_is_shortcut=allow_is_shortcut) if is_ListLike(T1): T1 = cast(Type[List], T1) t1 = get_ListLike_arg(T1) return can_be_used_as2(t1, t2, matches, allow_is_shortcut=allow_is_shortcut) if is_DictLike(T1): T1 = cast(Type[Dict], T1) K, V = get_DictLike_args(T1) t1 = Tuple[K, V] return can_be_used_as2(t1, t2, matches, allow_is_shortcut=allow_is_shortcut) return CanBeUsed(False, "expect iterable", matches) if is_SetLike(T2): if not is_SetLike(T1): msg = "A Set can only be used as a Set" return CanBeUsed(False, msg, matches) T1 = cast(Type[Set], T1) T2 = cast(Type[Set], T2) t1 = get_SetLike_arg(T1) t2 = get_SetLike_arg(T2) # print(f'matching List with {t1} {t2}') can = can_be_used_as2(t1, t2, matches, assumptions, allow_is_shortcut=allow_is_shortcut) if not can.result: return CanBeUsed(False, f"Set argument fails", matches, reasons={"set_arg": can}) return CanBeUsed(True, "", can.M) if is_Sequence(T1): T1 = cast(Type[Sequence], T1) t1 = get_Sequence_arg(T1) if is_ListLike(T2): T2 = cast(Type[List], T2) t2 = get_ListLike_arg(T2) can = can_be_used_as2(t1, t2, matches, assumptions, allow_is_shortcut=allow_is_shortcut) if not can.result: return CanBeUsed(False, f"{t1} {T2}", matches) return CanBeUsed(True, "", can.M) msg = f"Needs a Sequence[{t1}], got {T2}" return CanBeUsed(False, msg, matches) if isinstance(T1, type) and isinstance(T2, type): # NOTE: this didn't work with Number for whatever reason # NOTE: issubclass(A, B) == type(T2).__subclasscheck__(T2, T1) # a0 = type.__subclasscheck__(T2, T1) # b0 = type.__subclasscheck__(T1, T2) logger.info(T1=T1, T2=T2) a = issubclass(T1, T2) # assert a0 == a and b0 == b, (T1, T2, a0, b0, a, b) if a: return CanBeUsed(True, f"type.__subclasscheck__ {T1} {T2}", matches) else: msg = f"Type {T1} is not a subclass of {T2} " # msg += f"; viceversa : {b}" return CanBeUsed(False, msg, matches) if is_List(T1): msg = f"Needs a List, got {T2}" return CanBeUsed(False, msg, matches) if T2 is type(None): msg = f"Needs type(None), got {T1}" return CanBeUsed(False, msg, matches) if is_NewType(T1): n1 = get_NewType_arg(T1) if is_NewType(T2): n2 = get_NewType_arg(T2) return can_be_used_as2(n1, n2, matches, assumptions, allow_is_shortcut=allow_is_shortcut) # if n1 == n2: # return CanBeUsed(True, "", matches) # else: # raise ZNotImplementedError(T1=T1, T2=T2) else: return can_be_used_as2(n1, T2, matches, assumptions, allow_is_shortcut=allow_is_shortcut) if is_Type(T1): if not is_Type(T2): return CanBeUsed(False, f"Not a Type[X], T1={T1}, T2={T2}", matches) sc1 = get_Type_arg(T1) sc2 = get_Type_arg(T2) return can_be_used_as2(sc1, sc2, matches, assumptions, allow_is_shortcut=allow_is_shortcut) # msg = f"{T1} ? {T2}" # pragma: no cover raise ZNotImplementedError(T1=T1, T2=T2) can_be_used_as2 = type_liskov def value_liskov(a: object, T: TypeLike) -> CanBeUsed: if is_Literal(T): res = a in get_Literal_args(T) # XXX return CanBeUsed(res, "literal", Matches()) if is_DictLike(T): return value_liskov_DictLike(a, cast(Type[Dict], T)) if is_SetLike(T): return value_liskov_SetLike(a, cast(Type[Set], T)) if is_ListLike(T): return value_liskov_ListLike(a, cast(Type[List], T)) if is_FixedTupleLike(T): return value_liskov_FixedTupleLike(a, cast(Type[Tuple], T)) if is_VarTuple(T): return value_liskov_VarTuple(a, cast(Type[Tuple], T)) if is_Union(T): return value_liskov_Union(a, T) S = ztype(a) return can_be_used_as2(S, T) def value_liskov_Union(a: object, T: type) -> CanBeUsed: ts = get_Union_args(T) reasons = {} for i, t in enumerate(ts): ok_k = value_liskov(a, t) if ok_k: msg = f"Match #{i}" return CanBeUsed(True, msg, ok_k.M, ok_k.matches, reasons={str(i): ok_k}) reasons[str(i)] = ok_k return CanBeUsed(False, "No match", Matches(), reasons=reasons) def value_liskov_DictLike(a: object, T: Type[Dict]) -> CanBeUsed: K, V = get_DictLike_args(cast(Type[Dict], T)) if not isinstance(a, dict): return CanBeUsed(False, "not a dict", Matches()) for k, v in a.items(): ok_k = value_liskov(k, K) if not ok_k: msg = f"Invalid key: {ok_k}" return CanBeUsed(False, msg, Matches()) ok_v = value_liskov(v, V) if not ok_v: msg = f"Invalid value: {ok_v}" return CanBeUsed(False, msg, Matches()) return CanBeUsed(True, "ok", Matches()) def value_liskov_SetLike(a: object, T: Type[Set]) -> CanBeUsed: V = get_SetLike_arg(T) if not isinstance(a, set): return CanBeUsed(False, "not a set", Matches()) for i, v in enumerate(a): ok = value_liskov(v, V) if not ok: msg = f"Invalid value #{i}: {ok}" return CanBeUsed(False, msg, Matches()) return CanBeUsed(True, "ok", Matches()) def value_liskov_ListLike(a: object, T: Type[List]) -> CanBeUsed: V = get_ListLike_arg(T) if not isinstance(a, list): return CanBeUsed(False, f"not a list: {type(a)}", Matches()) for i, v in enumerate(a): ok = value_liskov(v, V) if not ok: msg = f"Invalid value #{i}: {ok}" return CanBeUsed(False, msg, Matches()) return CanBeUsed(True, "ok", Matches()) def value_liskov_VarTuple(a: object, T: Type[Tuple]) -> CanBeUsed: V = get_VarTuple_arg(T) if not isinstance(a, tuple): return CanBeUsed(False, "not a tuple", Matches()) for i, v in enumerate(a): ok = value_liskov(v, V) if not ok: msg = f"Invalid value #{i}" return CanBeUsed(False, msg, reasons={str(i): ok}, M=Matches()) return CanBeUsed(True, "ok", Matches()) def value_liskov_FixedTupleLike(a: object, T: Type[Tuple]) -> CanBeUsed: VS = get_FixedTupleLike_args(T) if not isinstance(a, tuple): return CanBeUsed(False, "not a tuple", Matches()) if len(a) != len(VS): return CanBeUsed(False, "wrong length", Matches()) for i, (v, V) in enumerate(zip(a, VS)): ok = value_liskov(v, V) if not ok: msg = f"Invalid value #{i}" return CanBeUsed(False, msg, reasons={str(i): ok}, M=Matches()) return CanBeUsed(True, "ok", Matches()) X = TypeVar("X") def check_value_liskov(ob: object, T: Type[X]) -> X: try: ok = value_liskov(ob, T) except ZException as e: msg = "Could not run check_value_liskov() successfully." raise ZAssertionError(msg, ob=ob, Tob=type(ob), T=T) from e if not ok: raise ZTypeError(ob=ob, T=T, ok=ok) else: return cast(T, ob) def ztype(a: object) -> type: if type(a) is tuple: a = cast(tuple, a) ts = tuple(make_Literal(_) for _ in a) return make_Tuple(*ts) # todo: substitute tuple, list, dict with estimated return type(a)
zuper-typing-z6
/zuper-typing-z6-6.2.3.tar.gz/zuper-typing-z6-6.2.3/src/zuper_typing/subcheck.py
subcheck.py
from dataclasses import dataclass, Field, fields, is_dataclass, MISSING from typing import Dict, Optional, Tuple, Type from zuper_commons.text import pretty_dict from zuper_commons.types import ZAssertionError, ZValueError from . import logger from .aliases import TypeLike from .annotations_tricks import is_TypeLike from .constants import ANNOTATIONS_ATT from .constants import MULTI_ATT __all__ = [ "get_dataclass_info", "set_dataclass_info", "DataclassInfo", "same_as_default", "is_dataclass_instance", "asdict_not_recursive", "has_default", "get_default", "get_fields_values", ] class DataclassInfo: name: str # only for keeping track # These are the open ones # generic_att_XXX: Tuple[TypeLike, ...] # These are the bound ones # bindings: Dict[TypeLike, TypeLike] # These are the original ones orig: Tuple[TypeLike, ...] # Plus the ones we collected # extra: Tuple[TypeLike, ...] specializations: Dict[Tuple, type] _open: Optional[Tuple[TypeLike, ...]] fti = None def __init__(self, *, name: str, orig: Tuple[TypeLike, ...]): self.name = name # self.bindings = bindings self.orig = orig if not isinstance(orig, tuple): # pragma: no cover raise ZAssertionError(sself=self) for i, _ in enumerate(orig): # pragma: no cover if not is_TypeLike(_): msg = f"Element #{i} is not a typelike." raise ZAssertionError(msg, name=name, orig=orig) # self.extra = extra # if bindings: raise ZException(self=self) self.specializations = {} self._open = None def get_open(self) -> Tuple[TypeLike, ...]: if DataclassInfo.fti is None: from .recursive_tricks import find_typevars_inside DataclassInfo.fti = find_typevars_inside _open = getattr(self, "_open", None) if _open is None: res = [] for x in self.orig: for y in DataclassInfo.fti(x): if y not in res: res.append(y) self._open = tuple(res) return self._open # # def get_open_old(self) -> Tuple[TypeLike, ...]: # res = [] # for x in self.orig: # if x not in self.bindings: # res.append(x) # for x in self.extra: # if x not in self.bindings: # res.append(x) # # return tuple(res) # def __post_init__(self): # for k in self.bindings: # if k not in (self.orig + self.extra): # msg = f"There is a bound variable {k} which is not an original one or child. " # raise ZValueError(msg, di=self) def __repr__(self): # from .debug_print_ import debug_print debug_print = str return pretty_dict( "DataclassInfo", dict( name=self.name, orig=debug_print(self.orig), # extra=debug_print(self.extra), # bindings=debug_print(self.bindings) open=self.get_open(), ), ) def set_dataclass_info(T, di: DataclassInfo): assert is_TypeLike(T), T if not hasattr(T, MULTI_ATT): setattr(T, MULTI_ATT, {}) ma = getattr(T, MULTI_ATT) ma[id(T)] = di def get_dataclass_info(T: Type[dataclass]) -> DataclassInfo: assert is_TypeLike(T), T default = DataclassInfo(name=T.__name__, orig=()) if not hasattr(T, MULTI_ATT): return default ma = getattr(T, MULTI_ATT) if not id(T) in ma: msg = f"Cannot find type info for {T} ({id(T)}" logger.info(msg, ma=ma) return default return ma[id(T)] def get_fields_values(x: dataclass) -> Dict[str, object]: assert is_dataclass_instance(x), x res = {} T = type(x) try: fields_ = fields(T) except Exception as e: raise ZValueError(T=T) from e for f in fields_: k = f.name v0 = getattr(x, k) res[k] = v0 return res def get_all_annotations(cls: type) -> Dict[str, type]: """ Gets all the annotations including the parents. """ res = {} for base in cls.__bases__: annotations = getattr(base, ANNOTATIONS_ATT, {}) res.update(annotations) return res def asdict_not_recursive(x: dataclass) -> Dict[str, object]: """ Note: this does not return the classvars""" return get_fields_values(x) def is_dataclass_instance(x: object) -> bool: return not isinstance(x, type) and is_dataclass(x) def has_default(f: Field): """ Returns true if it has a default value or factory""" if f.default != MISSING: return True elif f.default_factory != MISSING: return True else: return False def has_default_value(f: Field): if f.default != MISSING: return True else: return False def has_default_factory(f: Field): if f.default_factory != MISSING: return True else: return False def get_default(f: Field) -> object: assert has_default(f) if f.default != MISSING: return f.default elif f.default_factory != MISSING: return f.default_factory() assert False def same_as_default(f: Field, value: object) -> bool: if f.default != MISSING: return f.default == value elif f.default_factory != MISSING: default = f.default_factory() return default == value else: return False
zuper-typing-z6
/zuper-typing-z6-6.2.3.tar.gz/zuper-typing-z6-6.2.3/src/zuper_typing/dataclass_info.py
dataclass_info.py
import traceback from dataclasses import dataclass, is_dataclass from datetime import datetime from decimal import Decimal from typing import cast, Dict, Iterator, List, Optional, Set, Tuple, Type, Union from zuper_commons.types import ZNotImplementedError, ZValueError from . import logger from .aliases import TypeLike from .annotations_tricks import ( get_ClassVar_arg, get_DictLike_args, get_fields_including_static, get_FixedTupleLike_args, get_ListLike_arg, get_NewType_arg, get_NewType_name, get_Optional_arg, get_SetLike_arg, get_Type_arg, get_TypeVar_name, get_Union_args, get_VarTuple_arg, is_Any, is_ClassVar, is_DictLike, is_FixedTupleLike, is_ListLike, is_NewType, is_Optional, is_SetLike, is_Type, is_TypeLike, is_TypeVar, is_Union, is_VarTuple, MyBytes, MyStr, ) from .dataclass_info import get_fields_values, is_dataclass_instance from .literal import get_Literal_args, is_Literal from .my_intersection import get_Intersection_args, is_Intersection from .uninhabited import is_Uninhabited assert logger __all__ = [ "assert_equivalent_objects", "assert_equivalent_types", "get_patches", "is_placeholder", "patch", "NotEquivalentException", ] @dataclass class Patch: __print_order__ = ["prefix_str", "value1", "value2", "msg"] prefix: Tuple[Union[str, int], ...] value1: object value2: Optional[object] prefix_str: Optional[str] = None msg: Optional[str] = None def __post_init__(self): self.prefix_str = "/".join(map(str, self.prefix)) def assert_equivalent_objects(ob1: object, ob2: object, compare_types: bool = True): if is_TypeLike(ob1): ob1 = cast(TypeLike, ob1) ob2 = cast(TypeLike, ob2) assert_equivalent_types(ob1, ob2) else: patches = get_patches(ob1, ob2, compare_types) if patches: msg = "The objects are not equivalent" raise ZValueError(msg, ob1=ob1, ob2=ob2, patches=patches) def get_patches(a: object, b: object, compare_types: bool = True) -> List[Patch]: patches = list(patch(a, b, (), compare_types)) return patches def patch( o1, o2, prefix: Tuple[Union[str, int], ...], compare_types: bool = True ) -> Iterator[Patch]: import numpy as np if isinstance(o1, np.ndarray): if np.all(o1 == o2): return else: yield Patch(prefix, o1, o2) if o1 == o2: return if is_TypeLike(o1) and is_TypeLike(o2): try: assert_equivalent_types(o1, o2) except NotEquivalentException as e: yield Patch(prefix, o1, o2, msg=traceback.format_exc()) elif is_dataclass_instance(o1) and is_dataclass_instance(o2): if compare_types: try: assert_equivalent_types(type(o1), type(o2)) except BaseException as e: yield Patch( prefix=prefix + ("$schema",), value1=type(o1), value2=type(o2), msg=traceback.format_exc(), ) fields1 = get_fields_values(o1) fields2 = get_fields_values(o2) if list(fields1) != list(fields2): yield Patch(prefix, o1, o2) for k in fields1: v1 = fields1[k] v2 = fields2[k] yield from patch(v1, v2, prefix + (k,), compare_types) elif isinstance(o1, dict) and isinstance(o2, dict): for k, v in o1.items(): if not k in o2: yield Patch(prefix + (k,), v, None) else: yield from patch(v, o2[k], prefix + (k,), compare_types) elif isinstance(o1, list) and isinstance(o2, list): n = max(len(o1), len(o2)) for i in range(n): if i >= len(o1): yield Patch(prefix + (i,), value1=o1, value2=o2, msg="Different length") elif i >= len(o2): yield Patch(prefix + (i,), value1=o1, value2=o2, msg="Different length") else: yield from patch(o1[i], o2[i], prefix + (i,), compare_types) # todo: we also need to check else: if o1 != o2: yield Patch(prefix, o1, o2) class NotEquivalentException(ZValueError): pass from .zeneric2 import DataclassInfo def check_dataclass_info_same(d1, d2, assume_yes: Set[Tuple[int, int]]): d1 = cast(DataclassInfo, d1) d2 = cast(DataclassInfo, d2) if len(d1.orig) != len(d2.orig): msg = "Different orig" raise NotEquivalentException(msg, d1=d1, d2=d2) for t1, t2 in zip(d1.orig, d2.orig): assert_equivalent_types(t1, t2, assume_yes=assume_yes) def sort_dict(x: dict) -> dict: keys = list(x) keys_sorted = sorted(keys, key=lambda _: repr(_)) return {k: x[k] for k in keys_sorted} def is_placeholder(x): return hasattr(x, "__name__") and "Placeholder" in x.__name__ def strip_my_types(T: TypeLike): if T is MyBytes: return bytes if T is MyStr: return str return T from .zeneric2 import get_dataclass_info def assert_equivalent_types( T1: TypeLike, T2: TypeLike, assume_yes: set = None, bypass_identity=False ): T1 = strip_my_types(T1) T2 = strip_my_types(T2) if assume_yes is None: # logger.warn('assuming yes from scratch') assume_yes = set() # debug(f'equivalent', T1=T1, T2=T2) key = (id(T1), id(T2)) if key in assume_yes: return if is_placeholder(T1) or is_placeholder(T2): msg = "One class is incomplete" raise NotEquivalentException(msg, T1=T1, T2=T2) assume_yes = set(assume_yes) assume_yes.add(key) recursive = lambda t1, t2: assert_equivalent_types( T1=t1, T2=t2, assume_yes=assume_yes, bypass_identity=bypass_identity ) try: # print(f'assert_equivalent_types({T1},{T2})') if (T1 is T2) and (not is_dataclass(T1) or bypass_identity): # logger.debug('same by equality') return if is_dataclass(T1): if not is_dataclass(T2): raise NotEquivalentException(T1=T1, T2=T2) # warnings.warn("devl") if False: if type(T1) != type(T2): msg = f"Different types for types: {type(T1)} {type(T2)}" raise NotEquivalentException(msg, T1=T1, T2=T2) atts = ["__name__", "__module__"] # atts.append('__doc__') if "__doc__" not in atts: pass # warnings.warn("de-selected __doc__ comparison") for k in atts: v1 = getattr(T1, k, ()) v2 = getattr(T2, k, ()) if v1 != v2: msg = f"Difference for {k} of {T1} ({type(T1)}) and {T2} ({type(T2)}" raise NotEquivalentException(msg, v1=v1, v2=v2) T1i = get_dataclass_info(T1) T2i = get_dataclass_info(T2) check_dataclass_info_same(T1i, T2i, assume_yes) fields1 = get_fields_including_static(T1) fields2 = get_fields_including_static(T2) if list(fields1) != list(fields2): msg = f"Different fields" raise NotEquivalentException(msg, fields1=fields1, fields2=fields2) ann1 = getattr(T1, "__annotations__", {}) ann2 = getattr(T2, "__annotations__", {}) for k in fields1: t1 = fields1[k].type t2 = fields2[k].type try: recursive(t1, t2) except NotEquivalentException as e: msg = f"Could not establish the annotation {k!r} to be equivalent" raise NotEquivalentException( msg, t1=t1, t2=t2, t1_ann=T1.__annotations__[k], t2_ann=T2.__annotations__[k], t1_att=getattr(T1, k, "no attribute"), t2_att=getattr(T2, k, "no attribute"), ) from e d1 = fields1[k].default d2 = fields2[k].default try: assert_equivalent_objects(d1, d2) except ZValueError as e: raise NotEquivalentException(d1=d1, d2=d2) from e # if d1 != d2: # msg = f"Defaults for {k!r} are different." # raise NotEquivalentException(msg, d1=d1, d2=d2) # # d1 = fields1[k].default_factory # d2 = fields2[k].default # if d1 != d2: # msg = f"Defaults for {k!r} are different." # raise NotEquivalentException(msg, d1=d1, d2=d2) for k in ann1: t1 = ann1[k] t2 = ann2[k] try: recursive(t1, t2) except NotEquivalentException as e: msg = f"Could not establish the annotation {k!r} to be equivalent" raise NotEquivalentException( msg, t1=t1, t2=t2, t1_ann=T1.__annotations__[k], t2_ann=T2.__annotations__[k], t1_att=getattr(T1, k, "no attribute"), t2_att=getattr(T2, k, "no attribute"), ) from e elif is_Literal(T1): if not is_Literal(T2): raise NotEquivalentException(T1=T1, T2=T2) values1 = get_Literal_args(T1) values2 = get_Literal_args(T2) if values1 != values2: raise NotEquivalentException(T1=T1, T2=T2) elif is_ClassVar(T1): if not is_ClassVar(T2): raise NotEquivalentException(T1=T1, T2=T2) t1 = get_ClassVar_arg(T1) t2 = get_ClassVar_arg(T2) recursive(t1, t2) elif is_Optional(T1): if not is_Optional(T2): raise NotEquivalentException(T1=T1, T2=T2) t1 = get_Optional_arg(T1) t2 = get_Optional_arg(T2) recursive(t1, t2) elif T1 is type(None): if not T2 is type(None): raise NotEquivalentException(T1=T1, T2=T2) elif is_Union(T1): if not is_Union(T2): raise NotEquivalentException(T1=T1, T2=T2) ts1 = get_Union_args(T1) ts2 = get_Union_args(T2) for t1, t2 in zip(ts1, ts2): recursive(t1, t2) elif is_Intersection(T1): if not is_Intersection(T2): raise NotEquivalentException(T1=T1, T2=T2) ts1 = get_Intersection_args(T1) ts2 = get_Intersection_args(T2) for t1, t2 in zip(ts1, ts2): recursive(t1, t2) elif is_FixedTupleLike(T1): if not is_FixedTupleLike(T2): raise NotEquivalentException(T1=T1, T2=T2) T1 = cast(Type[Tuple], T1) T2 = cast(Type[Tuple], T2) ts1 = get_FixedTupleLike_args(T1) ts2 = get_FixedTupleLike_args(T2) for t1, t2 in zip(ts1, ts2): recursive(t1, t2) elif is_VarTuple(T1): if not is_VarTuple(T2): raise NotEquivalentException(T1=T1, T2=T2) T1 = cast(Type[Tuple], T1) T2 = cast(Type[Tuple], T2) t1 = get_VarTuple_arg(T1) t2 = get_VarTuple_arg(T2) recursive(t1, t2) elif is_SetLike(T1): T1 = cast(Type[Set], T1) if not is_SetLike(T2): raise NotEquivalentException(T1=T1, T2=T2) T2 = cast(Type[Set], T2) t1 = get_SetLike_arg(T1) t2 = get_SetLike_arg(T2) recursive(t1, t2) elif is_ListLike(T1): T1 = cast(Type[List], T1) if not is_ListLike(T2): raise NotEquivalentException(T1=T1, T2=T2) T2 = cast(Type[List], T2) t1 = get_ListLike_arg(T1) t2 = get_ListLike_arg(T2) recursive(t1, t2) elif is_DictLike(T1): T1 = cast(Type[Dict], T1) if not is_DictLike(T2): raise NotEquivalentException(T1=T1, T2=T2) T2 = cast(Type[Dict], T2) t1, u1 = get_DictLike_args(T1) t2, u2 = get_DictLike_args(T2) recursive(t1, t2) recursive(u1, u2) elif is_Any(T1): if not is_Any(T2): raise NotEquivalentException(T1=T1, T2=T2) elif is_TypeVar(T1): if not is_TypeVar(T2): raise NotEquivalentException(T1=T1, T2=T2) n1 = get_TypeVar_name(T1) n2 = get_TypeVar_name(T2) if n1 != n2: raise NotEquivalentException(n1=n1, n2=n2) elif T1 in (int, str, bool, Decimal, datetime, float, type): if T1 != T2: raise NotEquivalentException(T1=T1, T2=T2) elif is_NewType(T1): if not is_NewType(T2): raise NotEquivalentException(T1=T1, T2=T2) n1 = get_NewType_name(T1) n2 = get_NewType_name(T2) if n1 != n2: raise NotEquivalentException(T1=T1, T2=T2) o1 = get_NewType_arg(T1) o2 = get_NewType_arg(T2) recursive(o1, o2) elif is_Type(T1): if not is_Type(T2): raise NotEquivalentException(T1=T1, T2=T2) t1 = get_Type_arg(T1) t2 = get_Type_arg(T2) recursive(t1, t2) elif is_Uninhabited(T1): if not is_Uninhabited(T2): raise NotEquivalentException(T1=T1, T2=T2) else: raise ZNotImplementedError(T1=T1, T2=T2) except NotEquivalentException as e: # logger.error(e) msg = f"Could not establish the two types to be equivalent." raise NotEquivalentException(msg, T1=T1, T2=T2) from e # assert T1 == T2 # assert_equal(T1.mro(), T2.mro())
zuper-typing-z6
/zuper-typing-z6-6.2.3.tar.gz/zuper-typing-z6-6.2.3/src/zuper_typing/get_patches_.py
get_patches_.py
import inspect import numbers from dataclasses import dataclass, field, Field, fields, is_dataclass, replace from datetime import datetime from decimal import Decimal from fractions import Fraction from typing import Any, Callable, cast, Dict, List, Optional, Sequence, Set, Tuple, Type, TypeVar import termcolor from frozendict import frozendict from zuper_commons.logs import ZLogger from zuper_commons.text import ( format_table, get_length_on_screen, indent, remove_escapes, Style, ) from zuper_commons.types import ZException from zuper_commons.types.exceptions import disable_colored from zuper_commons.ui import ( color_constant, color_float, color_int, color_ops, color_par, color_synthetic_types, color_typename, color_typename2, colorize_rgb, ) from zuper_commons.ui.colors import color_magenta, color_ops_light from .aliases import TypeLike from .annotations_tricks import ( CustomDict, CustomList, CustomSet, CustomTuple, get_Callable_info, get_ClassVar_arg, get_CustomDict_args, get_CustomList_arg, get_CustomSet_arg, get_CustomTuple_args, get_Dict_args, get_fields_including_static, get_FixedTupleLike_args, get_List_arg, get_NewType_arg, get_NewType_name, get_Optional_arg, get_Set_arg, get_Type_arg, get_TypeVar_bound, get_Union_args, get_VarTuple_arg, is_Any, is_Callable, is_ClassVar, is_CustomDict, is_CustomList, is_CustomSet, is_CustomTuple, is_Dict, is_FixedTupleLike, is_ForwardRef, is_Iterable, is_Iterator, is_List, is_NewType, is_Optional, is_Sequence, is_Set, is_Type, is_TypeLike, is_TypeVar, is_Union, is_VarTuple, MyBytes, MyStr, name_for_type_like, ) from .constants import ATT_PRINT_ORDER, DataclassHooks from .dataclass_info import has_default_factory, has_default_value from .literal import get_Literal_args, is_Literal from .my_intersection import get_Intersection_args, is_Intersection from .uninhabited import is_Uninhabited from .zeneric2 import get_dataclass_info __all__ = [ "debug_print", "DPOptions", "debug_print_str", "debug_print0", "get_default_dpoptions", ] def nothing(x: object) -> str: return "" # return " *" @dataclass class DPOptions: obey_print_order: bool = True do_special_EV: bool = True do_not_display_defaults: bool = True compact: bool = False abbreviate: bool = False # |│┃┆ default_border_left = "│ " # <-- note box-drawing id_gen: Callable[[object], object] = id # cid_if_known max_initial_levels: int = 20 omit_type_if_empty: bool = True omit_type_if_short: bool = True ignores: List[Tuple[str, str]] = field(default_factory=list) other_decoration_dataclass: Callable[[object], str] = nothing abbreviate_zuper_lang: bool = False ignore_dunder_dunder: bool = False spaces_after_separator: bool = True preferred_container_width: int = 88 compact_types: bool = True # different_color_mystr : bool = False # def get_default_dpoptions() -> DPOptions: ignores = [] id_gen = id return DPOptions(ignores=ignores, id_gen=id_gen) def remove_color_if_no_support(f): def f2(*args, **kwargs): s = f(*args, **kwargs) if disable_colored(): # pragma: no cover s = remove_escapes(s) return s f2.__name__ = "remove_color_if_no_support" return f2 @remove_color_if_no_support def debug_print(x: object, opt: Optional[DPOptions] = None) -> str: if opt is None: opt = get_default_dpoptions() max_levels = opt.max_initial_levels already = {} stack = () return debug_print0(x, max_levels=max_levels, already=already, stack=stack, opt=opt) eop = replace(get_default_dpoptions(), max_initial_levels=20) ZException.entries_formatter = lambda x: debug_print(x, opt=eop) eop_log = replace(get_default_dpoptions(), max_initial_levels=5) # <lower ZLogger.debug_print = lambda x: debug_print(x, opt=eop_log) def debug_print0( x: object, *, max_levels: int, already: Dict[int, str], stack: Tuple[int, ...], opt: DPOptions ) -> str: if id(x) in stack: if hasattr(x, "__name__"): n = x.__name__ return color_typename2(n + "↑") # ↶' return "(recursive)" if len(stack) > 50: return "!!! recursion not detected" if opt.compact: if isinstance(x, type) and is_dataclass(x): other = opt.other_decoration_dataclass(x) return color_typename(x.__name__) + other # logger.info(f'stack: {stack} {id(x)} {type(x)}') stack2 = stack + (id(x),) args = dict(max_levels=max_levels, already=already, stack=stack2, opt=opt) dpa = lambda _: debug_print0(_, **args) opt_compact = replace(opt, compact=True) dp_compact = lambda _: debug_print0( _, max_levels=max_levels, already=already, stack=stack2, opt=opt_compact ) # abbreviate = True if not opt.abbreviate: prefix = "" else: show_id = is_dataclass(x) and type(x).__name__ != "Constant" show_id = True if show_id: # noinspection PyBroadException try: h = opt.id_gen(x) except: prefix = termcolor.colored("!!!", "red") # except ValueError: # prefix = '!' else: if h is not None: if h in already: if isinstance(x, type): short = type(x).__name__ + "(...) " else: short = color_typename(type(x).__name__) + "(...) " res = short + termcolor.colored("$" + already[h], "green") # logger.info(f'ok already[h] = {res} already = {already}') return res else: already[h] = f"{len(already)}" prefix = termcolor.colored("&" + already[h], "green", attrs=["dark"]) else: prefix = "" else: prefix = "" postfix = " " + prefix if prefix else "" if False: # TODO: make configurable postfix += " " + opt.other_decoration_dataclass(x) postfix = postfix.rstrip() # prefix = prefix + f' L{max_levels}' if isinstance(x, int): return color_int(str(x)) + postfix if isinstance(x, float): return color_float(str(x)) + postfix if x is type: return color_ops("type") + postfix if x is BaseException: return color_ops("BaseException") + postfix if x is tuple: return color_ops("tuple") + postfix if x is object: return color_ops("object") + postfix if x is list: return color_ops("list") + postfix if x is dict: return color_ops("dict") + postfix if x is type(...): return color_ops("ellipsis") + postfix if x is int: return color_ops("int") + postfix if x is float: return color_ops("float") + postfix if x is bool: return color_ops("bool") + postfix if x is numbers.Number: return color_ops("Number") + postfix if x is str: return color_ops("str") + postfix if x is bytes: return color_ops("bytes") + postfix if x is set: return color_ops("set") + postfix if x is slice: return color_ops("slice") + postfix if x is datetime: return color_ops("datetime") + postfix if x is Decimal: return color_ops("Decimal") + postfix if not isinstance(x, str): if is_TypeLike(x): x = cast(TypeLike, x) return debug_print_typelike(x, dp_compact, dpa=dpa, opt=opt, prefix=prefix, args=args) if isinstance(x, bytes): return debug_print_bytes(x) + postfix if isinstance(x, str): return debug_print_str(x, prefix=prefix) # + postfix if isinstance(x, Decimal): # return color_ops("Dec") + " " + color_float(str(x)) return color_typename2(str(x)) # + postfix if isinstance(x, Fraction): if x in known_fraction: return color_float(known_fraction[x]) # + postfix # return color_ops("Dec") + " " + color_float(str(x)) return color_float(str(x)) # + postfix if isinstance(x, datetime): return debug_print_date(x, prefix=prefix) if isinstance(x, (set, frozenset)): return debug_print_set(x, prefix=prefix, **args) if isinstance(x, (dict, frozendict)): return debug_print_dict(x, prefix=prefix, **args) if isinstance(x, tuple): return debug_print_tuple(x, prefix=prefix, **args) if isinstance(x, list): return debug_print_list(x, prefix=prefix, **args) if isinstance(x, (bool, type(None))): return color_ops(str(x)) + postfix if not isinstance(x, type) and is_dataclass(x): return debug_print_dataclass_instance(x, prefix=prefix, **args) if "Expr" in type(x).__name__: return f"{x!r}\n{x}" repr_own = repr(x) cname = type(x).__name__ if cname in repr_own: r = repr_own else: r = f"instance of {cname}: {repr_own}" # assert not 'typing.Union' in r, (r, x, is_Union(x)) return r known_fraction = { Fraction(1, 2): "½", Fraction(1, 3): "⅓", Fraction(2, 3): "⅔", Fraction(1, 4): "¼", Fraction(3, 4): "¾", Fraction(1, 5): "⅕", Fraction(2, 5): "⅖", Fraction(3, 5): "⅗", Fraction(4, 5): "⅘", Fraction(1, 6): "⅙", Fraction(5, 6): "⅚", Fraction(1, 7): "⅐", Fraction(1, 8): "⅛", Fraction(3, 8): "⅜", Fraction(5, 8): "⅝", Fraction(7, 8): "⅞", Fraction(1, 9): "⅑", Fraction(1, 10): "⅒", } cst = color_synthetic_types def debug_print_typelike(x: TypeLike, dp_compact, dpa, opt: DPOptions, prefix: str, args) -> str: h = opt.other_decoration_dataclass(x) assert is_TypeLike(x), x if is_Any(x): s = name_for_type_like(x) s = termcolor.colored(s, on_color="on_magenta") return s + " " + h if is_Uninhabited(x): s = "Nothing" s = termcolor.colored(s, on_color="on_magenta") return s + " " + h if is_NewType(x): n = get_NewType_name(x) w = get_NewType_arg(x) return color_synthetic_types(n) + " " + h # + '<' + debug_print_typelike(w, dpa, opt, '', args) if ( (x is type(None)) # or is_List(x) # or is_Dict(x) # or is_Set(x) # or is_ClassVar(x) # or is_Type(x) or is_Iterator(x) or is_Sequence(x) or is_Iterable(x) or is_NewType(x) or is_ForwardRef(x) or is_Uninhabited(x) ): s = color_ops(name_for_type_like(x)) return s + h if is_TypeVar(x): assert isinstance(x, TypeVar), x name = x.__name__ bound = get_TypeVar_bound(x) covariant = getattr(x, "__covariant__") contravariant = getattr(x, "__contravariant__") if covariant: n = name + "+" elif contravariant: n = name + "-" else: n = name + "=" n = cst(n) if bound is not object: n += color_ops("<") + dp_compact(bound) return n + h if x is MyBytes: s = cst("MyBytes") return s + h if is_CustomDict(x): x = cast(Type[CustomDict], x) K, V = get_CustomDict_args(x) s = cst("Dict") + cst("[") + dp_compact(K) + cst(",") + dp_compact(V) + cst("]") return s + h if is_Dict(x): x = cast(Type[Dict], x) K, V = get_Dict_args(x) s = color_ops("Dict") + cst("[") + dp_compact(K) + cst(",") + dp_compact(V) + cst("]") return s + h if is_Type(x): V = get_Type_arg(x) s = cst("Type") + cst("[") + dp_compact(V) + cst("]") return s + h if is_ClassVar(x): V = get_ClassVar_arg(x) s = color_ops("ClassVar") + cst("[") + dp_compact(V) + cst("]") return s + h if is_CustomSet(x): x = cast(Type[CustomSet], x) V = get_CustomSet_arg(x) s = cst("Set") + cst("[") + dp_compact(V) + cst("]") return s + h if is_Set(x): x = cast(Type[Set], x) V = get_Set_arg(x) s = color_ops("Set") + cst("[") + dp_compact(V) + cst("]") return s + h if is_CustomList(x): x = cast(Type[CustomList], x) V = get_CustomList_arg(x) s = cst("List") + cst("[") + dp_compact(V) + cst("]") return s + h if is_List(x): x = cast(Type[List], x) V = get_List_arg(x) s = color_ops("List") + cst("[") + dp_compact(V) + cst("]") return s + h if is_Optional(x): V = get_Optional_arg(x) s0 = dp_compact(V) s = color_ops("Optional") + cst("[") + s0 + cst("]") return s + h if is_Literal(x): vs = get_Literal_args(x) s = ", ".join(dp_compact(_) for _ in vs) s = color_ops("Literal") + cst("[") + s + cst("]") return s + h if is_CustomTuple(x): x = cast(Type[CustomTuple], x) ts = get_CustomTuple_args(x) ss = [] for t in ts: ss.append(dp_compact(t)) args = color_ops(",").join(ss) s = cst("Tuple") + cst("[") + args + cst("]") return s + h if is_FixedTupleLike(x): x = cast(Type[Tuple], x) ts = get_FixedTupleLike_args(x) ss = [] for t in ts: ss.append(dp_compact(t)) args = color_ops(",").join(ss) s = color_ops("Tuple") + cst("[") + args + cst("]") return s + h if is_VarTuple(x): x = cast(Type[Tuple], x) t = get_VarTuple_arg(x) s = color_ops("Tuple") + cst("[") + dp_compact(t) + ", ..." + cst("]") return s + h if is_Union(x): Ts = get_Union_args(x) if opt.compact or len(Ts) <= 3: ss = list(dp_compact(v) for v in Ts) inside = color_ops(",").join(ss) s = color_ops("Union") + cst("[") + inside + cst("]") else: ss = list(dpa(v) for v in Ts) s = color_ops("Union") for v in ss: s += "\n" + indent(v, "", color_ops(f"* ")) return s + h if is_Intersection(x): Ts = get_Intersection_args(x) if opt.compact or len(Ts) <= 3: ss = list(dp_compact(v) for v in Ts) inside = color_ops(",").join(ss) s = color_ops("Intersection") + cst("[") + inside + cst("]") else: ss = list(dpa(v) for v in Ts) s = color_ops("Intersection") for v in ss: s += "\n" + indent(v, "", color_ops(f"* ")) return s + h if is_Callable(x): info = get_Callable_info(x) def ps(k, v): if k.startswith("__"): return dp_compact(v) else: return f"NamedArg({dp_compact(v)},{k!r})" params = color_ops(",").join(ps(k, v) for k, v in info.parameters_by_name.items()) ret = dp_compact(info.returns) s = color_ops("Callable") + cst("[[") + params + color_ops("],") + ret + cst("]") return s + h if isinstance(x, type) and is_dataclass(x): if opt.compact_types: return name_for_type_like(x) else: return debug_print_dataclass_type(x, prefix=prefix, **args) if hasattr(x, "__name__"): n = x.__name__ if n == "frozendict": # return 'frozen' + color_ops('dict') return color_ops_light("fdict") if n == "frozenset": # return 'frozen' + color_ops('set') return color_ops_light("fset") r = repr(x) if "frozendict" in r: raise Exception(r) r = termcolor.colored(r, "red") return r + h def clipped() -> str: return " " + termcolor.colored("...", "blue", on_color="on_yellow") braces = "{", "}" empty_dict = "".join(braces) def debug_print_dict(x: dict, *, prefix, max_levels: int, already: Dict, stack: Tuple[int], opt: DPOptions): h = opt.other_decoration_dataclass(x) lbrace, rbrace = braces if type(x) is frozendict: bprefix = "f" bracket_colors = color_ops_light elif "Dict[" in type(x).__name__: bprefix = "" bracket_colors = color_synthetic_types else: bprefix = "" bracket_colors = color_ops dpa = lambda _: debug_print0(_, max_levels=max_levels - 1, already=already, stack=stack, opt=opt) opt_compact = replace(opt, compact=True) dps = lambda _: debug_print0(_, max_levels=max_levels, already={}, stack=stack, opt=opt_compact) ps = " " + prefix if prefix else "" if len(x) == 0: if opt.omit_type_if_empty: return bracket_colors(bprefix + empty_dict) + ps + " " + h else: return dps(type(x)) + " " + bracket_colors(bprefix + empty_dict) + ps + " " + h s = dps(type(x)) + f"[{len(x)}]" + ps + " " + h if max_levels == 0: return s + clipped() r = {} for k, v in x.items(): if isinstance(k, str): if k.startswith("zd"): k = "zd..." + k[-4:] k = termcolor.colored(k, "yellow") else: k = dpa(k) # ks = debug_print(k) # if ks.startswith("'"): # ks = k r[k] = dpa(v) # colon_sep = ":" + short_space colon_sep = ": " ss = [k + colon_sep + v for k, v in r.items()] nlines = sum(_.count("\n") for _ in ss) tlen = sum(get_length_on_screen(_) for _ in ss) if nlines == 0 and tlen < get_max_col(stack): # x = "," if len(x) == 1 else "" res = ( bracket_colors(bprefix + lbrace) + bracket_colors(", ").join(ss) + bracket_colors(rbrace) + ps + " " + h ) if opt.omit_type_if_short: return res else: return dps(type(x)) + " " + res leftmargin = bracket_colors(opt.default_border_left) return pretty_dict_compact(s, r, leftmargin=leftmargin, indent_value=0) def get_max_col(stack: Tuple) -> int: max_line = 110 return max_line - 4 * len(stack) def debug_print_dataclass_type( x: Type[dataclass], prefix: str, max_levels: int, already: Dict, stack: Tuple, opt: DPOptions ) -> str: if max_levels <= 0: return name_for_type_like(x) + clipped() dpa = lambda _: debug_print0(_, max_levels=max_levels - 1, already=already, stack=stack, opt=opt) ps = " " + prefix if prefix else "" # ps += f" {id(x)} {type(x)}" # note breaks string equality if opt.abbreviate_zuper_lang: if x.__module__.startswith("zuper_lang."): return color_constant(x.__name__) more = "" if x.__name__ != x.__qualname__: more += f" ({x.__qualname__})" mod = x.__module__ + "." s = color_ops("dataclass") + " " + mod + color_typename(x.__name__) + more + ps # + f' {id(x)}' # noinspection PyArgumentList other = opt.other_decoration_dataclass(x) s += other cells = {} # FIXME: what was the unique one ? seen_fields = set() row = 0 all_fields: Dict[str, Field] = get_fields_including_static(x) for name, f in all_fields.items(): T = f.type if opt.ignore_dunder_dunder: if f.name.startswith("__"): continue cells[(row, 0)] = color_ops("field") cells[(row, 1)] = f.name cells[(row, 2)] = color_ops(":") cells[(row, 3)] = dpa(T) if has_default_value(f): cells[(row, 4)] = color_ops("=") cells[(row, 5)] = dpa(f.default) elif has_default_factory(f): cells[(row, 4)] = color_ops("=") cells[(row, 5)] = f"factory {dpa(f.default_factory)}" if is_ClassVar(T): if not hasattr(x, name): cells[(row, 6)] = "no attribute set" else: v = getattr(x, name) # cells[(row, 4)] = color_ops("=") cells[(row, 6)] = dpa(v) seen_fields.add(f.name) row += 1 try: xi = get_dataclass_info(x) except: # pragma: no cover cells[(row, 1)] = "cannot get the dataclass info" row += 1 else: if xi.orig: cells[(row, 1)] = "original" cells[(row, 3)] = dpa(xi.orig) row += 1 open = xi.get_open() if open: cells[(row, 1)] = "open" cells[(row, 3)] = dpa(open) row += 1 if getattr(x, "__doc__", None): cells[(row, 1)] = "__doc__" cells[(row, 3)] = str(getattr(x, "__doc__", "(missing)"))[:50] row += 1 if not cells: return s + ": (no fields)" align_right = Style(halign="right") col_style = {0: align_right, 1: align_right} res = format_table(cells, style="spaces", draw_grid_v=False, col_style=col_style) return s + "\n" + res # indent(res, ' ') list_parens = "[", "]" # empty_set = "∅" empty_list = "".join(list_parens) def debug_print_list( x: list, prefix: str, max_levels: int, already: Dict, stack: Tuple, opt: DPOptions ) -> str: # if type(x) is frozendict: # bprefix = 'f' # bracket_colors = color_ops_light if "List[" in type(x).__name__: bracket_colors = color_synthetic_types else: bracket_colors = color_ops lbra, rbra = list_parens lbra = bracket_colors(lbra) rbra = bracket_colors(rbra) empty = bracket_colors(empty_list) dpa = lambda _: debug_print0(_, max_levels=max_levels - 1, already=already, stack=stack, opt=opt) dps = lambda _: debug_print0(_, opt=opt, max_levels=max_levels, already={}, stack=stack) ps = " " + prefix if prefix else "" s = dps(type(x)) + f"[{len(x)}]" + ps if max_levels <= 0: return s + clipped() if len(x) == 0: if opt.omit_type_if_empty: return empty + ps else: return dps(type(x)) + " " + empty + ps ss = [dpa(v) for v in x] nlines = sum(_.count("\n") for _ in ss) if nlines == 0: max_width = min(opt.preferred_container_width, get_max_col(stack)) sep = color_ops(",") if opt.spaces_after_separator: sep += " " return arrange_in_rows(ss, start=lbra, sep=sep, stop=rbra + ps, max_width=max_width) else: for i, si in enumerate(ss): # s += '\n' + indent(debug_print(v), '', color_ops(f'#{i} ')) s += "\n" + indent(si, "", color_ops(f"#{i} ")) return s def arrange_in_rows(ss: Sequence[str], start: str, sep: str, stop: str, max_width: int) -> str: s = start indent_length = get_length_on_screen(start) cur_line_length = indent_length for i, si in enumerate(ss): this_one = si if i != len(ss) - 1: this_one += sep this_one_len = get_length_on_screen(this_one) if cur_line_length + this_one_len > max_width: # s += f' len {cur_line_length}' s += "\n" s += " " * indent_length cur_line_length = indent_length s += this_one cur_line_length += get_length_on_screen(this_one) s += stop return s set_parens = "❨", "❩" # empty_set = "∅" empty_set = "".join(set_parens) def debug_print_set( x: set, *, prefix: str, max_levels: int, already: Dict, stack: Tuple, opt: DPOptions ) -> str: h = opt.other_decoration_dataclass(x) popen, pclose = set_parens if type(x) is frozenset: bprefix = "f" bracket_colors = color_ops_light elif "Set[" in type(x).__name__: bprefix = "" bracket_colors = color_synthetic_types else: bprefix = "" bracket_colors = color_ops popen = bracket_colors(bprefix + popen) pclose = bracket_colors(pclose) dpa = lambda _: debug_print0(_, max_levels=max_levels - 1, already=already, stack=stack, opt=opt) dps = lambda _: debug_print0(_, max_levels=max_levels, already={}, stack=stack, opt=opt) # prefix = prefix or 'no prefix' ps = " " + prefix if prefix else "" if len(x) == 0: if opt.omit_type_if_empty: return bracket_colors(bprefix + empty_set) + ps + " " + h else: return dps(type(x)) + " " + bracket_colors(bprefix + empty_set) + ps + " " + h s = dps(type(x)) + f"[{len(x)}]" + ps + " " + h if max_levels <= 0: return s + clipped() ss = [dpa(v) for v in x] nlines = sum(_.count("\n") for _ in ss) tlen = sum(get_length_on_screen(_) for _ in ss) if nlines == 0 and tlen < get_max_col(stack): sep = bracket_colors(",") if opt.spaces_after_separator: sep += " " res = bracket_colors(bprefix + popen) + sep.join(ss) + bracket_colors(pclose) + ps + " " + h if opt.omit_type_if_short: return res else: return dps(type(x)) + " " + res for i, si in enumerate(ss): # s += '\n' + indent(debug_print(v), '', color_ops(f'#{i} ')) s += "\n" + indent(si, "", bracket_colors("• ")) return s # short_space = "\u2009" tuple_braces = "(", ")" empty_tuple_str = "".join(tuple_braces) def debug_print_tuple( x: tuple, prefix: str, max_levels: int, already: Dict, stack: Tuple, opt: DPOptions ) -> str: dpa = lambda _: debug_print0(_, max_levels=max_levels - 1, already=already, stack=stack, opt=opt) dps = lambda _: debug_print0(_, max_levels=max_levels, already={}, stack=stack, opt=opt) ps = " " + prefix if prefix else "" if "Tuple[" in type(x).__name__: bracket_colors = color_synthetic_types else: bracket_colors = color_ops open_brace = bracket_colors(tuple_braces[0]) close_brace = bracket_colors(tuple_braces[1]) if len(x) == 0: if opt.omit_type_if_empty: return bracket_colors(empty_tuple_str) + ps else: return dps(type(x)) + " " + bracket_colors(empty_tuple_str) + ps s = dps(type(x)) + f"[{len(x)}]" + ps if max_levels <= 0: return s + clipped() ss = [dpa(v) for v in x] nlines = sum(_.count("\n") for _ in ss) tlen = sum(get_length_on_screen(_) for _ in ss) if nlines == 0 and tlen < get_max_col(stack): x = "," if len(x) == 1 else "" sep = bracket_colors(",") if opt.spaces_after_separator: sep += " " res = open_brace + sep.join(ss) + x + close_brace + ps if opt.omit_type_if_short: return res else: return dps(type(x)) + " " + res for i, si in enumerate(ss): s += "\n" + indent(si, "", bracket_colors(f"#{i} ")) return s def debug_print_dataclass_instance( x: dataclass, prefix: str, max_levels: int, already: Dict, stack: Tuple, opt: DPOptions ) -> str: assert is_dataclass(x) fields_x = fields(x) dpa = lambda _: debug_print0(_, max_levels=max_levels - 1, already=already, stack=stack, opt=opt) opt_compact = replace(opt, compact=True) dp_compact = lambda _: debug_print0( _, max_levels=max_levels - 1, already=already, stack=stack, opt=opt_compact ) # noinspection PyArgumentList other = opt.other_decoration_dataclass(x) CN = type(x).__name__ # + str(id(type(x))) special_colors = { "EV": "#77aa77", "ZFunction": "#ffffff", "ArgRef": "#00ffff", "ZArg": "#00ffff", "ATypeVar": "#00ffff", "MakeProcedure": "#ffffff", "IF": "#fafaaf", } if CN in special_colors: cn = colorize_rgb(CN, special_colors[CN]) else: cn = color_typename(CN) ps = " " + prefix if prefix else "" ps += other s = cn + ps if max_levels <= 0: return s + clipped() if opt.obey_print_order and hasattr(x, ATT_PRINT_ORDER): options = getattr(x, ATT_PRINT_ORDER) else: options = [] for f in fields_x: options.append(f.name) if opt.do_not_display_defaults: same = [] for f in fields_x: att = getattr(x, f.name) if has_default_value(f): if f.default == att: same.append(f.name) elif has_default_factory(f): default = f.default_factory() if default == att: same.append(f.name) to_display = [_ for _ in options if _ not in same] else: to_display = options r = {} dpa_result = {} for k in to_display: if k == "expect": att = getattr(x, k) # logger.info(f'CN {CN} k {k!r} {getattr(att, "val", None)}') if CN == "EV" and k == "expect" and getattr(att, "val", None) is type: expects_type = True continue if not k in to_display: continue if k.startswith("__"): # TODO: make configurable continue if (CN, k) in opt.ignores: continue # r[color_par(k)] = "(non visualized)" else: att = getattr(x, k) if inspect.ismethod(att): att = att() r[color_par(k)] = dpa_result[k] = dpa(att) # r[(k)] = debug_print(att) expects_type = False if len(r) == 0: return cn + f"()" + prefix + other if type(x).__name__ == "Constant": s0 = dpa_result["val"] if not "\n" in s0: # 「 」‹ › return color_constant("⟬") + s0 + color_constant("⟭") else: l = color_constant("│ ") # ║") f = color_constant("C ") return indent(s0, l, f) if type(x).__name__ == "QualifiedName": module_name = x.module_name qual_name = x.qual_name return color_typename("QN") + " " + module_name + "." + color_typename(qual_name) if type(x).__name__ == "ATypeVar": if len(r) == 1: # only if no other stuff return color_synthetic_types(x.typevar_name) if CN == "EV" and opt.do_special_EV: if len(r) == 1: res = list(r.values())[0] else: res = pretty_dict_compact("", r, leftmargin="") if x.pr is not None: color_to_use = x.pr.get_color() else: color_to_use = "#f0f0f0" def colorit(_: str) -> str: return colorize_rgb(_, color_to_use) if expects_type: F = "ET " else: F = "E " l = colorit("┋ ") f = colorit(F) return indent(res, l, f) if len(r) == 1: k0 = list(r)[0] v0 = r[k0] if not "\n" in v0 and not "(" in v0: return cn + f"({k0}={v0.rstrip()})" + prefix + other # ss = list(r.values()) ss = [k + ": " + v for k, v in r.items()] tlen = sum(get_length_on_screen(_) for _ in ss) nlines = sum(_.count("\n") for _ in ss) # npars = sum(_.count("(") for _ in ss) if nlines == 0 and (tlen < get_max_col(stack)) and (tlen < 50): # ok, we can do on one line if type(x).__name__ == "MakeUnion": # assert len(r) == 1 + 1 ts = x.utypes v = [dpa(_) for _ in ts] return "(" + color_ops(" ∪ ").join(v) + ")" if type(x).__name__ == "MakeIntersection": # assert len(r) == 1 + 1 ts = x.inttypes v = [dpa(_) for _ in ts] return "(" + color_ops(" ∩ ").join(v) + ")" contents = ", ".join(k + "=" + v for k, v in r.items()) res = cn + "(" + contents + ")" + ps return res if CN == "MakeProcedure": M2 = "┇ " else: M2 = opt.default_border_left if CN in special_colors: leftmargin = colorize_rgb(M2, special_colors[CN]) else: leftmargin = color_typename(M2) return pretty_dict_compact(s, r, leftmargin=leftmargin, indent_value=0) # # def debug_print_dataclass_compact( # x, max_levels: int, already: Dict, stack: Tuple, # opt: DPOptions # ): # dpa = lambda _: debug_print0(_, max_levels=max_levels - 1, already=already, stack=stack, opt=opt) # # dps = lambda _: debug_print(_, max_levels, already={}, stack=stack) # s = color_typename(type(x).__name__) + color_par("(") # ss = [] # for k, v in x.__annotations__.items(): # att = getattr(x, k) # ss.append(f'{color_par(k)}{color_par("=")}{dpa(att)}') # # s += color_par(", ").join(ss) # s += color_par(")") # return s FANCY_BAR = "│" def pretty_dict_compact( head: Optional[str], d: Dict[str, Any], leftmargin="|", indent_value: int = 0 ): # | <-- note box-making if not d: return head + ": (empty dict)" if head else "(empty dict)" s = [] # n = max(get_length_on_screen(str(_)) for _ in d) ordered = list(d) # ks = sorted(d) for k in ordered: v = d[k] heading = str(k) + ":" # if isinstance(v, TypeVar): # # noinspection PyUnresolvedReferences # v = f'TypeVar({v.__name__}, bound={v.__bound__})' # if isinstance(v, dict): # v = pretty_dict_compact("", v) # vs = v if "\n" in v: vs = indent(v, " " * indent_value) s.append(heading) s.append(vs) else: s.append(heading + " " + v) # s.extend(.split('\n')) # return (head + ':\n' if head else '') + indent("\n".join(s), '| ') indented = indent("\n".join(s), leftmargin) return (head + "\n" if head else "") + indented def nice_str(self): return DataclassHooks.dc_repr(self) def blue(x): return termcolor.colored(x, "blue") def nice_repr(self): s = termcolor.colored(type(self).__name__, "red") s += blue("(") ss = [] annotations = getattr(type(self), "__annotations__", {}) for k in annotations: if not hasattr(self, k): continue a = getattr(self, k) a_s = debug_print_compact(a) eq = blue("=") k = termcolor.colored(k, attrs=["dark"]) ss.append(f"{k}{eq}{a_s}") s += blue(", ").join(ss) s += blue(")") return s def debug_print_compact(x): if isinstance(x, str): return debug_print_str(x, prefix="") if isinstance(x, bytes): return debug_print_bytes(x) if isinstance(x, datetime): return debug_print_date(x, prefix="") return f"{x!r}" def debug_print_str(x: str, *, prefix: str): # Note: this breaks zuper-comp different_color_mystr = False if different_color_mystr and isinstance(x, MyStr): color = color_ops_light else: color = color_magenta if type(x) not in (str, MyStr): return type(x).__name__ + " - " + debug_print_str(str(x), prefix=prefix) if x == "\n": return "'\\n'" # if x.startswith("Qm"): # x2 = "Qm..." + x[-4:] + " " + prefix # return termcolor.colored(x2, "magenta") # if x.startswith("zd"): # x2 = "zd..." + x[-4:] + " " + prefix # return termcolor.colored(x2, "magenta") if x.startswith("-----BEGIN"): s = "PEM key" + " " + prefix return termcolor.colored(s, "yellow") # if x.startswith("Traceback"): # lines = x.split("\n") # colored = [termcolor.colored(_, "red") for _ in lines] # if colored: # colored[0] += " " + prefix # s = "\n".join(colored) # return s ps = " " + prefix if prefix else "" lines = x.split("\n") if len(lines) > 1: first = color("|") lines[0] = lines[0] + ps try: return indent(x, first) # res = box(x, color="magenta") # , attrs=["dark"]) # return side_by_side([res, ps]) except: # pragma: no cover # print(traceback.format_exc()) return "?" if x.startswith("zdpu"): return termcolor.colored(x, "yellow") if x == "": return "''" else: if x.strip() == x: return color(x) + ps else: return color("'" + x + "'") + ps # return x.__repr__() + ps def debug_print_date(x: datetime, *, prefix: str): s = x.isoformat() # [:19] s = s.replace("T", " ") return termcolor.colored(s, "yellow") + (" " + prefix if prefix else "") def debug_print_bytes(x: bytes): s = f"{len(x)} bytes " + x[:10].__repr__() # s = f"{len(x)} bytes " + str(list(x)) return termcolor.colored(s, "yellow") DataclassHooks.dc_str = lambda self: debug_print(self) DataclassHooks.dc_repr = nice_repr
zuper-typing-z6
/zuper-typing-z6-6.2.3.tar.gz/zuper-typing-z6-6.2.3/src/zuper_typing/debug_print_.py
debug_print_.py
import dataclasses import typing from dataclasses import dataclass as original_dataclass from typing import Dict, Generic, Tuple, TypeVar from zuper_commons.types import ZTypeError from .annotations_tricks import make_dict from .constants import ANNOTATIONS_ATT, DataclassHooks, DEPENDS_ATT, PYTHON_36 from .dataclass_info import get_all_annotations from .zeneric2 import resolve_types, ZenericFix __all__ = ["get_remembered_class", "MyNamedArg", "remember_created_class", "my_dataclass", "ZenericFix"] def _cmp_fn_loose(name, op, self_tuple, other_tuple, *args, **kwargs): body = [ "if other.__class__.__name__ == self.__class__.__name__:", # "if other is not None:", f" return {self_tuple}{op}{other_tuple}", "return NotImplemented", ] fn = dataclasses._create_fn(name, ("self", "other"), body) fn.__doc__ = """ This is a loose comparison function. Instead of comparing: self.__class__ is other.__class__ we compare: self.__class__.__name__ == other.__class__.__name__ """ return fn dataclasses._cmp_fn = _cmp_fn_loose def typevar__repr__(self): if self.__covariant__: prefix = "+" elif self.__contravariant__: prefix = "-" else: prefix = "~" s = prefix + self.__name__ if self.__bound__: if isinstance(self.__bound__, type): b = self.__bound__.__name__ else: b = str(self.__bound__) s += f"<{b}" return s setattr(TypeVar, "__repr__", typevar__repr__) NAME_ARG = "__name_arg__" # need to have this otherwise it's not possible to say that two types are the same class Reg: already = {} def MyNamedArg(T, name: str): try: int(name) except: pass else: msg = f"Tried to create NamedArg with name = {name!r}." raise ValueError(msg) key = f"{T} {name}" if key in Reg.already: return Reg.already[key] class CNamedArg: pass setattr(CNamedArg, NAME_ARG, name) setattr(CNamedArg, "original", T) Reg.already[key] = CNamedArg return CNamedArg try: import mypy_extensions except ImportError: pass else: setattr(mypy_extensions, "NamedArg", MyNamedArg) class RegisteredClasses: klasses: Dict[Tuple[str, str], type] = {} def get_remembered_class(module_name: str, qual_name: str) -> type: # TODO: not tested k = (module_name, qual_name) return RegisteredClasses.klasses[k] def remember_created_class(res: type, msg: str = ""): k = (res.__module__, res.__qualname__) # logger.info(f"Asked to remember {k}: {msg}") if k in RegisteredClasses.klasses: pass # logger.info(f"Asked to remember again {k}: {msg}") RegisteredClasses.klasses[k] = res # noinspection PyShadowingBuiltins def my_dataclass(_cls=None, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False): def wrap(cls): # logger.info(f'called my_dataclass for {cls} with bases {_cls.__bases__}') # if cls.__name__ == 'B' and len(cls.__bases__) == 1 and cls.__bases__[0].__name__ # == 'object' and len(cls.__annotations__) != 2: # assert False, (cls, cls.__bases__, cls.__annotations__) res = my_dataclass_( cls, init=init, repr=repr, eq=eq, order=order, unsafe_hash=unsafe_hash, frozen=frozen ) # logger.info(f'called my_dataclass for {cls} with bases {_cls.__bases__}, ' # f'returning {res} with bases {res.__bases__} and annotations { # _cls.__annotations__}') remember_created_class(res, "my_dataclass") return res # See if we're being called as @dataclass or @dataclass(). if _cls is None: # We're called with parens. return wrap # We're called as @dataclass without parens. return wrap(_cls) # noinspection PyShadowingBuiltins def my_dataclass_(_cls, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False): original_doc = getattr(_cls, "__doc__", None) # logger.info(_cls.__dict__) unsafe_hash = True if hasattr(_cls, "nominal"): # logger.info('nominal for {_cls}') nominal = True else: nominal = False # # if the class does not have a metaclass, add one # We copy both annotations and constants. This is needed for cases like: # # @dataclass # class C: # a: List[] = field(default_factory=list) # # # if Generic in _cls.__bases__: msg = ( f"There are problems with initialization: class {_cls.__name__} inherits from Generic: " f"{_cls.__bases__}" ) raise Exception(msg) if type(_cls) is type: old_annotations = get_all_annotations(_cls) from .zeneric2 import StructuralTyping old_annotations.update(getattr(_cls, ANNOTATIONS_ATT, {})) attrs = {ANNOTATIONS_ATT: old_annotations} for k in old_annotations: if hasattr(_cls, k): attrs[k] = getattr(_cls, k) class Base(metaclass=StructuralTyping): pass _cls2 = type(_cls.__name__, (_cls, Base) + _cls.__bases__, attrs) _cls2.__module__ = _cls.__module__ _cls2.__qualname__ = _cls.__qualname__ _cls = _cls2 else: old_annotations = get_all_annotations(_cls) old_annotations.update(getattr(_cls, ANNOTATIONS_ATT, {})) setattr(_cls, ANNOTATIONS_ATT, old_annotations) k = "__" + _cls.__name__.replace("[", "_").replace("]", "_") if nominal: # # annotations = getattr(K, '__annotations__', {}) # old_annotations[k] = bool # typing.Optional[bool] old_annotations[k] = typing.ClassVar[bool] # typing.Optional[bool] setattr(_cls, k, True) # if True: # anns = getattr(_cls, ANNOTATIONS_ATT) # anns_reordered = reorder_annotations(_cls, anns) # setattr(_cls, ANNOTATIONS_ATT, anns_reordered) if "__hash__" in _cls.__dict__: unsafe_hash = False # print(_cls.__dict__) # _cls.__dict__['__hash__']= None fields_before = dict(getattr(_cls, dataclasses._FIELDS, {})) # if hasattr(_cls, dataclasses._FIELDS): # delattr(_cls, dataclasses._FIELDS) try: res = original_dataclass( _cls, init=init, repr=repr, eq=eq, order=order, unsafe_hash=unsafe_hash, frozen=frozen ) except KeyboardInterrupt: raise except Exception as e: msg = "Cannot create dataclass " raise ZTypeError( msg, _cls=_cls, fields=getattr(_cls, dataclasses._FIELDS, "n/a"), fields_before=fields_before, anns=getattr(_cls, "__annotations__", "n/a"), ) from e # do it right away setattr(res, "__doc__", original_doc) # assert dataclasses.is_dataclass(res) refs = getattr(_cls, DEPENDS_ATT, ()) resolve_types(res, refs=refs) def __repr__(self) -> str: return DataclassHooks.dc_repr(self) def __str__(self): return DataclassHooks.dc_str(self) setattr(res, "__repr__", __repr__) setattr(res, "__str__", __str__) if nominal: setattr(_cls, k, True) # <!--- FIXME return res if False: if PYTHON_36: # pragma: no cover from typing import GenericMeta # noinspection PyUnresolvedReferences previous_getitem = GenericMeta.__getitem__ else: from typing import _GenericAlias previous_getitem = _GenericAlias.__getitem__ class Alias1: def __getitem__(self, params): if self is typing.Dict: K, V = params if K is not str: return make_dict(K, V) # noinspection PyArgumentList return previous_getitem(self, params) def original_dict_getitem(a): # noinspection PyArgumentList return previous_getitem(Dict, a) Dict.__getitem__ = Alias1.__getitem__ def monkey_patch_dataclass(): setattr(dataclasses, "dataclass", my_dataclass) def monkey_patch_Generic(): if PYTHON_36: # pragma: no cover GenericMeta.__getitem__ = ZenericFix.__getitem__ else: Generic.__class_getitem__ = ZenericFix.__class_getitem__ _GenericAlias.__getitem__ = Alias1.__getitem__
zuper-typing-z6
/zuper-typing-z6-6.2.3.tar.gz/zuper-typing-z6-6.2.3/src/zuper_typing/monkey_patching_typing.py
monkey_patching_typing.py
from dataclasses import dataclass, field, is_dataclass from datetime import datetime from decimal import Decimal from functools import reduce from typing import cast, Dict, List, Optional, Set, Tuple, Type from zuper_commons.types import ZValueError from .aliases import TypeLike from .annotations_tricks import ( get_DictLike_args, get_FixedTupleLike_args, get_ListLike_arg, get_Optional_arg, get_SetLike_arg, get_TypeVar_name, get_Union_args, get_VarTuple_arg, is_DictLike, is_FixedTupleLike, is_ListLike, is_Optional, is_SetLike, is_TypeVar, is_Union, is_VarTuple, make_dict, make_list, make_set, make_Tuple, make_Union, make_VarTuple, unroll_union, ) from .common import DictStrType from .my_intersection import get_Intersection_args, is_Intersection, make_Intersection from .uninhabited import is_Uninhabited, make_Uninhabited __all__ = ["type_inf", "type_sup", "Matches"] def unroll_intersection(a: TypeLike) -> Tuple[TypeLike, ...]: if is_Intersection(a): return get_Intersection_args(a) else: return (a,) def type_sup(a: TypeLike, b: TypeLike) -> TypeLike: assert a is not None assert b is not None assert not isinstance(a, tuple), a assert not isinstance(b, tuple), b if a is b or (a == b): return a if a is object or b is object: return object if is_Uninhabited(a): return b if is_Uninhabited(b): return a if a is type(None): if is_Optional(b): return b else: return Optional[b] if b is type(None): if is_Optional(a): return a else: return Optional[a] if is_Optional(a): return type_sup(type(None), type_sup(get_Optional_arg(a), b)) if is_Optional(b): return type_sup(type(None), type_sup(get_Optional_arg(b), a)) # if is_Union(a) and is_Union(b): # XXX # r = [] # r.extend(unroll_union(a)) # r.extend(unroll_union(b)) # return reduce(type_sup, r) # if is_Union(a) and is_Union(b): ta = unroll_union(a) tb = unroll_union(b) tva, oa = get_typevars(ta) tvb, ob = get_typevars(tb) tv = tuple(set(tva + tvb)) oab = oa + ob if not oab: return make_Union(*tv) else: other = reduce(type_sup, oa + ob) os = unroll_union(other) return make_Union(*(tv + os)) if (a, b) in [(bool, int), (int, bool)]: return int if is_ListLike(a) and is_ListLike(b): a = cast(Type[List], a) b = cast(Type[List], b) A = get_ListLike_arg(a) B = get_ListLike_arg(b) u = type_sup(A, B) return make_list(u) if is_SetLike(a) and is_SetLike(b): a = cast(Type[Set], a) b = cast(Type[Set], b) A = get_SetLike_arg(a) B = get_SetLike_arg(b) u = type_sup(A, B) return make_set(u) if is_DictLike(a) and is_DictLike(b): a = cast(Type[Dict], a) b = cast(Type[Dict], b) KA, VA = get_DictLike_args(a) KB, VB = get_DictLike_args(b) K = type_sup(KA, KB) V = type_sup(VA, VB) return make_dict(K, V) if is_VarTuple(a) and is_VarTuple(b): a = cast(Type[Tuple], a) b = cast(Type[Tuple], b) VA = get_VarTuple_arg(a) VB = get_VarTuple_arg(b) V = type_sup(VA, VB) return make_VarTuple(V) if is_FixedTupleLike(a) and is_FixedTupleLike(b): a = cast(Type[Tuple], a) b = cast(Type[Tuple], b) tas = get_FixedTupleLike_args(a) tbs = get_FixedTupleLike_args(b) ts = tuple(type_sup(ta, tb) for ta, tb in zip(tas, tbs)) return make_Tuple(*ts) if is_dataclass(a) and is_dataclass(b): return type_sup_dataclass(a, b) if is_TypeVar(a) and is_TypeVar(b): if get_TypeVar_name(a) == get_TypeVar_name(b): return a return make_Union(a, b) # raise NotImplementedError(a, b) def type_inf_dataclass(a: Type[dataclass], b: Type[dataclass]) -> Type[dataclass]: from .monkey_patching_typing import my_dataclass ann_a = a.__annotations__ ann_b = b.__annotations__ all_keys = set(ann_a) | set(ann_b) res = {} for k in all_keys: if k in ann_a and k not in ann_b: R = ann_a[k] elif k not in ann_a and k in ann_b: R = ann_b[k] else: VA = ann_a[k] VB = ann_b[k] R = type_inf(VA, VB) if is_Uninhabited(R): return R res[k] = R name = f"Int_{a.__name__}_{b.__name__}" T2 = my_dataclass(type(name, (), {"__annotations__": res, "__module__": "zuper_typing"})) return T2 def type_sup_dataclass(a: Type[dataclass], b: Type[dataclass]) -> Type[dataclass]: from .monkey_patching_typing import my_dataclass ann_a = a.__annotations__ ann_b = b.__annotations__ common_keys = set(ann_a) & set(ann_b) res = {} for k in common_keys: if k in ann_a and k not in ann_b: R = ann_a[k] elif k not in ann_a and k in ann_b: R = ann_b[k] else: VA = ann_a[k] VB = ann_b[k] R = type_sup(VA, VB) res[k] = R name = f"Join_{a.__name__}_{b.__name__}" T2 = my_dataclass(type(name, (), {"__annotations__": res, "__module__": "zuper_typing"})) return T2 def type_inf(a: TypeLike, b: TypeLike) -> TypeLike: try: res = type_inf0(a, b) except ZValueError as e: # pragma: no cover raise # raise ZValueError("problem", a=a, b=b) from e # if isinstance(res, tuple): # raise ZValueError(a=a, b=b, res=res) return res def get_typevars(a: Tuple[TypeLike, ...]) -> Tuple[Tuple, Tuple]: tv = [] ts = [] for _ in a: if is_TypeVar(_): tv.append(_) else: ts.append(_) return tuple(tv), tuple(ts) def type_inf0(a: TypeLike, b: TypeLike) -> TypeLike: assert a is not None assert b is not None if isinstance(a, tuple): # pragma: no cover raise ZValueError(a=a, b=b) if isinstance(b, tuple): # pragma: no cover raise ZValueError(a=a, b=b) if a is b or (a == b): return a if a is object: return b if b is object: return a if is_Uninhabited(a): return a if is_Uninhabited(b): return b if is_Optional(a): if b is type(None): return b if is_Optional(b): if a is type(None): return a if is_Optional(a) and is_Optional(b): x = type_inf(get_Optional_arg(a), get_Optional_arg(b)) if is_Uninhabited(x): return type(None) return Optional[x] # if not is_Intersection(a) and is_Intersection(b): # r = (a,) + unroll_intersection(b) # return reduce(type_inf, r) if is_Intersection(a) or is_Intersection(b): ta = unroll_intersection(a) tb = unroll_intersection(b) tva, oa = get_typevars(ta) tvb, ob = get_typevars(tb) tv = tuple(set(tva + tvb)) oab = oa + ob if not oab: return make_Intersection(tv) else: other = reduce(type_inf, oa + ob) os = unroll_intersection(other) return make_Intersection(tv + os) if is_Union(b): # A ^ (C u D) # = A^C u A^D r = [] for t in get_Union_args(b): r.append(type_inf(a, t)) return reduce(type_sup, r) # if is_Intersection(a) and not is_Intersection(b): # res = [] # for aa in get_Intersection_args(a): # r = type_inf(aa) # r.extend(unroll_intersection(a)) # r.extend(unroll_intersection(b)) # put first! # return reduce(type_inf, r) if (a, b) in [(bool, int), (int, bool)]: return bool if is_TypeVar(a) and is_TypeVar(b): if get_TypeVar_name(a) == get_TypeVar_name(b): return a if is_TypeVar(a) or is_TypeVar(b): return make_Intersection((a, b)) primitive = (bool, int, str, Decimal, datetime, float, bytes, type(None)) if a in primitive or b in primitive: return make_Uninhabited() if is_ListLike(a) ^ is_ListLike(b): return make_Uninhabited() if is_ListLike(a) & is_ListLike(b): a = cast(Type[List], a) b = cast(Type[List], b) A = get_ListLike_arg(a) B = get_ListLike_arg(b) u = type_inf(A, B) return make_list(u) if is_SetLike(a) ^ is_SetLike(b): return make_Uninhabited() if is_SetLike(a) and is_SetLike(b): a = cast(Type[Set], a) b = cast(Type[Set], b) A = get_SetLike_arg(a) B = get_SetLike_arg(b) u = type_inf(A, B) return make_set(u) if is_DictLike(a) ^ is_DictLike(b): return make_Uninhabited() if is_DictLike(a) and is_DictLike(b): a = cast(Type[Dict], a) b = cast(Type[Dict], b) KA, VA = get_DictLike_args(a) KB, VB = get_DictLike_args(b) K = type_inf(KA, KB) V = type_inf(VA, VB) return make_dict(K, V) if is_dataclass(a) ^ is_dataclass(b): return make_Uninhabited() if is_dataclass(a) and is_dataclass(b): return type_inf_dataclass(a, b) if is_VarTuple(a) and is_VarTuple(b): a = cast(Type[Tuple], a) b = cast(Type[Tuple], b) VA = get_VarTuple_arg(a) VB = get_VarTuple_arg(b) V = type_inf(VA, VB) return make_VarTuple(V) if is_FixedTupleLike(a) and is_FixedTupleLike(b): a = cast(Type[Tuple], a) b = cast(Type[Tuple], b) tas = get_FixedTupleLike_args(a) tbs = get_FixedTupleLike_args(b) ts = tuple(type_inf(ta, tb) for ta, tb in zip(tas, tbs)) return make_Tuple(*ts) if is_TypeVar(a) and is_TypeVar(b): if get_TypeVar_name(a) == get_TypeVar_name(b): return a return make_Intersection((a, b)) @dataclass class MatchConstraint: ub: Optional[type] = None lb: Optional[type] = None def impose_subtype(self, ub) -> "MatchConstraint": ub = type_sup(self.ub, ub) if self.ub is not None else ub return MatchConstraint(ub=ub, lb=self.lb) def impose_supertype(self, lb) -> "MatchConstraint": lb = type_inf(self.lb, lb) if self.lb is not None else lb return MatchConstraint(lb=lb, ub=self.ub) DMC = make_dict(str, MatchConstraint) @dataclass class Matches: m: Dict[str, MatchConstraint] = field(default_factory=DMC) def __post_init__(self): self.m = DMC(self.m) def get_matches(self) -> Dict[str, type]: res = DictStrType() for k, v in self.m.items(): if v.ub is not None: res[k] = v.ub return res def get_ub(self, k: str): if k not in self.m: return None return self.m[k].ub def get_lb(self, k: str): if k not in self.m: return None return self.m[k].lb def must_be_subtype_of(self, k: str, ub) -> "Matches": m2 = dict(self.m) if k not in m2: m2[k] = MatchConstraint() m2[k] = m2[k].impose_subtype(ub=ub) return Matches(m2) def must_be_supertype_of(self, k: str, lb) -> "Matches": m2 = dict(self.m) if k not in m2: m2[k] = MatchConstraint() m2[k] = m2[k].impose_supertype(lb=lb) return Matches(m2)
zuper-typing-z6
/zuper-typing-z6-6.2.3.tar.gz/zuper-typing-z6-6.2.3/src/zuper_typing/type_algebra.py
type_algebra.py
import sys import typing from abc import ABCMeta, abstractmethod from dataclasses import _PARAMS, dataclass, fields, is_dataclass from datetime import datetime from decimal import Decimal from typing import Any, cast, ClassVar, Dict, Optional, Tuple, Type, TypeVar from zuper_commons.types import ZTypeError, ZValueError from . import logger from .aliases import TypeLike from .annotations_tricks import ( get_ClassVar_arg, get_Type_arg, get_TypeVar_bound, is_ClassVar, is_NewType, is_Type, is_TypeLike, make_dict, name_for_type_like, ) from .constants import ANNOTATIONS_ATT, DEPENDS_ATT, MakeTypeCache, PYTHON_36, ZuperTypingGlobals from .dataclass_info import DataclassInfo, get_dataclass_info, set_dataclass_info from .recursive_tricks import ( get_name_without_brackets, NoConstructorImplemented, replace_typevars, ) from .subcheck import can_be_used_as2, value_liskov __all__ = ["resolve_types", "MyABC", "StructuralTyping", "make_type"] X = TypeVar("X") def as_tuple(x) -> Tuple: return x if isinstance(x, tuple) else (x,) if PYTHON_36: # pragma: no cover from typing import GenericMeta # noinspection PyUnresolvedReferences old_one = GenericMeta.__getitem__ else: old_one = None if PYTHON_36: # pragma: no cover # logger.info('In Python 3.6') class ZMeta(type): def __getitem__(self, *params): return ZenericFix.__class_getitem__(*params) else: ZMeta = type class ZenericFix(metaclass=ZMeta): if PYTHON_36: # pragma: no cover def __getitem__(self, *params): # logger.info(f'P36 {params} {self}') if self is typing.Generic: return ZenericFix.__class_getitem__(*params) if self is Dict: K, V = params if K is not str: return make_dict(K, V) # noinspection PyArgumentList return old_one(self, params) # noinspection PyMethodParameters @classmethod def __class_getitem__(cls0, params): # logger.info(f"ZenericFix.__class_getitem__ params = {params}") types0 = as_tuple(params) assert isinstance(types0, tuple) for t in types0: assert is_TypeLike(t), (t, types0) bound_att = types0 name = "Generic[%s]" % ",".join(name_for_type_like(_) for _ in bound_att) di = DataclassInfo(name=name, orig=bound_att) gp = type(name, (GenericProxy,), {"di": di}) set_dataclass_info(gp, di) return gp # # def autoInitDecorator(toDecoreFun): # def wrapper(*args, **kwargs): # print("Hello from autoinit decorator") # toDecoreFun(*args, **kwargs) # # return wrapper class StructuralTyping(type): cache = {} def __subclasscheck__(self, subclass: type) -> bool: key = (self, subclass) if key in StructuralTyping.cache: return StructuralTyping.cache[key] # logger.info(f"{subclass.__name__} <= {self.__name__}") try: can = can_be_used_as2(subclass, self) except: if PYTHON_36: return False else: raise res = can.result StructuralTyping.cache[key] = res return res def __instancecheck__(self, instance) -> bool: T = type(instance) if T is self: return True if not is_dataclass(T): return False i = super().__instancecheck__(instance) if i: return True # logger.info(f"in {T.__name__} <= {self.__name__}") # res = can_be_used_as2(T, self) return self.__subclasscheck__(T) # return res.result class MyABC(StructuralTyping, ABCMeta): def __new__(mcs, name_orig: str, bases, namespace, **kwargs): # logger.info(name_orig=name_orig, bases=bases, namespace=namespace, kwargs=kwargs) clsi = None if "di" in namespace: clsi = cast(DataclassInfo, namespace["di"]) # logger.info('got clsi from namespace', clsi) else: if bases: # this is when we subclass base_info = get_dataclass_info(bases[-1]) clsi = DataclassInfo(name="", orig=base_info.get_open()) # logger.info('got clsi from subclass', base_info=base_info, clsi=clsi) if clsi is None: default = DataclassInfo(name=name_orig, orig=()) clsi = default name = clsi.name = get_name_for(name_orig, clsi) # noinspection PyArgumentList cls = super().__new__(mcs, name, bases, namespace, **kwargs) qn = cls.__qualname__.replace("." + name_orig, "." + name) setattr(cls, "__qualname__", qn) # logger.info(f" old module {cls.__module__} new {mcs.__module__}") # setattr(cls, "__module__", mcs.__module__) set_dataclass_info(cls, clsi) return cls def get_name_for(name_orig: str, clsi: DataclassInfo) -> str: name0 = get_name_without_brackets(name_orig) params = [] for x in clsi.orig: # params.append(replace_typevars(x, bindings=clsi.bindings, symbols={})) params.append(x) if not params: return name0 else: name = f"{name0}[%s]" % (",".join(name_for_type_like(_) for _ in params)) return name if PYTHON_36: # pragma: no cover class FakeGenericMeta(MyABC): def __getitem__(self, params2): clsi = get_dataclass_info(self) types_open = clsi.get_open() types2 = as_tuple(params2) assert isinstance(types2, tuple), types2 for t in types2: assert is_TypeLike(t), (t, types2) if types_open == types2: return self bindings: Dict[TypeVar, TypeVar] = {} for T, U in zip(types_open, types2): bindings[T] = U bound = get_TypeVar_bound(T) if bound is not None: try: can = can_be_used_as2(U, bound) except (TypeError, ValueError) as e: if PYTHON_36: continue else: raise # raise ZTypeError(U=U, bound=bound) from e else: if not can: msg = ( f'For type parameter "{name_for_type_like(T)}", expected a ' f'subclass of "{name_for_type_like(bound)}", found {U}.' ) raise ZTypeError(msg, can=can, T=T, bound=bound, U=U) return make_type(self, bindings) else: FakeGenericMeta = MyABC class GenericProxy(metaclass=FakeGenericMeta): @abstractmethod def need(self) -> None: """""" @classmethod def __class_getitem__(cls, params2) -> type: clsi = get_dataclass_info(cls) types_open = clsi.get_open() types2 = as_tuple(params2) if len(types_open) != len(types2): msg = "Cannot match type length" raise ZValueError( msg, cls=cls.__name__, clsi=get_dataclass_info(cls), types=types_open, types2=types2 ) bindings = {} for T, U in zip(types_open, types2): bindings[T] = U bound = get_TypeVar_bound(T) if (bound is not None) and (bound is not object) and isinstance(bound, type): # logger.info(f"{U} should be usable as {T.__bound__}") # logger.info( # f" issubclass({U}, {T.__bound__}) =" # f" {issubclass(U, T.__bound__)}" # ) try: # issub = issubclass(U, bound) issub = can_be_used_as2(U, bound) except TypeError as e: msg = "" raise ZTypeError(msg, T=T, T_bound=bound, U=U) from e if not issub: msg = ( f'For type parameter "{T.__name__}", expected a' f'subclass of "{bound.__name__}", found @U.' ) raise ZTypeError(msg, T=T, T_bound=bound, U=U) res = make_type(cls, bindings) # from .monkey_patching_typing import remember_created_class # # remember_created_class(res, "__class_getitem__") return res class Fake: symbols: dict myt: type def __init__(self, myt, symbols: dict): self.myt = myt n = name_for_type_like(myt) self.name_without = get_name_without_brackets(n) self.symbols = symbols def __getitem__(self, item: type) -> type: n = name_for_type_like(item) complete = f"{self.name_without}[{n}]" if complete in self.symbols: res = self.symbols[complete] else: # noinspection PyUnresolvedReferences res = self.myt[item] # myt = self.myt, symbols = self.symbols, # d = debug_print(dict(item=item, res=res)) # logger.error(f"Fake:getitem", myt=self.myt, item=item, res=res) return res def resolve_types(T, locals_=None, refs: Tuple = (), nrefs: Optional[Dict[str, Any]] = None): if nrefs is None: nrefs = {} assert is_dataclass(T) clsi = get_dataclass_info(T) # rl = RecLogger() if locals_ is None: locals_ = {} symbols = dict(locals_) for k, v in nrefs.items(): symbols[k] = v others = getattr(T, DEPENDS_ATT, ()) for t in (T,) + refs + others: n = name_for_type_like(t) symbols[n] = t # logger.info(f't = {t} n {n}') name_without = get_name_without_brackets(n) # if name_without in ['Union', 'Dict', ]: # # FIXME please add more here # continue if name_without not in symbols: symbols[name_without] = Fake(t, symbols) # else: # pass for x in clsi.get_open(): # (T, GENERIC_ATT2, ()): if hasattr(x, "__name__"): symbols[x.__name__] = x # logger.debug(f'symbols: {symbols}') annotations: Dict[str, TypeLike] = getattr(T, ANNOTATIONS_ATT, {}) # add in case it was not there setattr(T, ANNOTATIONS_ATT, annotations) for k, v in annotations.items(): if not isinstance(v, str) and is_ClassVar(v): continue # XXX v = cast(TypeLike, v) try: r = replace_typevars(v, bindings={}, symbols=symbols) # rl.p(f'{k!r} -> {v!r} -> {r!r}') annotations[k] = r except NameError: # msg = ( # f"resolve_type({T.__name__}):" # f' Cannot resolve names for attribute "{k}" = {v!r}.' # ) # msg += f'\n symbols: {symbols}' # msg += '\n\n' + indent(traceback.format_exc(), '', '> ') # raise NameError(msg) from e # logger.warning(msg) continue except TypeError as e: # pragma: no cover msg = f'Cannot resolve type for attribute "{k}".' raise ZTypeError(msg) from e for f in fields(T): assert f.name in annotations # msg = f'Cannot get annotation for field {f.name!r}' # logger.warning(msg) # continue # logger.info(K=T.__name__, name=f.name, before=f.type, after=annotations[f.name], # a=annotations[f.name].__dict__) f.type = annotations[f.name] # logger.info(K=T.__name__, anns=getattr(T, '__annotations__',"?"), annotations=annotations) def type_check(type_self: type, k: str, T_expected: type, value_found: object): try: enable_difficult = ZuperTypingGlobals.enable_type_checking_difficult T_found = type(value_found) simple = T_found in [int, float, bool, str, bytes, Decimal, datetime] definitely_exclude = T_found in [dict, list, tuple] do_it = (not definitely_exclude) and (enable_difficult or simple) if do_it: ok = value_liskov(value_found, T_expected) if not ok: # pragma: no cover type_self_name = name_for_type_like(type_self) # T_expected_name = name_for_type_like(T_expected) # T_found_name = name_for_type_like(T_found) msg = f"Error for field {k!r} of class {type_self_name}" # warnings.warn(msg, stacklevel=3) raise ZValueError( msg, field=k, why=ok, expected_type=T_expected, found_value=value_found, found_type=type(value_found), ) except TypeError as e: # pragma: no cover msg = f"Cannot judge annotation of {k} (supposedly {value_found!r})." if sys.version_info[:2] == (3, 6): # FIXME: warn return logger.error(msg) raise TypeError(msg) from e def make_type( cls: Type[dataclass], bindings: Dict[type, type], # TypeVars symbols: Optional[Dict[str, type]] = None, ) -> type: if symbols is None: symbols = {} clsi = get_dataclass_info(cls) key = tuple(bindings.items()) + tuple(symbols.items()) if key in clsi.specializations: return clsi.specializations[key] try: res = make_type_(cls, bindings, symbols) except ZValueError as e: # pragma: no cover msg = "Cannot run make_type" raise ZValueError(msg, cls=cls, bindings=bindings, symbols=symbols) from e clsi.specializations[key] = res return res def make_type_( cls: Type[dataclass], bindings0: Dict[type, type], # TypeVars symbols: Optional[Dict[str, type]] = None, ) -> type: clsi = get_dataclass_info(cls) # We only allow the binding of the open ones bindings: Dict[type, type] = {} open = clsi.get_open() for k, v in bindings0.items(): if k in open: bindings[k] = v else: pass if not bindings: return cls if symbols is None: symbols = {} symbols = dict(symbols) refs = getattr(cls, DEPENDS_ATT, ()) for r in refs: # n = name_for_type_like(r) n = r.__name__ symbols[get_name_without_brackets(n)] = r assert not is_NewType(cls), cls cache_key = (str(cls), str(bindings), str(clsi.orig)) if ZuperTypingGlobals.cache_enabled: if cache_key in MakeTypeCache.cache: # logger.info(f"using cached value for {cache_key}") return MakeTypeCache.cache[cache_key] recur = lambda _: replace_typevars(_, bindings=bindings, symbols=symbols) new_bindings = bindings # its_globals = dict(sys.modules[cls.__module__].__dict__) # # its_globals[get_name_without_brackets(cls.__name__)] = cls # try: # annotations = typing.get_type_hints(cls, its_globals) # except: # logger.info(f'globals for {cls.__name__}', cls.__module__, list(its_globals)) # raise annotations = getattr(cls, ANNOTATIONS_ATT, {}) name_without = get_name_without_brackets(cls.__name__) def param_name(x: type) -> str: x = replace_typevars(x, bindings=new_bindings, symbols=symbols) return name_for_type_like(x) if clsi.orig: pnames = tuple(param_name(_) for _ in clsi.orig) name2 = "%s[%s]" % (name_without, ",".join(pnames)) else: name2 = name_without try: # def __new__(_cls, *args, **kwargs): # print('creating object') # x = super().__new__(_cls, *args, **kwargs) # return x cls2 = type(name2, (cls,), {"need": lambda: None}) # cls2.__new__ = __new__ except TypeError as e: # pragma: no cover msg = f'Cannot create derived class "{name2}" from the class.' raise ZTypeError(msg, cls=cls) from e symbols[name2] = cls2 symbols[cls.__name__] = cls2 # also MyClass[X] should resolve to the same MakeTypeCache.cache[cache_key] = cls2 class Fake2: def __getitem__(self, item): n = name_for_type_like(item) complete = f"{name_without}[{n}]" if complete in symbols: return symbols[complete] logger.info(f"Fake2:getitem", name_for_type_like(cls), complete=complete) # noinspection PyUnresolvedReferences return cls[item] if name_without not in symbols: symbols[name_without] = Fake2() for T, U in bindings.items(): symbols[T.__name__] = U if hasattr(U, "__name__"): # dict does not have name symbols[U.__name__] = U new_annotations = {} for k, v0 in annotations.items(): v = recur(v0) # print(f'{v0!r} -> {v!r}') if is_ClassVar(v): s = get_ClassVar_arg(v) if is_Type(s): st = get_Type_arg(s) concrete = recur(st) new_annotations[k] = ClassVar[type] setattr(cls2, k, concrete) else: s2 = recur(s) new_annotations[k] = ClassVar[s2] else: new_annotations[k] = v original__post_init__ = getattr(cls, "__post_init__", None) if ZuperTypingGlobals.enable_type_checking: def __post_init__(self): # do it first (because they might change things around) if original__post_init__ is not None: original__post_init__(self) for k, T_expected in new_annotations.items(): if is_ClassVar(T_expected): continue if isinstance(T_expected, type): val = getattr(self, k) type_check(type(self), k=k, value_found=val, T_expected=T_expected) # important: do it before dataclass setattr(cls2, "__post_init__", __post_init__) cls2.__annotations__ = new_annotations # logger.info('new annotations: %s' % new_annotations) if is_dataclass(cls): frozen = is_frozen(cls) cls2 = dataclass(cls2, unsafe_hash=True, frozen=frozen) else: # noinspection PyUnusedLocal def init_placeholder(self, *args, **kwargs): if args or kwargs: msg = ( f"Default constructor of {cls2.__name__} does not know " f"what to do with arguments." ) msg += f"\nargs: {args!r}\nkwargs: {kwargs!r}" msg += f"\nself: {self}" msg += f"\nself: {dir(type(self))}" msg += f"\nself: {type(self)}" raise NoConstructorImplemented(msg) if cls.__init__ == object.__init__: setattr(cls2, "__init__", init_placeholder) cls2.__module__ = cls.__module__ setattr(cls2, "__name__", name2) setattr(cls2, "__doc__", getattr(cls, "__doc__")) qn = cls.__qualname__ qn0, sep, _ = qn.rpartition(".") if not sep: sep = "" setattr(cls2, "__qualname__", qn0 + sep + name2) orig2 = tuple(replace_typevars(x, bindings=new_bindings, symbols=symbols) for x in clsi.orig) clsi2 = DataclassInfo(name=name2, orig=orig2) set_dataclass_info(cls2, clsi2) MakeTypeCache.cache[cache_key] = cls2 return cls2 def is_frozen(t): return getattr(t, _PARAMS).frozen
zuper-typing-z6
/zuper-typing-z6-6.2.3.tar.gz/zuper-typing-z6-6.2.3/src/zuper_typing/zeneric2.py
zeneric2.py
import typing from dataclasses import _FIELDS, dataclass as dataclass_orig, Field, is_dataclass from typing import ( Any, Callable, cast, ClassVar, Dict, Iterable, Iterator, List, Optional, Sequence, Set, Tuple, Type, TYPE_CHECKING, TypeVar, Union, ) from zuper_commons.types import ZAssertionError, ZTypeError, ZValueError # from .my_intersection import Intersection from .aliases import TypeLike from .constants import ( ATT_TUPLE_TYPES, NAME_ARG, PYTHON_36, ZuperTypingGlobals, ATT_LIST_TYPE, TUPLE_EMPTY_ATTR, ) from .literal import get_Literal_args, is_Literal from .uninhabited import is_Uninhabited __all__ = [ "is_Set", "is_List", "is_Dict", "is_Optional", "is_Union", "is_Tuple", "is_Literal", "is_dataclass", "is_TypeLike", "is_TypeVar", "is_Awaitable", "is_Any", "is_Callable", "is_ClassVar", "is_FixedTuple", "is_FixedTupleLike_canonical", "is_ForwardRef", "is_Iterable", "is_Iterator", "is_List_canonical", "is_MyNamedArg", "is_NewType", "is_Sequence", "is_SpecialForm", "is_Type", "is_VarTuple", "is_VarTuple_canonical", "get_Set_name_V", "get_Set_arg", "get_List_arg", "get_Dict_name_K_V", "get_Dict_args", "get_Literal_args", "get_TypeVar_bound", "get_TypeVar_name", "get_Optional_arg", "get_Union_args", "get_Awaitable_arg", "get_Callable_info", "get_ClassVar_arg", "get_ClassVar_name", "get_Dict_name", "get_fields_including_static", "get_FixedTuple_args", "get_ForwardRef_arg", "get_Iterable_arg", "get_Iterable_name", "get_Iterator_arg", "get_Iterator_name", "get_List_name", "get_MyNamedArg_name", "get_NewType_arg", "get_NewType_name", "get_NewType_repr", "get_Optional_name", "get_Sequence_arg", "get_Sequence_name", "get_Set_name", "get_Tuple_name", "get_tuple_types", "get_Type_arg", "get_Type_name", "get_Union_name", "get_VarTuple_arg", "name_for_type_like", "make_ForwardRef", "make_Tuple", "make_TypeVar", "make_Union", "make_VarTuple", "key_for_sorting_types", "MyBytes", "MyStr", "get_ListLike_arg", "get_FixedTupleLike_args", "get_CustomTuple_args", "get_CustomDict_args", "get_CustomList_arg", "get_CustomSet_arg", "get_Dict_args", "get_DictLike_args", "get_Dict_name_K_V", "get_List_arg", "get_DictLike_name", "get_ListLike_name", "get_Set_arg", "get_Set_name_V", "get_SetLike_arg", "get_SetLike_name", "is_ListLike", "is_CustomDict", "is_CustomList", "is_CustomSet", "is_CustomTuple", "is_Dict", "is_DictLike", "is_DictLike_canonical", "is_FixedTupleLike", "is_List", "is_ListLike_canonical", "is_Set", "is_SetLike", "is_SetLike_canonical", "make_list", "make_CustomTuple", "make_dict", "make_set", "CustomTuple", "CustomDict", "CustomList", "CustomSet", "lift_to_customtuple", "lift_to_customtuple_type", "is_TupleLike", "get_FixedTupleLike_args", "get_FixedTupleLike_name", ] def is_TypeLike(x: object) -> bool: if isinstance(x, type): return True else: # noinspection PyTypeChecker return ( is_SpecialForm(x) or is_ClassVar(x) or is_MyNamedArg(x) or is_Type(x) or is_TypeVar(x) or is_NewType(x) ) def is_SpecialForm(x: TypeLike) -> bool: """ Does not include: ClassVar, NamedArg, Type, TypeVar Does include: ForwardRef, NewType, Literal """ if ( is_Any(x) or is_Callable(x) or is_Dict(x) or is_Tuple(x) or is_ForwardRef(x) or is_Iterable(x) or is_Iterator(x) or is_List(x) or is_NewType(x) or is_Optional(x) or is_Sequence(x) or is_Set(x) or is_Tuple(x) or is_Union(x) or is_Awaitable(x) or is_Literal(x) ): return True return False # noinspection PyProtectedMember def is_Optional(x: TypeLike) -> bool: if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences return isinstance(x, typing._Union) and len(x.__args__) >= 2 and x.__args__[-1] is type(None) else: # noinspection PyUnresolvedReferences return ( isinstance(x, typing._GenericAlias) and (getattr(x, "__origin__") is Union) and len(x.__args__) >= 2 and x.__args__[-1] is type(None) ) X = TypeVar("X") def get_Optional_arg(x: Type[Optional[X]]) -> Type[X]: assert is_Optional(x) args = x.__args__ if len(args) == 2: return args[0] else: return make_Union(*args[:-1]) # return x.__args__[0] def is_Union(x: TypeLike) -> bool: """ Union[X, None] is not considered a Union""" if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences return not is_Optional(x) and isinstance(x, typing._Union) else: # noinspection PyUnresolvedReferences return not is_Optional(x) and isinstance(x, typing._GenericAlias) and (x.__origin__ is Union) def get_Union_args(x: TypeLike) -> Tuple[TypeLike, ...]: assert is_Union(x), x # noinspection PyUnresolvedReferences return tuple(x.__args__) def key_for_sorting_types(y: TypeLike) -> tuple: if is_TypeVar(y): return (1, get_TypeVar_name(y)) elif is_dataclass(y): return (2, name_for_type_like(y)) # This never happens because NoneType is removed # (we do Optional) # elif y is type(None): # return (3, "") else: return (0, name_for_type_like(y)) def remove_duplicates(a: Tuple[TypeLike]) -> Tuple[TypeLike]: done = [] for _ in a: assert is_TypeLike(_), a if _ not in done: done.append(_) return tuple(done) def unroll_union(a: TypeLike) -> Tuple[TypeLike, ...]: if is_Union(a): return get_Union_args(a) elif is_Optional(a): return get_Optional_arg(a), type(None) else: return (a,) def make_Union(*a: TypeLike) -> TypeLike: r = () for _ in a: if not is_TypeLike(_): raise ZValueError(not_typelike=_, inside=a) r = r + unroll_union(_) a = r if len(a) == 0: raise ValueError("empty") a = remove_duplicates(a) if len(a) == 1: return a[0] # print(list(map(key_for_sorting_types, a))) if type(None) in a: others = tuple(_ for _ in a if _ is not type(None)) return Optional[make_Union(*others)] a = tuple(sorted(a, key=key_for_sorting_types)) if len(a) == 2: x = Union[a[0], a[1]] elif len(a) == 3: x = Union[a[0], a[1], a[2]] elif len(a) == 4: x = Union[a[0], a[1], a[2], a[3]] elif len(a) == 5: x = Union[a[0], a[1], a[2], a[3], a[4]] else: x = Union.__getitem__(tuple(a)) return x class MakeTupleCaches: tuple_caches = {} def make_VarTuple(a: Type[X]) -> Type[Tuple[X, ...]]: args = (a, ...) res = make_Tuple(*args) return res class DummyForEmpty: pass def make_Tuple(*a: TypeLike) -> Type[Tuple]: for _ in a: if isinstance(_, tuple): raise ValueError(a) if a in MakeTupleCaches.tuple_caches: return MakeTupleCaches.tuple_caches[a] if len(a) == 0: x = Tuple[DummyForEmpty] setattr(x, TUPLE_EMPTY_ATTR, True) elif len(a) == 1: x = Tuple[a[0]] elif len(a) == 2: x = Tuple[a[0], a[1]] elif len(a) == 3: x = Tuple[a[0], a[1], a[2]] elif len(a) == 4: x = Tuple[a[0], a[1], a[2], a[3]] elif len(a) == 5: x = Tuple[a[0], a[1], a[2], a[3], a[4]] else: if PYTHON_36: # pragma: no cover x = Tuple[a] else: # NOTE: actually correct # noinspection PyArgumentList x = Tuple.__getitem__(tuple(a)) MakeTupleCaches.tuple_caches[a] = x return x def _check_valid_arg(x: Any) -> None: if not ZuperTypingGlobals.paranoid: return if isinstance(x, str): # pragma: no cover msg = f"The annotations must be resolved: {x!r}" raise ValueError(msg) def is_ForwardRef(x: TypeLike) -> bool: _check_valid_arg(x) if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences return isinstance(x, typing._ForwardRef) else: # noinspection PyUnresolvedReferences return isinstance(x, typing.ForwardRef) class CacheFor: cache = {} def make_ForwardRef(n: str) -> TypeLike: if n in CacheFor.cache: return CacheFor.cache[n] if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences res = typing._ForwardRef(n) else: # noinspection PyUnresolvedReferences res = typing.ForwardRef(n) CacheFor.cache[n] = res return res def get_ForwardRef_arg(x: TypeLike) -> str: assert is_ForwardRef(x) # noinspection PyUnresolvedReferences return x.__forward_arg__ def is_Any(x: TypeLike) -> bool: _check_valid_arg(x) if PYTHON_36: # pragma: no cover return x is Any else: # noinspection PyUnresolvedReferences return isinstance(x, typing._SpecialForm) and x._name == "Any" class CacheTypeVar: cache = {} if TYPE_CHECKING: make_TypeVar = TypeVar else: def make_TypeVar( name: str, *, bound: Optional[type] = None, contravariant: bool = False, covariant: bool = False, ) -> TypeVar: key = (name, bound, contravariant, covariant) if key in CacheTypeVar.cache: return CacheTypeVar.cache[key] # noinspection PyTypeHints res = TypeVar(name, bound=bound, contravariant=contravariant, covariant=covariant) CacheTypeVar.cache[key] = res return res def is_TypeVar(x: TypeLike) -> bool: return isinstance(x, typing.TypeVar) def get_TypeVar_bound(x: TypeVar) -> TypeLike: assert is_TypeVar(x), x bound = x.__bound__ if bound is None: return object else: return bound def get_TypeVar_name(x: TypeVar) -> str: assert is_TypeVar(x), x return x.__name__ def is_ClassVar(x: TypeLike) -> bool: _check_valid_arg(x) if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences return isinstance(x, typing._ClassVar) else: # noinspection PyUnresolvedReferences return isinstance(x, typing._GenericAlias) and (x.__origin__ is typing.ClassVar) def get_ClassVar_arg(x: TypeLike) -> TypeLike: # cannot put ClassVar assert is_ClassVar(x), x if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences return x.__type__ else: # noinspection PyUnresolvedReferences return x.__args__[0] def get_ClassVar_name(x: TypeLike) -> str: # cannot put ClassVar assert is_ClassVar(x), x s = name_for_type_like(get_ClassVar_arg(x)) return f"ClassVar[{s}]" def is_Type(x: TypeLike) -> bool: _check_valid_arg(x) if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences return (x is typing.Type) or (isinstance(x, typing.GenericMeta) and (x.__origin__ is typing.Type)) else: # noinspection PyUnresolvedReferences return (x is typing.Type) or (isinstance(x, typing._GenericAlias) and (x.__origin__ is type)) def is_NewType(x: TypeLike) -> bool: _check_valid_arg(x) # if PYTHON_36: # pragma: no cover # # noinspection PyUnresolvedReferences # return (x is typing.Type) or (isinstance(x, typing.GenericMeta) and (x.__origin__ # is typing.Type)) # else: # return (x is typing.Type) or (isinstance(x, typing._GenericAlias) and (x.__origin__ is # type)) res = hasattr(x, "__supertype__") and type(x).__name__ == "function" return res def get_NewType_arg(x: TypeLike) -> TypeLike: assert is_NewType(x), x # noinspection PyUnresolvedReferences return x.__supertype__ def get_NewType_name(x: TypeLike) -> str: return x.__name__ def get_NewType_repr(x: TypeLike) -> str: n = get_NewType_name(x) p = get_NewType_arg(x) if is_Any(p) or p is object: return f"NewType({n!r})" else: sp = name_for_type_like(p) return f"NewType({n!r}, {sp})" def is_Tuple(x: TypeLike) -> bool: _check_valid_arg(x) if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences return isinstance(x, typing.TupleMeta) else: # noinspection PyUnresolvedReferences return isinstance(x, typing._GenericAlias) and (x._name == "Tuple") def is_FixedTuple(x: TypeLike) -> bool: if not is_Tuple(x): return False x = cast(Type[Tuple], x) ts = get_tuple_types(x) # if len(ts) == 0: # return False if len(ts) == 2 and ts[-1] is ...: return False else: return True def is_VarTuple(x: TypeLike) -> bool: if x is tuple: return True if not is_Tuple(x): return False x = cast(Type[Tuple], x) ts = get_tuple_types(x) if len(ts) == 2 and ts[-1] is ...: return True else: return False def get_FixedTuple_args(x: Type[Tuple]) -> Tuple[TypeLike, ...]: assert is_FixedTuple(x), x return get_tuple_types(x) def is_VarTuple_canonical(x: Type[Tuple]) -> bool: return (x is not tuple) and (x is not Tuple) # # def is_FixedTuple_canonical(x: Type[Tuple]) -> bool: # return (x is not tuple) and (x is not Tuple) def is_FixedTupleLike_canonical(x: Type[Tuple]) -> bool: return (x is not tuple) and (x is not Tuple) def get_VarTuple_arg(x: Type[Tuple[X, ...]]) -> Type[X]: if x is tuple: return Any assert is_VarTuple(x), x ts = get_tuple_types(x) # if len(ts) == 0: # pragma: no cover # return Any return ts[0] def is_generic_alias(x: TypeLike, name: str) -> bool: # noinspection PyUnresolvedReferences return isinstance(x, typing._GenericAlias) and (x._name == name) def is_List(x: TypeLike) -> bool: _check_valid_arg(x) if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences return x is typing.List or isinstance(x, typing.GenericMeta) and x.__origin__ is typing.List else: return is_generic_alias(x, "List") def is_Iterator(x: TypeLike) -> bool: _check_valid_arg(x) if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences return x is typing.Iterator or isinstance(x, typing.GenericMeta) and x.__origin__ is typing.Iterator else: return is_generic_alias(x, "Iterator") def is_Iterable(x: TypeLike) -> bool: _check_valid_arg(x) if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences return x is typing.Iterable or isinstance(x, typing.GenericMeta) and x.__origin__ is typing.Iterable else: return is_generic_alias(x, "Iterable") def is_Sequence(x: TypeLike) -> bool: _check_valid_arg(x) if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences return x is typing.Sequence or isinstance(x, typing.GenericMeta) and x.__origin__ is typing.Sequence else: return is_generic_alias(x, "Sequence") def is_placeholder_typevar(x: TypeLike) -> bool: return is_TypeVar(x) and get_TypeVar_name(x) in ["T", "T_co"] def get_Set_arg(x: Type[Set]) -> TypeLike: assert is_Set(x) if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences if x is typing.Set: return Any # noinspection PyUnresolvedReferences t = x.__args__[0] if is_placeholder_typevar(t): return Any return t def get_List_arg(x: Type[List[X]]) -> Type[X]: assert is_List(x), x if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences if x.__args__ is None: return Any # noinspection PyUnresolvedReferences t = x.__args__[0] if is_placeholder_typevar(t): return Any return t def is_List_canonical(x: Type[List]) -> bool: assert is_List(x), x if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences if x.__args__ is None: return False # noinspection PyUnresolvedReferences t = x.__args__[0] if is_placeholder_typevar(t): return False return True _K = TypeVar("_K") _V = TypeVar("_V") def get_Dict_args(T: Type[Dict[_K, _V]]) -> Tuple[Type[_K], Type[_V]]: assert is_Dict(T), T if T is Dict: return Any, Any # noinspection PyUnresolvedReferences K, V = T.__args__ if PYTHON_36: # pragma: no cover if is_placeholder_typevar(K): K = Any if is_placeholder_typevar(V): V = Any return K, V _X = TypeVar("_X") def get_Iterator_arg(x: TypeLike) -> TypeLike: # PyCharm has problems assert is_Iterator(x), x if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences if x.__args__ is None: return Any # noinspection PyUnresolvedReferences t = x.__args__[0] if is_placeholder_typevar(t): return Any return t def get_Iterable_arg(x: TypeLike) -> TypeLike: # PyCharm has problems assert is_Iterable(x), x if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences if x.__args__ is None: return Any # noinspection PyUnresolvedReferences t = x.__args__[0] if is_placeholder_typevar(t): return Any return t def get_Sequence_arg(x: Type[Sequence[_X]]) -> Type[_X]: assert is_Sequence(x), x if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences if x.__args__ is None: return Any # noinspection PyUnresolvedReferences t = x.__args__[0] if is_placeholder_typevar(t): return Any return t def get_Type_arg(x: TypeLike) -> TypeLike: assert is_Type(x) if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences if x.__args__ is None: return type # noinspection PyUnresolvedReferences return x.__args__[0] def is_Callable(x: TypeLike) -> bool: _check_valid_arg(x) if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences return isinstance(x, typing.CallableMeta) else: return getattr(x, "_name", None) == "Callable" # return hasattr(x, '__origin__') and x.__origin__ is typing.Callable # return isinstance(x, typing._GenericAlias) and x.__origin__.__name__ == "Callable" def is_Awaitable(x: TypeLike) -> bool: if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences return getattr(x, "_gorg", None) is typing.Awaitable else: return getattr(x, "_name", None) == "Awaitable" def get_Awaitable_arg(x: TypeLike) -> TypeLike: if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences if x.__args__ is None: return Any # noinspection PyUnresolvedReferences t = x.__args__[0] if is_placeholder_typevar(t): return Any return t def is_MyNamedArg(x: object) -> bool: return hasattr(x, NAME_ARG) def get_MyNamedArg_name(x: TypeLike) -> str: assert is_MyNamedArg(x), x return getattr(x, NAME_ARG) def is_Dict(x: TypeLike) -> bool: _check_valid_arg(x) if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences return x is Dict or isinstance(x, typing.GenericMeta) and x.__origin__ is typing.Dict else: return is_generic_alias(x, "Dict") def is_Set(x: TypeLike) -> bool: _check_valid_arg(x) if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences if x is typing.Set: return True # noinspection PyUnresolvedReferences return isinstance(x, typing.GenericMeta) and x.__origin__ is typing.Set else: return is_generic_alias(x, "Set") or is_generic_alias(x, "FrozenSet") # XXX: hack def get_Dict_name(T: Type[Dict]) -> str: assert is_Dict(T), T K, V = get_Dict_args(T) return get_Dict_name_K_V(K, V) def get_Dict_name_K_V(K: TypeLike, V: TypeLike) -> str: return "Dict[%s,%s]" % (name_for_type_like(K), name_for_type_like(V)) def get_Set_name_V(V: TypeLike) -> str: return "Set[%s]" % (name_for_type_like(V)) def get_Union_name(V: TypeLike) -> str: return "Union[%s]" % ",".join(name_for_type_like(_) for _ in get_Union_args(V)) def get_List_name(V: Type[List]) -> str: v = get_List_arg(V) return "List[%s]" % name_for_type_like(v) def get_Type_name(V: TypeLike) -> str: v = get_Type_arg(V) return "Type[%s]" % name_for_type_like(v) def get_Iterator_name(V: Type[Iterator]) -> str: # noinspection PyTypeChecker v = get_Iterator_arg(V) return "Iterator[%s]" % name_for_type_like(v) def get_Iterable_name(V: Type[Iterable[X]]) -> str: # noinspection PyTypeChecker v = get_Iterable_arg(V) return "Iterable[%s]" % name_for_type_like(v) def get_Sequence_name(V: Type[Sequence]) -> str: v = get_Sequence_arg(V) return "Sequence[%s]" % name_for_type_like(v) def get_Optional_name(V: TypeLike) -> str: # cannot use Optional as type arg v = get_Optional_arg(V) return "Optional[%s]" % name_for_type_like(v) def get_Set_name(V: Type[Set]) -> str: v = get_Set_arg(V) return "Set[%s]" % name_for_type_like(v) def get_Tuple_name(V: Type[Tuple]) -> str: return "Tuple[%s]" % ",".join(name_for_type_like(_) for _ in get_tuple_types(V)) def get_tuple_types(V: Type[Tuple]) -> Tuple[TypeLike, ...]: # from .annotations_tricks import is_CustomTuple, get_CustomTuple_args, CustomTuple if is_CustomTuple(V): V = cast(Type[CustomTuple], V) args = get_CustomTuple_args(V) return args if V is tuple: return Any, ... if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences if V.__args__ is None: return Any, ... # noinspection PyUnresolvedReferences args = V.__args__ # XXX if args == (DummyForEmpty,): return () if args == (): if hasattr(V, TUPLE_EMPTY_ATTR): return () else: return Any, ... else: return args def name_for_type_like(x: TypeLike) -> str: if is_Any(x): return "Any" elif isinstance(x, typing.TypeVar): return x.__name__ elif x is type(None): return "NoneType" elif x is MyStr: return "str" elif x is MyBytes: return "bytes" elif is_Union(x): return get_Union_name(x) elif is_List(x): x = cast(Type[List], x) return get_List_name(x) elif is_Iterator(x): x = cast(Type[Iterator], x) # noinspection PyTypeChecker return get_Iterator_name(x) elif is_Iterable(x): x = cast(Type[Iterable], x) # noinspection PyTypeChecker return get_Iterable_name(x) elif is_Tuple(x): x = cast(Type[Tuple], x) return get_Tuple_name(x) elif is_Set(x): x = cast(Type[Set], x) return get_Set_name(x) elif is_SetLike(x): x = cast(Type[Set], x) return get_SetLike_name(x) elif is_Dict(x): x = cast(Type[Dict], x) return get_Dict_name(x) elif is_DictLike(x): x = cast(Type[Dict], x) return get_DictLike_name(x) elif is_Type(x): return get_Type_name(x) elif is_ClassVar(x): return get_ClassVar_name(x) elif is_Sequence(x): x = cast(Type[Sequence], x) return get_Sequence_name(x) elif is_Optional(x): return get_Optional_name(x) elif is_NewType(x): return get_NewType_name(x) # return get_NewType_repr(x) elif is_Literal(x): s = ",".join(repr(_) for _ in get_Literal_args(x)) return f"Literal[{s}]" elif is_ForwardRef(x): a = get_ForwardRef_arg(x) return f"ForwardRef({a!r})" elif is_Uninhabited(x): return "!" elif is_Callable(x): info = get_Callable_info(x) # params = ','.join(name_for_type_like(p) for p in info.parameters_by_position) def ps(k, v): if k.startswith("__"): return name_for_type_like(v) else: return f"NamedArg({name_for_type_like(v)},{k!r})" params = ",".join(ps(k, v) for k, v in info.parameters_by_name.items()) ret = name_for_type_like(info.returns) return f"Callable[[{params}],{ret}]" elif x is typing.IO: return str(x) # TODO: should get the attribute elif hasattr(x, "__name__"): # logger.info(f'not matching __name__ {type(x)} {x!r}') return x.__name__ else: # logger.info(f'not matching {type(x)} {x!r}') return str(x) # do not make a dataclass class CallableInfo: parameters_by_name: Dict[str, TypeLike] parameters_by_position: Tuple[TypeLike, ...] ordering: Tuple[str, ...] returns: TypeLike def __init__(self, parameters_by_name, parameters_by_position, ordering, returns): for k, v in parameters_by_name.items(): assert not is_MyNamedArg(v), v for v in parameters_by_position: assert not is_MyNamedArg(v), v self.parameters_by_name = parameters_by_name self.parameters_by_position = parameters_by_position self.ordering = ordering self.returns = returns def __repr__(self) -> str: return ( f"CallableInfo({self.parameters_by_name!r}, {self.parameters_by_position!r}, " f"{self.ordering}, {self.returns})" ) def replace(self, f: typing.Callable[[Any], Any]) -> "CallableInfo": parameters_by_name = {k: f(v) for k, v in self.parameters_by_name.items()} parameters_by_position = tuple(f(v) for v in self.parameters_by_position) ordering = self.ordering returns = f(self.returns) return CallableInfo(parameters_by_name, parameters_by_position, ordering, returns) def as_callable(self) -> typing.Callable: args = [] for k, v in self.parameters_by_name.items(): # if is_MyNamedArg(v): # # try: # v = v.original # TODO: add MyNamedArg args.append(v) # noinspection PyTypeHints return Callable[args, self.returns] def get_Callable_info(x: Type[typing.Callable]) -> CallableInfo: assert is_Callable(x), x parameters_by_name = {} parameters_by_position = [] ordering = [] args = x.__args__ if args: returns = args[-1] rest = args[:-1] else: returns = Any rest = () for i, a in enumerate(rest): if is_MyNamedArg(a): name = get_MyNamedArg_name(a) t = a.original # t = a else: name = f"{i}" t = a parameters_by_name[name] = t ordering.append(name) parameters_by_position.append(t) return CallableInfo( parameters_by_name=parameters_by_name, parameters_by_position=tuple(parameters_by_position), ordering=tuple(ordering), returns=returns, ) def get_fields_including_static(x: Type[dataclass_orig]) -> Dict[str, Field]: """ returns the fields including classvars """ fields = getattr(x, _FIELDS) return fields # _V = TypeVar("_V") # _K = TypeVar("_K") # # _X = TypeVar("_X") _Y = TypeVar("_Y") _Z = TypeVar("_Z") class MyBytes(bytes): pass class MyStr(str): pass class CustomSet(set): __set_type__: ClassVar[type] def __hash__(self) -> Any: try: return self._cached_hash except AttributeError: try: h = self._cached_hash = hash(tuple(sorted(self))) except TypeError: # pragma: no cover h = self._cached_hash = hash(tuple(self)) return h class CustomList(list): __list_type__: ClassVar[type] def __hash__(self) -> Any: # pragma: no cover try: return self._cached_hash except AttributeError: # pragma: no cover h = self._cached_hash = hash(tuple(self)) return h def __getitem__(self, i): T = type(self) if isinstance(i, slice): # noinspection PyArgumentList return T(list.__getitem__(self, i)) return list.__getitem__(self, i) def __add__(self, other): r = super().__add__(other) T = type(self) # noinspection PyArgumentList return T(r) class CustomTuple(tuple): __tuple_types__: ClassVar[Tuple[type, ...]] def __new__(cls, *all_args): if not all_args: args = () else: (args,) = all_args if ZuperTypingGlobals.check_tuple_values: from .subcheck import value_liskov for i, (a, T) in enumerate(zip(args, cls.__tuple_types__)): can = value_liskov(a, T) if not can: msg = f"Entry #{i} does not pass the liskov test." raise ZValueError( msg, args=args, __tuple_types__=cls.__tuple_types__, i=i, a=a, T=T, can=can ) # logger.info('hello', __tuple_types__=cls.__tuple_types__, args=args) # noinspection PyTypeChecker return tuple.__new__(cls, args) def __hash__(self) -> Any: # pragma: no cover try: return self._cached_hash except AttributeError: # pragma: no cover h = self._cached_hash = hash(tuple(self)) return h def __getitem__(self, i): if isinstance(i, slice): vals = super().__getitem__(i) types = self.__tuple_types__[i] T2 = make_CustomTuple(types) # noinspection PyArgumentList return T2(vals) else: return super().__getitem__(i) def __add__(self, other): vals = super().__add__(other) if isinstance(other, CustomTuple): types2 = type(other).__tuple_types__ else: types2 = (Any,) * len(other) T2 = make_CustomTuple(self.__tuple_types__ + types2) # noinspection PyArgumentList return T2(vals) class CustomDict(dict): __dict_type__: ClassVar[Tuple[type, type]] def __hash__(self) -> Any: try: return self._cached_hash except AttributeError: pass try: it = tuple(sorted(self.items())) except TypeError: it = tuple(self.items()) try: h = self._cached_hash = hash(tuple(it)) except TypeError as e: msg = "Cannot compute hash" raise ZTypeError(msg, it=it) from e return h def copy(self: _X) -> _X: return type(self)(self) def get_CustomSet_arg(x: Type[CustomSet]) -> TypeLike: assert is_CustomSet(x), x return x.__set_type__ def get_CustomList_arg(x: Type[CustomList]) -> TypeLike: assert is_CustomList(x), x if not hasattr(x, ATT_LIST_TYPE): msg = "CustomList without __list_type__?" raise ZValueError(msg, x=type(x), x2=str(x), d=x.__dict__) return getattr(x, ATT_LIST_TYPE) def get_CustomDict_args(x: Type[CustomDict]) -> Tuple[TypeLike, TypeLike]: assert is_CustomDict(x), x return x.__dict_type__ def get_CustomTuple_args(x: Type[CustomTuple]) -> Tuple[TypeLike, ...]: assert is_CustomTuple(x), x return x.__tuple_types__ def is_CustomSet(x: TypeLike) -> bool: return isinstance(x, type) and (x is not CustomSet) and issubclass(x, CustomSet) def is_CustomList(x: TypeLike) -> bool: return isinstance(x, type) and (x is not CustomList) and issubclass(x, CustomList) def is_CustomDict(x: TypeLike) -> bool: return isinstance(x, type) and (x is not CustomDict) and issubclass(x, CustomDict) def is_CustomTuple(x: TypeLike) -> bool: return isinstance(x, type) and (x is not CustomTuple) and issubclass(x, CustomTuple) def is_SetLike(x: TypeLike) -> bool: return (x is set) or is_Set(x) or is_CustomSet(x) def is_ListLike(x: TypeLike) -> bool: return (x is list) or is_List(x) or is_CustomList(x) def is_DictLike(x: TypeLike) -> bool: return (x is dict) or is_Dict(x) or is_CustomDict(x) def is_ListLike_canonical(x: Type[List]) -> bool: return is_CustomList(x) def is_DictLike_canonical(x: Type[Dict]) -> bool: return is_CustomDict(x) def is_SetLike_canonical(x: Type[Set]) -> bool: return is_CustomSet(x) def get_SetLike_arg(x: Type[Set[_V]]) -> Type[_V]: if x is set: return Any if is_Set(x): return get_Set_arg(x) if is_CustomSet(x): x = cast(Type[CustomSet], x) return get_CustomSet_arg(x) assert False, x def get_ListLike_arg(x: Type[List[_V]]) -> Type[_V]: if x is list: return Any if is_List(x): return get_List_arg(x) if is_CustomList(x): # noinspection PyTypeChecker return get_CustomList_arg(x) assert False, x def get_DictLike_args(x: Type[Dict[_K, _V]]) -> Tuple[Type[_K], Type[_V]]: assert is_DictLike(x), x if is_Dict(x): return get_Dict_args(x) elif is_CustomDict(x): x = cast(Type[CustomDict], x) return get_CustomDict_args(x) elif x is dict: return Any, Any else: assert False, x def get_DictLike_name(T: Type[Dict]) -> str: assert is_DictLike(T) K, V = get_DictLike_args(T) return get_Dict_name_K_V(K, V) def get_ListLike_name(x: Type[List]) -> str: V = get_ListLike_arg(x) return "List[%s]" % name_for_type_like(V) def get_SetLike_name(x: Type[Set]) -> str: v = get_SetLike_arg(x) return "Set[%s]" % name_for_type_like(v) Q_ = TypeVar("Q_") K__ = TypeVar("K__") V__ = TypeVar("V__") class Caches: use_cache = True make_set_cache: Dict[Type[Q_], Type[CustomSet]] = {} make_list_cache: Dict[Type[Q_], Type[CustomList]] = {} make_dict_cache: Dict[Tuple[Type[K__], Type[V__]], Type[CustomDict]] = {} make_tuple_cache: Dict[Tuple[TypeLike, ...], Type[CustomTuple]] = {} def assert_good_typelike(x: TypeLike) -> None: if isinstance(x, type): return # if is_dataclass(type(x)): # n = type(x).__name__ # if n in ["Constant"]: # raise AssertionError(x) # def make_list(V0: Type[_X]) -> Intersection[Type[List[Type[_X]]], Callable[[List[_X]], List[_X]]]: def make_list(V0: Type[_X]) -> Type[List[Type[_X]]]: if Caches.use_cache: if V0 in Caches.make_list_cache: return Caches.make_list_cache[V0] assert_good_typelike(V0) class MyType(type): def __eq__(self, other) -> bool: V2 = getattr(self, "__list_type__") if is_List(other): return V2 == get_List_arg(other) res2 = isinstance(other, type) and issubclass(other, CustomList) and other.__list_type__ == V2 return res2 def __hash__(cls) -> Any: # pragma: no cover return 1 # XXX # logger.debug(f'here ___eq__ {self} {other} {issubclass(other, CustomList)} = {res}') def copy(self: _X) -> _X: return type(self)(self) attrs = {"__list_type__": V0, "copy": copy} # name = get_List_name(V) name = "List[%s]" % name_for_type_like(V0) res = MyType(name, (CustomList,), attrs) setattr(res, "EMPTY", res([])) Caches.make_list_cache[V0] = res add_class_to_module(res) # noinspection PyTypeChecker return res def add_class_to_module(C: type) -> None: """ Adds the class to the module's dictionary, so that Pickle can save it. """ name = C.__name__ g = globals() # from . import logger # logger.info(f'added class {name}') g[name] = C def lift_to_customtuple(vs: tuple): ts = tuple(type(_) for _ in vs) T = make_CustomTuple(ts) # noinspection PyArgumentList return T(vs) def lift_to_customtuple_type(vs: tuple, T: type): if T is Any: ts = tuple(type(_) for _ in vs) # raise ZAssertionError(vs=vs, T=T) else: ts = tuple(T for _ in vs) T = make_CustomTuple(ts) # noinspection PyArgumentList return T(vs) def make_CustomTuple(Vs: Tuple[TypeLike, ...]) -> Type[Tuple]: if Vs == (Any, Any): raise ZAssertionError(Vs=Vs) # if len(Vs) == 2: # from zuper_lang.lang import Constant, EXP, EV # if Vs[0] is Constant and Vs[1] is EV: # raise ZValueError(Vs=Vs) if Caches.use_cache: if Vs in Caches.make_tuple_cache: return Caches.make_tuple_cache[Vs] for _ in Vs: assert_good_typelike(_) class MyTupleType(type): def __eq__(self, other) -> bool: V2 = getattr(self, ATT_TUPLE_TYPES) if is_FixedTupleLike(other): return V2 == get_FixedTupleLike_args(other) res2 = ( isinstance(other, type) and issubclass(other, CustomTuple) and getattr(other, ATT_TUPLE_TYPES) == V2 ) return res2 def __hash__(cls) -> Any: # pragma: no cover return 1 # XXX # logger.debug(f'here ___eq__ {self} {other} {issubclass(other, CustomList)} = {res}') def copy(self: _X) -> _X: return type(self)(self) attrs = {ATT_TUPLE_TYPES: Vs, "copy": copy} # name = get_List_name(V) s = ",".join(name_for_type_like(_) for _ in Vs) name = "Tuple[%s]" % s res = MyTupleType(name, (CustomTuple,), attrs) # setattr(res, "EMPTY", res()) Caches.make_tuple_cache[Vs] = res add_class_to_module(res) # noinspection PyTypeChecker return res def make_set(V: TypeLike) -> Type[CustomSet]: if Caches.use_cache: if V in Caches.make_set_cache: return Caches.make_set_cache[V] assert_good_typelike(V) class MyType(type): def __eq__(self, other) -> bool: V2 = getattr(self, "__set_type__") if is_Set(other): return V2 == get_Set_arg(other) res2 = isinstance(other, type) and issubclass(other, CustomSet) and other.__set_type__ == V2 return res2 def __hash__(cls) -> Any: # pragma: no cover return 1 # XXX def copy(self: _X) -> _X: return type(self)(self) attrs = {"__set_type__": V, "copy": copy} name = get_Set_name_V(V) res = MyType(name, (CustomSet,), attrs) setattr(res, "EMPTY", res([])) Caches.make_set_cache[V] = res add_class_to_module(res) # noinspection PyTypeChecker return res # from . import logger # def make_dict(K: Type[X], V: Type[Y]) -> Type[Dict[Type[X], Type[Y]]]: def make_dict(K: TypeLike, V: TypeLike) -> type: # Type[CustomDict]: key = (K, V) if Caches.use_cache: if key in Caches.make_dict_cache: return Caches.make_dict_cache[key] assert_good_typelike(K) assert_good_typelike(V) class MyType(type): def __eq__(self, other) -> bool: K2, V2 = getattr(self, "__dict_type__") if is_Dict(other): K1, V1 = get_Dict_args(other) return K2 == K1 and V2 == V1 res2 = ( isinstance(other, type) and issubclass(other, CustomDict) and other.__dict_type__ == (K2, V2) ) return res2 def __hash__(cls) -> Any: # pragma: no cover return 1 # XXX if isinstance(V, str): # pragma: no cover msg = f"Trying to make dict with K = {K!r} and V = {V!r}; I need types, not strings." raise ValueError(msg) # warnings.warn('Creating dict', stacklevel=2) attrs = {"__dict_type__": (K, V)} name = get_Dict_name_K_V(K, V) res = MyType(name, (CustomDict,), attrs) setattr(res, "EMPTY", res({})) Caches.make_dict_cache[key] = res # noinspection PyUnresolvedReferences # import zuper_typing.my_dict # # zuper_typing.my_dict.__dict__[res.__name__] = res # noinspection PyTypeChecker add_class_to_module(res) return res def is_TupleLike(x: TypeLike) -> bool: return is_Tuple(x) or x is tuple or is_CustomTuple(x) def is_FixedTupleLike(x: TypeLike) -> bool: return is_FixedTuple(x) or is_CustomTuple(x) def get_FixedTupleLike_args(x: Type[Tuple]) -> Tuple[TypeLike, ...]: assert is_FixedTupleLike(x), x if is_FixedTuple(x): x = cast(Type[Tuple], x) return get_tuple_types(x) if is_CustomTuple(x): x = cast(Type[CustomTuple], x) return get_CustomTuple_args(x) assert False, x def get_FixedTupleLike_name(V: Type[Tuple]) -> str: return "Tuple[%s]" % ",".join(name_for_type_like(_) for _ in get_FixedTupleLike_args(V))
zuper-typing-z6
/zuper-typing-z6-6.2.3.tar.gz/zuper-typing-z6-6.2.3/src/zuper_typing/annotations_tricks.py
annotations_tricks.py
from typing import Tuple from .aliases import TypeLike from .annotations_tricks import is_TypeLike, key_for_sorting_types, name_for_type_like from .constants import INTERSECTION_ATT, PYTHON_36 __all__ = [ "get_Intersection_args", "make_Intersection", "is_Intersection", "Intersection", ] if PYTHON_36: # pragma: no cover class IntersectionMeta(type): def __getitem__(self, params): return make_Intersection(params) class Intersection(metaclass=IntersectionMeta): pass else: class Intersection: @classmethod def __class_getitem__(cls, params): # return Intersection_item(cls, params) return make_Intersection(params) class IntersectionCache: use_cache = True make_intersection_cache = {} def make_Intersection(ts: Tuple[TypeLike, ...]) -> TypeLike: if len(ts) == 0: return object done = [] for t in ts: assert is_TypeLike(t), ts if t not in done: done.append(t) done = sorted(done, key=key_for_sorting_types) ts = tuple(done) if len(ts) == 1: return ts[0] if IntersectionCache.use_cache: if ts in IntersectionCache.make_intersection_cache: return IntersectionCache.make_intersection_cache[ts] class IntersectionBase(type): def __eq__(self, other): if is_Intersection(other): t1 = get_Intersection_args(self) t2 = get_Intersection_args(other) return set(t1) == set(t2) return False def __hash__(cls): # pragma: no cover return 1 # XXX # logger.debug(f'here ___eq__ {self} {other} {issubclass(other, CustomList)} = {res}') attrs = {INTERSECTION_ATT: ts} name = "Intersection[%s]" % ",".join(name_for_type_like(_) for _ in ts) res = IntersectionBase(name, (), attrs) IntersectionCache.make_intersection_cache[ts] = res return res def is_Intersection(T: TypeLike) -> bool: return hasattr(T, INTERSECTION_ATT) and type(T).__name__.startswith("Intersection") def get_Intersection_args(T: TypeLike) -> Tuple[TypeLike, ...]: assert is_Intersection(T) return getattr(T, INTERSECTION_ATT)
zuper-typing-z6
/zuper-typing-z6-6.2.3.tar.gz/zuper-typing-z6-6.2.3/src/zuper_typing/my_intersection.py
my_intersection.py
from datetime import datetime from decimal import Decimal from numbers import Number from typing import ( Any, Awaitable, cast, ClassVar, Dict, Generic, Iterable, Iterator, List, Optional, Sequence, Set, Tuple, Type, TypeVar, Union, ) from zuper_commons.types import ZNotImplementedError, ZTypeError, ZValueError from . import logger from .aliases import TypeLike from .annotations_tricks import ( get_Awaitable_arg, get_Callable_info, get_ClassVar_arg, get_ForwardRef_arg, get_Iterable_arg, get_Iterator_arg, get_List_arg, get_NewType_arg, get_Optional_arg, get_Sequence_arg, get_Type_arg, get_TypeVar_name, get_Union_args, get_VarTuple_arg, is_Any, is_Awaitable, is_Callable, is_ClassVar, is_FixedTupleLike_canonical, is_ForwardRef, is_Iterable, is_Iterator, is_List, is_List_canonical, is_NewType, is_Optional, is_Sequence, is_Type, is_TypeVar, is_Union, is_VarTuple, is_VarTuple_canonical, make_Tuple, make_Union, make_VarTuple, ) from .get_patches_ import is_placeholder from .literal import is_Literal from .annotations_tricks import ( CustomList, get_CustomList_arg, get_DictLike_args, get_FixedTupleLike_args, get_ListLike_arg, get_SetLike_arg, is_CustomList, is_DictLike, is_DictLike_canonical, is_FixedTupleLike, is_ListLike, is_ListLike_canonical, is_SetLike, is_SetLike_canonical, make_dict, make_list, make_set, ) from .my_intersection import get_Intersection_args, is_Intersection, make_Intersection from .uninhabited import is_Uninhabited __all__ = [ "get_name_without_brackets", "replace_typevars", "canonical", "NoConstructorImplemented", "find_typevars_inside", ] def get_name_without_brackets(name: str) -> str: if "[" in name: return name[: name.index("[")] else: return name class NoConstructorImplemented(TypeError): pass X = TypeVar("X") def get_default_attrs(): from .zeneric2 import dataclass @dataclass class MyQueue(Generic[X]): pass return dict( Any=Any, Optional=Optional, Union=Union, Tuple=Tuple, List=List, Set=Set, Dict=Dict, Queue=MyQueue, ) def canonical(typelike: TypeLike) -> TypeLike: return replace_typevars(typelike, bindings={}, symbols={}, make_canonical=True) def replace_typevars( cls: TypeLike, *, bindings: Dict[Any, type], symbols: Dict[str, type], make_canonical: bool = False, ) -> TypeLike: if is_placeholder(cls): msg = "Cannot run replace_typevars() on placeholder" raise ZValueError(msg, cls=cls) r = lambda _: replace_typevars(_, bindings=bindings, symbols=symbols) if cls is type: return type if hasattr(cls, "__name__") and cls.__name__ in symbols: return symbols[cls.__name__] elif (isinstance(cls, str) or is_TypeVar(cls)) and cls in bindings: return bindings[cls] elif hasattr(cls, "__name__") and cls.__name__.startswith("Placeholder"): return cls elif is_TypeVar(cls): name = get_TypeVar_name(cls) for k, v in bindings.items(): if is_TypeVar(k) and get_TypeVar_name(k) == name: return v return cls # return bindings[cls] elif isinstance(cls, str): if cls in symbols: return symbols[cls] g = dict(get_default_attrs()) g.update(symbols) g0 = dict(g) try: return eval(cls, g) except TypeError as e: raise ZTypeError(cls=cls, g=g) from e except NameError as e: msg = f"Cannot resolve {cls!r}\ng: {list(g0)}" # msg += 'symbols: {list(g0)' raise NameError(msg) from e elif is_NewType(cls): # XXX: maybe we should propagate? return cls elif is_Type(cls): x = get_Type_arg(cls) r = r(x) if x == r: return cls return Type[r] # return type elif is_DictLike(cls): cls = cast(Type[Dict], cls) is_canonical = is_DictLike_canonical(cls) K0, V0 = get_DictLike_args(cls) K = r(K0) V = r(V0) # logger.debug(f'{K0} -> {K}; {V0} -> {V}') if (K0, V0) == (K, V) and (is_canonical or not make_canonical): return cls res = make_dict(K, V) return res elif is_SetLike(cls): cls = cast(Type[Set], cls) is_canonical = is_SetLike_canonical(cls) V0 = get_SetLike_arg(cls) V = r(V0) if V0 == V and (is_canonical or not make_canonical): return cls return make_set(V) elif is_CustomList(cls): cls = cast(Type[CustomList], cls) V0 = get_CustomList_arg(cls) V = r(V0) if V0 == V: return cls return make_list(V) elif is_List(cls): cls = cast(Type[List], cls) arg = get_List_arg(cls) is_canonical = is_List_canonical(cls) arg2 = r(arg) if arg == arg2 and (is_canonical or not make_canonical): return cls return List[arg2] elif is_ListLike(cls): cls = cast(Type[List], cls) arg = get_ListLike_arg(cls) is_canonical = is_ListLike_canonical(cls) arg2 = r(arg) if arg == arg2 and (is_canonical or not make_canonical): return cls return make_list(arg2) # XXX NOTE: must go after CustomDict elif hasattr(cls, "__annotations__"): from .zeneric2 import make_type cls2 = make_type(cls, bindings=bindings, symbols=symbols) # from zuper_typing.logging_util import ztinfo # ztinfo("replace_typevars", bindings=bindings, cls=cls, cls2=cls2) # logger.info(f'old cls: {cls.__annotations__}') # logger.info(f'new cls2: {cls2.__annotations__}') return cls2 elif is_ClassVar(cls): is_canonical = True # XXXis_ClassVar_canonical(cls) x = get_ClassVar_arg(cls) r = r(x) if x == r and (is_canonical or not make_canonical): return cls return ClassVar[r] elif is_Iterator(cls): is_canonical = True # is_Iterator_canonical(cls) # noinspection PyTypeChecker x = get_Iterator_arg(cls) r = r(x) if x == r and (is_canonical or not make_canonical): return cls return Iterator[r] elif is_Sequence(cls): is_canonical = True # is_Sequence_canonical(cls) cls = cast(Type[Sequence], cls) x = get_Sequence_arg(cls) r = r(x) if x == r and (is_canonical or not make_canonical): return cls return Sequence[r] elif is_Optional(cls): is_canonical = True # is_Optional_canonical(cls) x = get_Optional_arg(cls) x2 = r(x) if x == x2 and (is_canonical or not make_canonical): return cls return Optional[x2] elif is_Union(cls): # cls = cast(Type[Union], cls) cannot cast xs = get_Union_args(cls) is_canonical = True # is_Union_canonical(cls) ys = tuple(r(_) for _ in xs) if ys == xs and (is_canonical or not make_canonical): return cls return make_Union(*ys) elif is_Intersection(cls): xs = get_Intersection_args(cls) ys = tuple(r(_) for _ in xs) if ys == xs: return cls return make_Intersection(ys) elif is_VarTuple(cls): cls = cast(Type[Tuple], cls) is_canonical = is_VarTuple_canonical(cls) X = get_VarTuple_arg(cls) Y = r(X) if X == Y and (is_canonical or not make_canonical): return cls return make_VarTuple(Y) elif is_FixedTupleLike(cls): cls = cast(Type[Tuple], cls) is_canonical = is_FixedTupleLike_canonical(cls) xs = get_FixedTupleLike_args(cls) ys = tuple(r(_) for _ in xs) if ys == xs and (is_canonical or not make_canonical): return cls return make_Tuple(*ys) elif is_Callable(cls): cinfo = get_Callable_info(cls) cinfo2 = cinfo.replace(r) return cinfo2.as_callable() elif is_Awaitable(cls): x = get_Awaitable_arg(cls) y = r(x) if x == y: return cls return Awaitable[cls] elif is_ForwardRef(cls): T = get_ForwardRef_arg(cls) if T in symbols: return r(symbols[T]) else: logger.warning(f"could not resolve {cls}") return cls elif cls in (int, bool, float, Decimal, datetime, str, bytes, Number, type(None), object): return cls elif is_Any(cls): return cls elif is_Uninhabited(cls): return cls elif is_Literal(cls): return cls elif isinstance(cls, type): # logger.warning(f"extraneous class {cls}") return cls # elif is_Literal(cls): # return cls else: # raise ZNotImplementedError(cls=cls) # logger.debug(f"Nothing to do with {cls!r} {cls}") return cls B = Dict[Any, Any] # bug in Python 3.6 def find_typevars_inside(cls: TypeLike, already: Set[int] = None) -> Tuple[TypeLike, ...]: if already is None: already = set() if id(cls) in already: return () already.add(id(cls)) r = lambda _: find_typevars_inside(_, already) def rs(ts): res = () for x in ts: res = res + r(x) return res if cls is type: return () # # if cls is function: # raise ZException(cls=cls, t=type(cls)) if is_TypeVar(cls): return (cls,) elif isinstance(cls, str): return () # XXX raise ZNotImplementedError(cls=cls) # if cls in symbols: # return symbols[cls] # g = dict(get_default_attrs()) # g.update(symbols) # g0 = dict(g) # try: # return eval(cls, g) # except NameError as e: # msg = f"Cannot resolve {cls!r}\ng: {list(g0)}" # # msg += 'symbols: {list(g0)' # raise NameError(msg) from e elif is_NewType(cls): return r(get_NewType_arg(cls)) elif is_Type(cls): return r(get_Type_arg(cls)) elif is_DictLike(cls): cls = cast(Type[Dict], cls) K0, V0 = get_DictLike_args(cls) return r(K0) + r(V0) elif is_SetLike(cls): cls = cast(Type[Set], cls) V0 = get_SetLike_arg(cls) return r(V0) elif is_ListLike(cls): cls = cast(Type[List], cls) V0 = get_ListLike_arg(cls) return r(V0) # XXX NOTE: must go after CustomDict elif hasattr(cls, "__annotations__"): # from .logging import logger # # logger.info(cls) # logger.info(is_NewType(cls)) # logger.info(cls.__annotations__) d = dict(cls.__annotations__) return rs(d.values()) elif is_ClassVar(cls): x = get_ClassVar_arg(cls) return r(x) elif is_Iterator(cls): V0 = get_Iterator_arg(cls) return r(V0) elif is_Sequence(cls): cls = cast(Type[Sequence], cls) V0 = get_Sequence_arg(cls) return r(V0) elif is_Iterable(cls): cls = cast(Type[Iterable], cls) V0 = get_Iterable_arg(cls) return r(V0) elif is_Optional(cls): x = get_Optional_arg(cls) return r(x) elif is_Union(cls): xs = get_Union_args(cls) return rs(xs) elif is_Intersection(cls): xs = get_Intersection_args(cls) return rs(xs) elif is_VarTuple(cls): cls = cast(Type[Tuple], cls) x = get_VarTuple_arg(cls) return r(x) elif is_FixedTupleLike(cls): cls = cast(Type[Tuple], cls) xs = get_FixedTupleLike_args(cls) return rs(xs) elif is_Callable(cls): cinfo = get_Callable_info(cls) return rs(cinfo.parameters_by_position) + r(cinfo.returns) elif is_ForwardRef(cls): return () # XXX elif cls in (int, bool, float, Decimal, datetime, str, bytes, Number, type(None), object): return () elif is_Any(cls): return () elif is_Uninhabited(cls): return () elif is_Literal(cls): return () elif isinstance(cls, type): return () else: raise ZNotImplementedError(cls=cls) # logger.debug(f'Nothing to do with {cls!r} {cls}') # return cls
zuper-typing-z6
/zuper-typing-z6-6.2.3.tar.gz/zuper-typing-z6-6.2.3/src/zuper_typing/recursive_tricks.py
recursive_tricks.py
import io import json import select import time import traceback from io import BufferedReader from json import JSONDecodeError from typing import Iterator import cbor2 import yaml from . import logger from .json_utils import decode_bytes_before_json_deserialization, encode_bytes_before_json_serialization __all__ = [ 'read_cbor_or_json_objects', 'json2cbor_main', 'cbor2json_main', 'cbor2yaml_main', 'read_next_cbor', 'read_next_either_json_or_cbor', ] def json2cbor_main(): fo = open('/dev/stdout', 'wb', buffering=0) fi = open('/dev/stdin', 'rb', buffering=0) # noinspection PyTypeChecker fi = BufferedReader(fi, buffer_size=1) for j in read_cbor_or_json_objects(fi): c = cbor2.dumps(j) fo.write(c) fo.flush() def cbor2json_main(): fo = open('/dev/stdout', 'wb', buffering=0) fi = open('/dev/stdin', 'rb', buffering=0) for j in read_cbor_objects(fi): j = encode_bytes_before_json_serialization(j) ob = json.dumps(j) ob = ob.encode('utf-8') fo.write(ob) fo.write(b'\n') fo.flush() def cbor2yaml_main(): fo = open('/dev/stdout', 'wb') fi = open('/dev/stdin', 'rb') for j in read_cbor_objects(fi): ob = yaml.dump(j) ob = ob.encode('utf-8') fo.write(ob) fo.write(b'\n') fo.flush() def read_cbor_or_json_objects(f, timeout=None) -> Iterator: """ Reads cbor or line-separated json objects from the binary file f.""" while True: try: ob = read_next_either_json_or_cbor(f, timeout=timeout) yield ob except StopIteration: break except TimeoutError: raise def read_cbor_objects(f, timeout=None) -> Iterator: """ Reads cbor or line-separated json objects from the binary file f.""" while True: try: ob = read_next_cbor(f, timeout=timeout) yield ob except StopIteration: break except TimeoutError: raise def read_next_either_json_or_cbor(f, timeout=None, waiting_for: str = None) -> dict: """ Raises StopIteration if it is EOF. Raises TimeoutError if over timeout""" fs = [f] t0 = time.time() intermediate_timeout = 3.0 while True: try: readyr, readyw, readyx = select.select(fs, [], fs, intermediate_timeout) except io.UnsupportedOperation: break if readyr: break elif readyx: logger.warning('Exceptional condition on input channel %s' % readyx) else: delta = time.time() - t0 if (timeout is not None) and (delta > timeout): msg = 'Timeout after %.1f s.' % delta logger.error(msg) raise TimeoutError(msg) else: msg = 'I have been waiting %.1f s.' % delta if timeout is None: msg += ' I will wait indefinitely.' else: msg += ' Timeout will occurr at %.1f s.' % timeout if waiting_for: msg += ' ' + waiting_for logger.warning(msg) first = f.peek(1)[:1] if len(first) == 0: msg = 'Detected EOF on %s.' % f if waiting_for: msg += ' ' + waiting_for raise StopIteration(msg) # logger.debug(f'first char is {first}') if first in [b' ', b'\n', b'{']: line = f.readline() line = line.strip() if not line: msg = 'Read empty line. Re-trying.' logger.warning(msg) return read_next_either_json_or_cbor(f) # logger.debug(f'line is {line!r}') try: j = json.loads(line) except JSONDecodeError: msg = f'Could not decode line {line!r}: {traceback.format_exc()}' logger.error(msg) return read_next_either_json_or_cbor(f) j = decode_bytes_before_json_deserialization(j) return j else: j = cbor2.load(f) return j def wait_for_data(f, timeout=None, waiting_for: str = None): """ Raises StopIteration if it is EOF. Raises TimeoutError if over timeout""" # XXX: StopIteration not implemented fs = [f] t0 = time.time() intermediate_timeout = 3.0 while True: try: readyr, readyw, readyx = select.select(fs, [], fs, intermediate_timeout) except io.UnsupportedOperation: break if readyr: break elif readyx: logger.warning('Exceptional condition on input channel %s' % readyx) else: delta = time.time() - t0 if (timeout is not None) and (delta > timeout): msg = 'Timeout after %.1f s.' % delta logger.error(msg) raise TimeoutError(msg) else: msg = 'I have been waiting %.1f s.' % delta if timeout is None: msg += ' I will wait indefinitely.' else: msg += ' Timeout will occurr at %.1f s.' % timeout if waiting_for: msg += ' ' + waiting_for logger.warning(msg) def read_next_cbor(f, timeout=None, waiting_for: str = None) -> dict: """ Raises StopIteration if it is EOF. Raises TimeoutError if over timeout""" wait_for_data(f, timeout, waiting_for) try: j = cbor2.load(f) return j except OSError as e: if e.errno == 29: raise StopIteration from None raise
zuper-utils
/zuper-utils-3.0.3.tar.gz/zuper-utils-3.0.3/src/zuper_json/json2cbor.py
json2cbor.py
from typing import ClassVar, Tuple, Any from .annotations_tricks import is_Dict, get_Set_name_V class CustomDict(dict): __dict_type__: ClassVar[Tuple[type, type]] def __setitem__(self, key, val): K, V = self.__dict_type__ if not isinstance(key, K): msg = f'Invalid key; expected {K}, got {type(key)}' raise ValueError(msg) # XXX: this should be for many more cases if isinstance(V, type) and not isinstance(val, V): msg = f'Invalid value; expected {V}, got {type(val)}' raise ValueError(msg) dict.__setitem__(self, key, val) def __hash__(self): try: return self._cached_hash except AttributeError: h = self._cached_hash = hash(tuple(sorted(self.items()))) return h def make_dict(K, V) -> type: attrs = {'__dict_type__': (K, V)} from .annotations_tricks import get_Dict_name_K_V name = get_Dict_name_K_V(K, V) res = type(name, (CustomDict,), attrs) return res def is_Dict_or_CustomDict(x): from .annotations_tricks import is_Dict return is_Dict(x) or (isinstance(x, type) and issubclass(x, CustomDict)) def get_Dict_or_CustomDict_Key_Value(x): assert is_Dict_or_CustomDict(x) if is_Dict(x): return x.__args__ else: return x.__dict_type__ class CustomSet(set): __set_type__: ClassVar[type] def __hash__(self): try: return self._cached_hash except AttributeError: h = self._cached_hash = hash(tuple(sorted(self))) return h def make_set(V) -> type: attrs = {'__set_type__': V} name = get_Set_name_V(V) res = type(name, (CustomSet,), attrs) return res def is_set_or_CustomSet(x): from .annotations_tricks import is_Set return is_Set(x) or (isinstance(x, type) and issubclass(x, CustomSet)) def get_set_Set_or_CustomSet_Value(x): from .annotations_tricks import is_Set, get_Set_arg if x is set: return Any if is_Set(x): return get_Set_arg(x) if isinstance(x, type) and issubclass(x, CustomSet): return x.__set_type__ assert False, x
zuper-utils
/zuper-utils-3.0.3.tar.gz/zuper-utils-3.0.3/src/zuper_json/my_dict.py
my_dict.py
from dataclasses import is_dataclass from typing import * from zuper_commons.text import indent from .annotations_tricks import is_Any, is_union, get_union_types, is_optional, get_optional_type from .my_dict import is_Dict_or_CustomDict, get_Dict_or_CustomDict_Key_Value def can_be_used_as(T1, T2) -> Tuple[bool, str]: # cop out for the easy cases if T1 == T2: return True, '' if is_Any(T2): return True, '' if is_Dict_or_CustomDict(T2): K2, V2 = get_Dict_or_CustomDict_Key_Value(T2) if not is_Dict_or_CustomDict(T1): msg = f'Expecting a dictionary, got {T1}' return False, msg else: K1, V1 = get_Dict_or_CustomDict_Key_Value(T1) # TODO: to finish return True, '' if is_dataclass(T2): if not is_dataclass(T1): msg = f'Expecting dataclass to match to {T2}, got {T1}' return False, msg h1 = get_type_hints(T1) h2 = get_type_hints(T2) for k, v2 in h2.items(): if not k in h1: # and not optional... msg = f'Type {T2}\n requires field "{k}" \n of type {v2} \n but {T1} does not have it. ' return False, msg v1 = h1[k] ok, why = can_be_used_as(v1, v2) if not ok: msg = f'Type {T2}\n requires field "{k}"\n of type {v2} \n but {T1}\n has annotated it as {v1}\n which cannot be used. ' msg += '\n\n' + indent(why, '> ') return False, msg return True, '' if is_union(T2): for t in get_union_types(T2): ok, why = can_be_used_as(T1, t) if ok: return True, '' msg = f'Cannot use {T1} as any of {T2}' return False, msg if is_optional(T2): t = get_optional_type(T2) return can_be_used_as(T1, t) # if isinstance(T2, type): # if issubclass(T1, T2): # return True, '' # # msg = f'Type {T1}\n is not a subclass of {T2}' # return False, msg # return True, '' if isinstance(T1, type) and isinstance(T2, type): if issubclass(T1, T2): print('yes') return True, '' else: msg = f'Type {T1}\n is not a subclass of {T2}' return False, msg msg = f'{T1} ? {T2}' raise NotImplementedError(msg)
zuper-utils
/zuper-utils-3.0.3.tar.gz/zuper-utils-3.0.3/src/zuper_json/subcheck.py
subcheck.py
import dataclasses import typing from datetime import datetime from typing import TypeVar, Generic, Dict import termcolor from .constants import PYTHON_36 from .my_dict import make_dict from .zeneric2 import ZenericFix, resolve_types if PYTHON_36: # pragma: no cover from typing import GenericMeta previous_getitem = GenericMeta.__getitem__ else: from typing import _GenericAlias previous_getitem = _GenericAlias.__getitem__ class Alias1: def __getitem__(self, params): if self is typing.Dict: K, V = params if K is not str: return make_dict(K, V) # noinspection PyArgumentList return previous_getitem(self, params) if PYTHON_36: # pragma: no cover from typing import GenericMeta old_one = GenericMeta.__getitem__ class P36Generic: def __getitem__(self, params): # pprint('P36', params=params, self=self) if self is typing.Generic: return ZenericFix.__class_getitem__(params) if self is typing.Dict: K, V = params if K is not str: return make_dict(K, V) # noinspection PyArgumentList return old_one(self, params) GenericMeta.__getitem__ = P36Generic.__getitem__ else: Generic.__class_getitem__ = ZenericFix.__class_getitem__ _GenericAlias.__getitem__ = Alias1.__getitem__ Dict.__getitem__ = Alias1.__getitem__ def _cmp_fn_loose(name, op, self_tuple, other_tuple): body = ['if other.__class__.__name__ == self.__class__.__name__:', f' return {self_tuple}{op}{other_tuple}', 'return NotImplemented'] fn = dataclasses._create_fn(name, ('self', 'other'), body) fn.__doc__ = """ This is a loose comparison function. Instead of comparing: self.__class__ is other.__class__ we compare: self.__class__.__name__ == other.__class__.__name__ """ return fn dataclasses._cmp_fn = _cmp_fn_loose def typevar__repr__(self): if self.__covariant__: prefix = '+' elif self.__contravariant__: prefix = '-' else: prefix = '~' s = prefix + self.__name__ if self.__bound__: if isinstance(self.__bound__, type): b = self.__bound__.__name__ else: b = str(self.__bound__) s += f'<{b}' return s setattr(TypeVar, '__repr__', typevar__repr__) NAME_ARG = '__name_arg__' # need to have this otherwise it's not possible to say that two types are the same class Reg: already = {} def MyNamedArg(x: type, name): key = f'{x} {name}' if key in Reg.already: return Reg.already[key] meta = getattr(x, '__metaclass_', type) d = {NAME_ARG: name, 'original': x} cname = x.__name__ res = meta(cname, (x,), d) res.__module__ = 'typing' Reg.already[key] = res return res import mypy_extensions setattr(mypy_extensions, 'NamedArg', MyNamedArg) from dataclasses import dataclass as original_dataclass class RegisteredClasses: # klasses: Dict[str, type] = {} klasses = {} def remember_created_class(res): # print(f'Registered class "{res.__name__}"') k = (res.__module__, res.__name__) RegisteredClasses.klasses[k] = res def my_dataclass(_cls=None, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False): def wrap(cls): return my_dataclass_(cls, init=init, repr=repr, eq=eq, order=order, unsafe_hash=unsafe_hash, frozen=frozen) # See if we're being called as @dataclass or @dataclass(). if _cls is None: # We're called with parens. return wrap # We're called as @dataclass without parens. return wrap(_cls) def my_dataclass_(_cls, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False): unsafe_hash = True # pprint('my_dataclass', _cls=_cls) res = original_dataclass(_cls, init=init, repr=repr, eq=eq, order=order, unsafe_hash=unsafe_hash, frozen=frozen) remember_created_class(res) assert dataclasses.is_dataclass(res) refs = getattr(_cls, '__depends__', ()) resolve_types(res, refs=refs) def __repr__(self): return DataclassHooks.dc_repr(self) def __str__(self): return DataclassHooks.dc_str(self) setattr(res, '__repr__', __repr__) setattr(res, '__str__', __str__) # res.__doc__ = res.__doc__.replace(' ', '') return res def nice_str(self): return DataclassHooks.dc_repr(self) def blue(x): return termcolor.colored(x, 'blue') def nice_repr(self): s = termcolor.colored(type(self).__name__, 'red') s += blue('(') ss = [] annotations = getattr(type(self), '__annotations__', {}) for k in annotations: a = getattr(self, k) a_s = debug_print_compact(a) eq = blue('=') k = termcolor.colored(k, attrs=['dark']) ss.append(f'{k}{eq}{a_s}') s += blue(', ').join(ss) s += blue(')') return s def debug_print_compact(x): if isinstance(x, str): return debug_print_str(x, '') if isinstance(x, bytes): return debug_print_bytes(x) if isinstance(x, datetime): return debug_print_date(x, '') return f'{x!r}' def debug_print_str(x: str, prefix: str): if x.startswith('Qm'): x2 = 'Qm...' + x[-4:] + ' ' + prefix return termcolor.colored(x2, 'magenta') if x.startswith('zd'): x2 = 'zd...' + x[-4:] + ' ' + prefix return termcolor.colored(x2, 'magenta') if x.startswith('-----BEGIN'): s = 'PEM key' + ' ' + prefix return termcolor.colored(s, 'yellow') if x.startswith('Traceback'): lines = x.split('\n') colored = [termcolor.colored(_, 'red') for _ in lines] if colored: colored[0] += ' ' + prefix s = "\n".join(colored) return s return x.__repr__() + ' ' + prefix def debug_print_date(x: datetime, prefix=None): s = x.isoformat()[:19] s = s.replace('T', ' ') return termcolor.colored(s, 'yellow') + (' ' + prefix if prefix else '') def debug_print_bytes(x: bytes): s = f'{len(x)} bytes ' + x[:10].__repr__() return termcolor.colored(s, 'yellow') class DataclassHooks: dc_repr = nice_repr dc_str = nice_str setattr(dataclasses, 'dataclass', my_dataclass)
zuper-utils
/zuper-utils-3.0.3.tar.gz/zuper-utils-3.0.3/src/zuper_json/monkey_patching_typing.py
monkey_patching_typing.py
import datetime import hashlib import inspect import traceback import typing from dataclasses import make_dataclass, _FIELDS, field, Field, dataclass, is_dataclass from decimal import Decimal from numbers import Number from typing import Type, Dict, Any, TypeVar, Optional, ClassVar, cast, Union, \ Generic, List, Tuple, Callable import base58 import cbor2 import numpy as np import yaml from frozendict import frozendict from jsonschema.validators import validator_for, validate from mypy_extensions import NamedArg from nose.tools import assert_in from zuper_commons.text import indent from zuper_commons.types import check_isinstance from .annotations_tricks import is_optional, get_optional_type, is_forward_ref, get_forward_ref_arg, is_Any, \ is_ClassVar, get_ClassVar_arg, is_Type, is_Callable, get_Callable_info, get_union_types, is_union, is_Dict, \ get_Dict_name_K_V, is_Tuple, get_List_arg, is_List, is_Set, get_Set_arg, get_Set_name_V from .constants import X_PYTHON_MODULE_ATT, ATT_PYTHON_NAME, SCHEMA_BYTES, GlobalsDict, JSONSchema, _SpecialForm, \ ProcessingDict, EncounteredDict, SCHEMA_ATT, SCHEMA_ID, JSC_TYPE, JSC_STRING, JSC_NUMBER, JSC_OBJECT, JSC_TITLE, \ JSC_ADDITIONAL_PROPERTIES, JSC_DESCRIPTION, JSC_PROPERTIES, BINDINGS_ATT, JSC_INTEGER, ID_ATT, \ JSC_DEFINITIONS, REF_ATT, JSC_REQUIRED, X_CLASSVARS, X_CLASSATTS, JSC_BOOL, PYTHON_36, JSC_TITLE_NUMPY, JSC_NULL, \ JSC_TITLE_BYTES, JSC_ARRAY, JSC_ITEMS, JSC_DEFAULT, GENERIC_ATT2, JSC_TITLE_DECIMAL, JSC_TITLE_DATETIME, \ JSC_TITLE_FLOAT, JSC_TITLE_CALLABLE, JSC_TITLE_TYPE, SCHEMA_CID, JSC_PROPERTY_NAMES from .my_dict import make_dict, CustomDict, make_set, CustomSet, get_set_Set_or_CustomSet_Value from .my_intersection import is_Intersection, get_Intersection_args, Intersection from .numpy_encoding import numpy_from_dict, dict_from_numpy from .pretty import pretty_dict from .subcheck import can_be_used_as from .types import IPCE from .zeneric2 import get_name_without_brackets, replace_typevars, loglevel, RecLogger # new interface def ipce_from_object(ob, globals_: GlobalsDict = None, suggest_type=None, with_schema=True) -> IPCE: globals_ = globals_ or {} return object_to_ipce(ob, globals_, suggest_type=suggest_type, with_schema=with_schema) def object_to_ipce(ob, globals_: GlobalsDict, suggest_type=None, with_schema=True) -> IPCE: # logger.debug(f'object_to_ipce({ob})') res = object_to_ipce_(ob, globals_, suggest_type=suggest_type, with_schema=with_schema) # print(indent(json.dumps(res, indent=3), '|', ' res: -')) if isinstance(res, dict) and SCHEMA_ATT in res: schema = res[SCHEMA_ATT] # print(json.dumps(schema, indent=2)) # print(json.dumps(res, indent=2)) # currently disabled becasue JSONSchema insists on resolving all the URIs if False: validate(res, schema) # # try: # # except: # pragma: no cover # # cannot generate this if there are no bugs # fn = 'error.json' # with open(fn, 'w') as f: # f.write(json.dumps(res, indent=2)) # raise return res def object_to_ipce_(ob, globals_: GlobalsDict, with_schema: bool, suggest_type: Type = None, ) -> IPCE: trivial = (bool, int, str, float, type(None), bytes, Decimal, datetime.datetime) if isinstance(ob, datetime.datetime): if not ob.tzinfo: msg = 'Cannot serialize dates without a timezone.' raise ValueError(msg) if isinstance(ob, trivial): for T in trivial: if isinstance(ob, T): if (suggest_type is not None) and (suggest_type is not T) and (not is_Any(suggest_type)) and \ (not can_be_used_as(T, suggest_type)[0]): msg = f'Found object of type {type(ob)!r} when expected a {suggest_type!r}' raise ValueError(msg) return ob if isinstance(ob, list): if is_List(suggest_type): suggest_type_l = get_List_arg(suggest_type) else: # XXX should we warn? suggest_type_l = None # XXX return [object_to_ipce(_, globals_, suggest_type=suggest_type_l, with_schema=with_schema) for _ in ob] if isinstance(ob, tuple): suggest_type_l = None # XXX return [object_to_ipce(_, globals_, suggest_type=suggest_type_l, with_schema=with_schema) for _ in ob] if isinstance(ob, set): # if is_Set(suggest_type): # suggest_type_l = get_Set_arg(suggest_type) # else: # suggest_type_l = None # # return [object_to_ipce(_, globals_, suggest_type=suggest_type_l, # with_schema=with_schema) for _ in ob] return set_to_ipce(ob, globals_, suggest_type=suggest_type, with_schema=with_schema) if isinstance(ob, (dict, frozendict)): return dict_to_ipce(ob, globals_, suggest_type=suggest_type, with_schema=with_schema) if isinstance(ob, type): return type_to_schema(ob, globals_, processing={}) if is_Any(ob) or is_List(ob) or is_Dict(ob): # TODO: put more here return type_to_schema(ob, globals_, processing={}) if isinstance(ob, np.ndarray): res = dict_from_numpy(ob) if with_schema: res[SCHEMA_ATT] = type_numpy_to_schema(type(ob), globals_, {}) return res if is_dataclass(ob): return serialize_dataclass(ob, globals_, with_schema=with_schema) msg = f'I do not know a way to convert object of type {type(ob)}.' raise NotImplementedError(msg) import dataclasses def serialize_dataclass(ob, globals_, with_schema: bool): globals_ = dict(globals_) res = {} T = type(ob) if with_schema: res[SCHEMA_ATT] = type_to_schema(T, globals_) globals_[T.__name__] = T for f in dataclasses.fields(ob): k = f.name suggest_type = f.type if not hasattr(ob, k): # pragma: no cover assert False, (ob, k) v = getattr(ob, k) try: suggest_type = resolve_all(suggest_type, globals_) if is_ClassVar(suggest_type): continue if v is None: if is_optional(suggest_type): continue if is_optional(suggest_type): suggest_type = get_optional_type(suggest_type) res[k] = object_to_ipce(v, globals_, suggest_type=suggest_type, with_schema=with_schema) except (KeyboardInterrupt, RecursionError): raise except BaseException as e: msg = f'Cannot serialize attribute {k} of type {type(v)}.' msg += f'\nThe schema for {type(ob)} says that it should be of type {f.type}.' raise ValueError(msg) from e return res def resolve_all(T, globals_): """ Returns either a type or a generic alias :return: """ if isinstance(T, type): return T if isinstance(T, str): T = eval_just_string(T, globals_) return T if is_forward_ref(T): tn = get_forward_ref_arg(T) return resolve_all(tn, globals_) if is_optional(T): t = get_optional_type(T) t = resolve_all(t, globals_) return Optional[t] # logger.debug(f'no thing to do for {T}') return T def dict_to_ipce(ob: dict, globals_: GlobalsDict, suggest_type: Optional[type], with_schema: bool): # assert suggest_type is not None res = {} # pprint('suggest_type ', suggest_type=suggest_type) if is_Dict(suggest_type): # noinspection PyUnresolvedReferences K, V = suggest_type.__args__ elif isinstance(suggest_type, type) and issubclass(suggest_type, CustomDict): K, V = suggest_type.__dict_type__ elif (suggest_type is None) or is_Any(suggest_type): all_str = all(type(_) is str for _ in ob) if all_str: K = str else: K = Any V = Any suggest_type = Dict[K, V] else: # pragma: no cover assert False, suggest_type if with_schema: res[SCHEMA_ATT] = type_to_schema(suggest_type, globals_) if isinstance(K, type) and issubclass(K, str): for k, v in ob.items(): res[k] = object_to_ipce(v, globals_, suggest_type=V, with_schema=with_schema) else: FV = FakeValues[K, V] for k, v in ob.items(): kj = object_to_ipce(k, globals_) if isinstance(k, int): h = str(k) else: h = get_sha256_base58(cbor2.dumps(kj)).decode('ascii') fv = FV(k, v) res[h] = object_to_ipce(fv, globals_, with_schema=with_schema) return res def set_to_ipce(ob: set, globals_: GlobalsDict, suggest_type: Optional[type], with_schema: bool): if is_Set(suggest_type): V = get_Set_arg(suggest_type) else: V = None res = {} if with_schema: res[SCHEMA_ATT] = type_to_schema(suggest_type, globals_) for v in ob: vj = object_to_ipce(v, globals_, with_schema=with_schema, suggest_type=V) h = get_sha256_base58(cbor2.dumps(vj)).decode('ascii') res[h] = vj return res def get_sha256_base58(contents): import hashlib m = hashlib.sha256() m.update(contents) s = m.digest() return base58.b58encode(s) ids2cid = {} @loglevel def ipce_to_object(mj: IPCE, global_symbols, encountered: Optional[dict] = None, expect_type: Optional[type] = None) -> object: res = ipce_to_object_(mj, global_symbols, encountered, expect_type) if id(mj) in ids2cid: pass # ids2cid[id(res)] = ids2cid[id(mj)] # setattr(res, '__ipde_cid_attr__', ids2cid[id(mj)]) return res def ipce_to_object_(mj: IPCE, global_symbols, encountered: Optional[dict] = None, expect_type: Optional[type] = None) -> object: encountered = encountered or {} # logger.debug(f'ipce_to_object expect {expect_type} mj {mj}') trivial = (int, float, bool, datetime.datetime, Decimal, bytes, str) if isinstance(mj, trivial): T = type(mj) if expect_type is not None: ok, why = can_be_used_as(T, expect_type) if not ok: msg = 'Found a {T}, wanted {expect_type}' raise ValueError(msg) return mj if isinstance(mj, list): if expect_type and is_Tuple(expect_type): # noinspection PyTypeChecker return deserialize_tuple(expect_type, mj, global_symbols, encountered) elif expect_type and is_List(expect_type): suggest = get_List_arg(expect_type) seq = [ipce_to_object(_, global_symbols, encountered, expect_type=suggest) for _ in mj] return seq else: suggest = None seq = [ipce_to_object(_, global_symbols, encountered, expect_type=suggest) for _ in mj] return seq if mj is None: if expect_type is None: return None elif expect_type is type(None): return None elif is_optional(expect_type): return None else: msg = f'The value is None but the expected type is {expect_type}.' raise TypeError(msg) # XXX if expect_type is np.ndarray: return numpy_from_dict(mj) assert isinstance(mj, dict), type(mj) if mj.get(SCHEMA_ATT, '') == SCHEMA_ID: schema = cast(JSONSchema, mj) return schema_to_type(schema, global_symbols, encountered) if SCHEMA_ATT in mj: sa = mj[SCHEMA_ATT] K = schema_to_type(sa, global_symbols, encountered) # logger.debug(f' loaded K = {K} from {mj}') else: if expect_type is not None: # logger.debug('expect_type = %s' % expect_type) # check_isinstance(expect_type, type) K = expect_type else: msg = f'Cannot find a schema and expect_type=None.\n{mj}' raise ValueError(msg) # assert isinstance(K, type), K if is_optional(K): assert mj is not None # excluded before K = get_optional_type(K) return ipce_to_object(mj, global_symbols, encountered, expect_type=K) if (isinstance(K, type) and issubclass(K, dict)) or is_Dict(K) or \ (isinstance(K, type) and issubclass(K, CustomDict)): return deserialize_Dict(K, mj, global_symbols, encountered) if (isinstance(K, type) and issubclass(K, set)) or is_Set(K) or \ (isinstance(K, type) and issubclass(K, CustomSet)): return deserialize_Set(K, mj, global_symbols, encountered) if is_dataclass(K): return deserialize_dataclass(K, mj, global_symbols, encountered) if is_union(K): errors = [] for T in get_union_types(K): try: return ipce_to_object(mj, global_symbols, encountered, expect_type=T) except KeyboardInterrupt: raise except BaseException as e: errors.append(e) msg = f'Cannot deserialize with any of {get_union_types(K)}' msg += '\n'.join(str(e) for e in errors) raise Exception(msg) if is_Any(K): msg = f'Not implemented\n{mj}' raise NotImplementedError(msg) assert False, (type(K), K, mj, expect_type) # pragma: no cover def deserialize_tuple(expect_type, mj, global_symbols, encountered): seq = [] for i, ob in enumerate(mj): expect_type_i = expect_type.__args__[i] seq.append(ipce_to_object(ob, global_symbols, encountered, expect_type=expect_type_i)) return tuple(seq) def deserialize_dataclass(K, mj, global_symbols, encountered): global_symbols = dict(global_symbols) global_symbols[K.__name__] = K # logger.debug(global_symbols) # logger.debug(f'Deserializing object of type {K}') # logger.debug(f'mj: \n' + json.dumps(mj, indent=2)) # some data classes might have no annotations ("Empty") anns = getattr(K, '__annotations__', {}) if not anns: pass # logger.warning(f'No annotations for class {K}') # pprint(f'annotations: {anns}') attrs = {} for k, v in mj.items(): if k in anns: expect_type = resolve_all(anns[k], global_symbols) if is_optional(expect_type): expect_type = get_optional_type(expect_type) if inspect.isabstract(expect_type): msg = f'Trying to instantiate abstract class for field "{k}" of class {K}' msg += f'\n annotation = {anns[k]}' msg += f'\n expect_type = {expect_type}' msg += f'\n\n%s' % indent(yaml.dump(mj), ' > ') raise TypeError(msg) try: attrs[k] = ipce_to_object(v, global_symbols, encountered, expect_type=expect_type) except KeyboardInterrupt: raise except BaseException as e: msg = f'Cannot deserialize attribute {k} (expect: {expect_type})' msg += f'\nvalue: {v!r}' msg += '\n\n' + indent(traceback.format_exc(), '| ') raise TypeError(msg) from e for k, T in anns.items(): T = resolve_all(T, global_symbols) if is_ClassVar(T): continue if not k in mj: msg = f'Cannot find field {k!r} in data. Know {sorted(mj)}' if is_optional(T): attrs[k] = None pass else: raise ValueError(msg) try: return K(**attrs) except TypeError as e: # pragma: no cover msg = f'Cannot instantiate type with attrs {attrs}:\n{K}' msg += f'\n\n Bases: {K.__bases__}' anns = getattr(K, '__annotations__', 'none') msg += f"\n{anns}" df = getattr(K, '__dataclass_fields__', 'none') # noinspection PyUnresolvedReferences msg += f'\n{df}' msg += f'because:\n{e}' # XXX raise TypeError(msg) from e def deserialize_Dict(D, mj, global_symbols, encountered): if isinstance(D, type) and issubclass(D, CustomDict): K, V = D.__dict_type__ ob = D() elif is_Dict(D): K, V = D.__args__ D2 = make_dict(K, V) ob = D2() elif isinstance(D, type) and issubclass(D, dict): K, V = Any, Any ob = D() else: # pragma: no cover msg = pretty_dict("not sure", dict(D=D)) raise NotImplementedError(msg) attrs = {} FV = FakeValues[K, V] for k, v in mj.items(): if k == SCHEMA_ATT: continue if issubclass(K, str): attrs[k] = ipce_to_object(v, global_symbols, encountered, expect_type=V) else: attrs[k] = ipce_to_object(v, global_symbols, encountered, expect_type=FV) if isinstance(K, type) and issubclass(K, str): ob.update(attrs) return ob else: for k, v in attrs.items(): # noinspection PyUnresolvedReferences ob[v.real_key] = v.value return ob def deserialize_Set(D, mj, global_symbols, encountered): V = get_set_Set_or_CustomSet_Value(D) res = set() for k, v in mj.items(): if k == SCHEMA_ATT: continue vob = ipce_to_object(v, global_symbols, encountered, expect_type=V) res.add(vob) T = make_set(V) return T(res) class CannotFindSchemaReference(ValueError): pass class CannotResolveTypeVar(ValueError): pass schema_cache: Dict[Any, Union[type, _SpecialForm]] = {} def schema_hash(k): ob_cbor = cbor2.dumps(k) ob_cbor_hash = hashlib.sha256(ob_cbor).digest() return ob_cbor_hash def schema_to_type(schema0: JSONSchema, global_symbols: Dict, encountered: Dict) -> Union[type, _SpecialForm]: h = schema_hash([schema0, list(global_symbols), list(encountered)]) if h in schema_cache: # logger.info(f'cache hit for {schema0}') return schema_cache[h] res = schema_to_type_(schema0, global_symbols, encountered) if ID_ATT in schema0: schema_id = schema0[ID_ATT] encountered[schema_id] = res # print(f'Found {schema_id} -> {res}') schema_cache[h] = res return res def schema_to_type_(schema0: JSONSchema, global_symbols: Dict, encountered: Dict) -> Union[type, _SpecialForm]: # pprint('schema_to_type_', schema0=schema0) encountered = encountered or {} info = dict(global_symbols=global_symbols, encountered=encountered) check_isinstance(schema0, dict) schema = cast(JSONSchema, dict(schema0)) # noinspection PyUnusedLocal metaschema = schema.pop(SCHEMA_ATT, None) schema_id = schema.pop(ID_ATT, None) if schema_id: if not JSC_TITLE in schema: pass else: cls_name = schema[JSC_TITLE] encountered[schema_id] = cls_name if schema == {}: return Any if REF_ATT in schema: r = schema[REF_ATT] if r == SCHEMA_ID: if schema.get(JSC_TITLE, '') == 'type': return type else: return Type if r in encountered: return encountered[r] else: m = f'Cannot evaluate reference {r!r}' msg = pretty_dict(m, info) raise CannotFindSchemaReference(msg) if "anyOf" in schema: options = schema["anyOf"] args = [schema_to_type(_, global_symbols, encountered) for _ in options] return Union[tuple(args)] if "allOf" in schema: options = schema["allOf"] args = [schema_to_type(_, global_symbols, encountered) for _ in options] res = Intersection[tuple(args)] return res jsc_type = schema.get(JSC_TYPE, None) jsc_title = schema.get(JSC_TITLE, '-not-provided-') if jsc_title == JSC_TITLE_NUMPY: return np.ndarray if jsc_type == JSC_STRING: if jsc_title == JSC_TITLE_BYTES: return bytes elif jsc_title == JSC_TITLE_DATETIME: return datetime.datetime elif jsc_title == JSC_TITLE_DECIMAL: return Decimal else: return str elif jsc_type == JSC_NULL: return type(None) elif jsc_type == JSC_BOOL: return bool elif jsc_type == JSC_NUMBER: if jsc_title == JSC_TITLE_FLOAT: return float else: return Number elif jsc_type == JSC_INTEGER: return int elif jsc_type == JSC_OBJECT: if jsc_title == JSC_TITLE_CALLABLE: return schema_to_type_callable(schema, global_symbols, encountered) elif jsc_title.startswith('Dict'): return schema_dict_to_DictType(schema, global_symbols, encountered) elif jsc_title.startswith('Set'): return schema_dict_to_SetType(schema, global_symbols, encountered) elif JSC_DEFINITIONS in schema: return schema_to_type_generic(schema, global_symbols, encountered) elif ATT_PYTHON_NAME in schema: tn = schema[ATT_PYTHON_NAME] if tn in global_symbols: return global_symbols[tn] else: # logger.debug(f'did not find {tn} in {global_symbols}') return schema_to_type_dataclass(schema, global_symbols, encountered, schema_id=schema_id) assert False, schema # pragma: no cover elif jsc_type == JSC_ARRAY: return schema_array_to_type(schema, global_symbols, encountered) assert False, schema # pragma: no cover def schema_array_to_type(schema, global_symbols, encountered): items = schema['items'] if isinstance(items, list): assert len(items) > 0 args = tuple([schema_to_type(_, global_symbols, encountered) for _ in items]) if PYTHON_36: # pragma: no cover return typing.Tuple[args] else: # noinspection PyArgumentList return Tuple.__getitem__(args) else: if 'Tuple' in schema[JSC_TITLE]: args = schema_to_type(items, global_symbols, encountered) if PYTHON_36: # pragma: no cover return typing.Tuple[args, ...] else: # noinspection PyArgumentList return Tuple.__getitem__((args, Ellipsis)) else: args = schema_to_type(items, global_symbols, encountered) if PYTHON_36: # pragma: no cover return List[args] else: # noinspection PyArgumentList return List[args] def schema_dict_to_DictType(schema, global_symbols, encountered): K = str V = schema_to_type(schema[JSC_ADDITIONAL_PROPERTIES], global_symbols, encountered) # pprint(f'here:', d=dict(V.__dict__)) # if issubclass(V, FakeValues): if isinstance(V, type) and V.__name__.startswith('FakeValues'): K = V.__annotations__['real_key'] V = V.__annotations__['value'] D = make_dict(K, V) # we never put it anyway # if JSC_DESCRIPTION in schema: # setattr(D, '__doc__', schema[JSC_DESCRIPTION]) return D def schema_dict_to_SetType(schema, global_symbols, encountered): V = schema_to_type(schema[JSC_ADDITIONAL_PROPERTIES], global_symbols, encountered) return make_set(V) def type_to_schema(T: Any, globals0: dict, processing: ProcessingDict = None) -> JSONSchema: # pprint('type_to_schema', T=T) globals_ = dict(globals0) processing = processing or {} try: if hasattr(T, '__name__') and T.__name__ in processing: return processing[T.__name__] # res = cast(JSONSchema, {REF_ATT: refname}) # return res if T is type: res = cast(JSONSchema, {REF_ATT: SCHEMA_ID, JSC_TITLE: JSC_TITLE_TYPE # JSC_DESCRIPTION: T.__doc__ }) return res if T is type(None): res = cast(JSONSchema, {SCHEMA_ATT: SCHEMA_ID, JSC_TYPE: JSC_NULL}) return res if isinstance(T, type): for klass in T.mro(): if klass.__name__.startswith('Generic'): continue if klass is object: continue # globals_[klass.__name__] = klass globals_[get_name_without_brackets(klass.__name__)] = klass bindings = getattr(klass, BINDINGS_ATT, {}) for k, v in bindings.items(): if hasattr(v, '__name__') and v.__name__ not in globals_: globals_[v.__name__] = v globals_[k.__name__] = v schema = type_to_schema_(T, globals_, processing) check_isinstance(schema, dict) except NotImplementedError: # pragma: no cover raise except (ValueError, AssertionError) as e: m = f'Cannot get schema for {T}' if hasattr(T, '__name__'): m += f' (name = {T.__name__!r})' msg = pretty_dict(m, dict( # globals0=globals0, # globals=globals_, processing=processing)) # msg += '\n' + traceback.format_exc() raise type(e)(msg) from e except KeyboardInterrupt: raise except BaseException as e: m = f'Cannot get schema for {T}' if hasattr(T, '__name__'): m += f' (name = {T.__name__!r})' m += f' {T.__name__ in processing}' msg = pretty_dict(m, dict( # globals0=globals0, # globals=globals_, processing=processing)) raise TypeError(msg) from e assert_in(SCHEMA_ATT, schema) assert schema[SCHEMA_ATT] in [SCHEMA_ID] # assert_equal(schema[SCHEMA_ATT], SCHEMA_ID) if schema[SCHEMA_ATT] == SCHEMA_ID: # print(yaml.dump(schema)) if False: cls = validator_for(schema) cls.check_schema(schema) return schema K = TypeVar('K') V = TypeVar('V') @dataclass class FakeValues(Generic[K, V]): real_key: K value: V def dict_to_schema(T, globals_, processing) -> JSONSchema: assert is_Dict(T) or (isinstance(T, type) and issubclass(T, CustomDict)) if is_Dict(T): K, V = T.__args__ elif issubclass(T, CustomDict): K, V = T.__dict_type__ else: # pragma: no cover assert False res = cast(JSONSchema, {JSC_TYPE: JSC_OBJECT}) res[JSC_TITLE] = get_Dict_name_K_V(K, V) if isinstance(K, type) and issubclass(K, str): res[JSC_PROPERTIES] = {"$schema": {}} # XXX res[JSC_ADDITIONAL_PROPERTIES] = type_to_schema(V, globals_, processing) res[SCHEMA_ATT] = SCHEMA_ID return res else: res[JSC_PROPERTIES] = {"$schema": {}} # XXX props = FakeValues[K, V] res[JSC_ADDITIONAL_PROPERTIES] = type_to_schema(props, globals_, processing) res[SCHEMA_ATT] = SCHEMA_ID return res def set_to_schema(T, globals_, processing) -> JSONSchema: assert is_Set(T) or (isinstance(T, type) and issubclass(T, set)) V = get_set_Set_or_CustomSet_Value(T) res = cast(JSONSchema, {JSC_TYPE: JSC_OBJECT}) res[JSC_TITLE] = get_Set_name_V(V) res[JSC_PROPERTY_NAMES] = SCHEMA_CID res[JSC_ADDITIONAL_PROPERTIES] = type_to_schema(V, globals_, processing) res[SCHEMA_ATT] = SCHEMA_ID return res def Tuple_to_schema(T, globals_: GlobalsDict, processing: ProcessingDict) -> JSONSchema: assert is_Tuple(T) args = T.__args__ if args[-1] == Ellipsis: items = args[0] res = cast(JSONSchema, {}) res[SCHEMA_ATT] = SCHEMA_ID res[JSC_TYPE] = JSC_ARRAY res[JSC_ITEMS] = type_to_schema(items, globals_, processing) res[JSC_TITLE] = 'Tuple' return res else: res = cast(JSONSchema, {}) res[SCHEMA_ATT] = SCHEMA_ID res[JSC_TYPE] = JSC_ARRAY res[JSC_ITEMS] = [] res[JSC_TITLE] = 'Tuple' for a in args: res[JSC_ITEMS].append(type_to_schema(a, globals_, processing)) return res def List_to_schema(T, globals_: GlobalsDict, processing: ProcessingDict) -> JSONSchema: assert is_List(T) items = get_List_arg(T) res = cast(JSONSchema, {}) res[SCHEMA_ATT] = SCHEMA_ID res[JSC_TYPE] = JSC_ARRAY res[JSC_ITEMS] = type_to_schema(items, globals_, processing) res[JSC_TITLE] = 'List' return res def type_callable_to_schema(T: Type, globals_: GlobalsDict, processing: ProcessingDict) -> JSONSchema: assert is_Callable(T) cinfo = get_Callable_info(T) # res: JSONSchema = {JSC_TYPE: X_TYPE_FUNCTION, SCHEMA_ATT: X_SCHEMA_ID} res = cast(JSONSchema, {JSC_TYPE: JSC_OBJECT, SCHEMA_ATT: SCHEMA_ID, JSC_TITLE: JSC_TITLE_CALLABLE, 'special': 'callable'}) p = res[JSC_DEFINITIONS] = {} for k, v in cinfo.parameters_by_name.items(): p[k] = type_to_schema(v, globals_, processing) p['return'] = type_to_schema(cinfo.returns, globals_, processing) res['ordering'] = cinfo.ordering # print(res) return res def schema_to_type_callable(schema: JSONSchema, global_symbols: GlobalsDict, encountered: ProcessingDict): schema = dict(schema) definitions = dict(schema[JSC_DEFINITIONS]) ret = schema_to_type(definitions.pop('return'), global_symbols, encountered) others = [] for k in schema['ordering']: d = schema_to_type(definitions[k], global_symbols, encountered) if not k.startswith('#'): d = NamedArg(d, k) others.append(d) # noinspection PyTypeHints return Callable[others, ret] def type_to_schema_(T: Type, globals_: GlobalsDict, processing: ProcessingDict) -> JSONSchema: if T is None: raise ValueError() if is_optional(T): # pragma: no cover msg = f'Should not be needed to have an Optional here yet: {T}' raise AssertionError(msg) if is_forward_ref(T): # pragma: no cover arg = get_forward_ref_arg(T) # if arg == MemoryJSON.__name__: # return type_to_schema_(MemoryJSON, globals_, processing) msg = f'It is not supported to have an ForwardRef here yet: {T}' raise ValueError(msg) if isinstance(T, str): # pragma: no cover msg = f'It is not supported to have a string here: {T!r}' raise ValueError(msg) # pprint('type_to_schema_', T=T) if T is str: res = cast(JSONSchema, {JSC_TYPE: JSC_STRING, SCHEMA_ATT: SCHEMA_ID}) return res if T is bool: res = cast(JSONSchema, {JSC_TYPE: JSC_BOOL, SCHEMA_ATT: SCHEMA_ID}) return res if T is Number: res = cast(JSONSchema, {JSC_TYPE: JSC_NUMBER, SCHEMA_ATT: SCHEMA_ID}) return res if T is float: res = cast(JSONSchema, {JSC_TYPE: JSC_NUMBER, SCHEMA_ATT: SCHEMA_ID, JSC_TITLE: JSC_TITLE_FLOAT}) return res if T is int: res = cast(JSONSchema, {JSC_TYPE: JSC_INTEGER, SCHEMA_ATT: SCHEMA_ID}) return res if T is Decimal: res = cast(JSONSchema, {JSC_TYPE: JSC_STRING, JSC_TITLE: JSC_TITLE_DECIMAL, SCHEMA_ATT: SCHEMA_ID}) return res if T is datetime.datetime: res = cast(JSONSchema, {JSC_TYPE: JSC_STRING, JSC_TITLE: JSC_TITLE_DATETIME, SCHEMA_ATT: SCHEMA_ID}) return res if T is bytes: return SCHEMA_BYTES # we cannot use isinstance on typing.Any if is_Any(T): # XXX not possible... res = cast(JSONSchema, {SCHEMA_ATT: SCHEMA_ID}) return res if is_union(T): return schema_Union(T, globals_, processing) if is_Dict(T) or (isinstance(T, type) and issubclass(T, CustomDict)): return dict_to_schema(T, globals_, processing) if is_Set(T) or (isinstance(T, type) and issubclass(T, set)): return set_to_schema(T, globals_, processing) if is_Intersection(T): return schema_Intersection(T, globals_, processing) if is_Callable(T): return type_callable_to_schema(T, globals_, processing) if is_List(T): return List_to_schema(T, globals_, processing) if is_Tuple(T): # noinspection PyTypeChecker return Tuple_to_schema(T, globals_, processing) assert isinstance(T, type), T if issubclass(T, dict): # pragma: no cover msg = f'A regular "dict" slipped through.\n{T}' raise TypeError(msg) if hasattr(T, GENERIC_ATT2) and is_generic(T): return type_generic_to_schema(T, globals_, processing) if is_dataclass(T): return type_dataclass_to_schema(T, globals_, processing) if T is np.ndarray: return type_numpy_to_schema(T, globals_, processing) msg = f'Cannot interpret this type: {T!r}' msg += f'\n globals_: {globals_}' msg += f'\n globals_: {processing}' raise ValueError(msg) def is_generic(T): a = getattr(T, GENERIC_ATT2) return any(isinstance(_, TypeVar) for _ in a) def type_numpy_to_schema(T, globals_, processing) -> JSONSchema: res = cast(JSONSchema, {SCHEMA_ATT: SCHEMA_ID}) res[JSC_TYPE] = JSC_OBJECT res[JSC_TITLE] = JSC_TITLE_NUMPY res[JSC_PROPERTIES] = { 'shape': {}, # TODO 'dtype': {}, # TODO 'data': SCHEMA_BYTES } return res def schema_Intersection(T, globals_, processing): args = get_Intersection_args(T) options = [type_to_schema(t, globals_, processing) for t in args] res = cast(JSONSchema, {SCHEMA_ATT: SCHEMA_ID, "allOf": options}) return res @loglevel def schema_to_type_generic(res: JSONSchema, global_symbols: dict, encountered: dict, rl: RecLogger = None) -> Type: rl = rl or RecLogger() # rl.pp('schema_to_type_generic', schema=res, global_symbols=global_symbols, encountered=encountered) assert res[JSC_TYPE] == JSC_OBJECT assert JSC_DEFINITIONS in res cls_name = res[JSC_TITLE] encountered = dict(encountered) required = res.get(JSC_REQUIRED, []) typevars: List[TypeVar] = [] for tname, t in res[JSC_DEFINITIONS].items(): bound = schema_to_type(t, global_symbols, encountered) # noinspection PyTypeHints if is_Any(bound): bound = None # noinspection PyTypeHints tv = TypeVar(tname, bound=bound) typevars.append(tv) if ID_ATT in t: encountered[t[ID_ATT]] = tv typevars: Tuple[TypeVar, ...] = tuple(typevars) if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences base = Generic.__getitem__(typevars) else: # noinspection PyUnresolvedReferences base = Generic.__class_getitem__(typevars) fields_required = [] # (name, type, Field) fields_not_required = [] for pname, v in res.get(JSC_PROPERTIES, {}).items(): ptype = schema_to_type(v, global_symbols, encountered) if pname in required: _Field = field() fields_required.append((pname, ptype, _Field)) else: _Field = field(default=None) ptype = Optional[ptype] fields_not_required.append((pname, ptype, _Field)) fields = fields_required + fields_not_required T = make_dataclass(cls_name, fields, bases=(base,), namespace=None, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False) fix_annotations_with_self_reference(T, cls_name) if JSC_DESCRIPTION in res: setattr(T, '__doc__', res[JSC_DESCRIPTION]) if ATT_PYTHON_NAME in res: setattr(T, '__qualname__', res[ATT_PYTHON_NAME]) if X_PYTHON_MODULE_ATT in res: setattr(T, '__module__', res[X_PYTHON_MODULE_ATT]) return T def type_generic_to_schema(T: Type, globals_: GlobalsDict, processing_: ProcessingDict) -> JSONSchema: assert hasattr(T, GENERIC_ATT2) types2 = getattr(T, GENERIC_ATT2) processing2 = dict(processing_) globals2 = dict(globals_) res = cast(JSONSchema, {}) res[SCHEMA_ATT] = SCHEMA_ID res[JSC_TITLE] = T.__name__ res[ATT_PYTHON_NAME] = T.__qualname__ res[X_PYTHON_MODULE_ATT] = T.__module__ res[ID_ATT] = make_url(T.__name__) res[JSC_TYPE] = JSC_OBJECT processing2[f'{T.__name__}'] = make_ref(res[ID_ATT]) # print(f'T: {T.__name__} ') definitions = {} if hasattr(T, '__doc__') and T.__doc__: res[JSC_DESCRIPTION] = T.__doc__ globals_ = dict(globals_) for t2 in types2: if not isinstance(t2, TypeVar): continue url = make_url(f'{T.__name__}/{t2.__name__}') # processing2[f'~{name}'] = {'$ref': url} processing2[f'{t2.__name__}'] = make_ref(url) # noinspection PyTypeHints globals2[t2.__name__] = t2 bound = t2.__bound__ or Any schema = type_to_schema(bound, globals2, processing2) schema[ID_ATT] = url definitions[t2.__name__] = schema globals_[t2.__name__] = t2 if definitions: res[JSC_DEFINITIONS] = definitions res[JSC_PROPERTIES] = properties = {} required = [] for name, t in T.__annotations__.items(): t = replace_typevars(t, bindings={}, symbols=globals_, rl=None) if is_ClassVar(t): continue try: result = eval_field(t, globals2, processing2) except KeyboardInterrupt: raise except BaseException as e: msg = f'Cannot evaluate field "{name}" of class {T} annotated as {t}' raise Exception(msg) from e assert isinstance(result, Result), result properties[name] = result.schema if not result.optional: required.append(name) if required: res[JSC_REQUIRED] = required return res def type_dataclass_to_schema(T: Type, globals_: GlobalsDict, processing: ProcessingDict) -> JSONSchema: assert is_dataclass(T), T p2 = dict(processing) res = cast(JSONSchema, {}) res[ID_ATT] = make_url(T.__name__) if hasattr(T, '__name__') and T.__name__: res[JSC_TITLE] = T.__name__ p2[T.__name__] = make_ref(res[ID_ATT]) res[ATT_PYTHON_NAME] = T.__qualname__ res[X_PYTHON_MODULE_ATT] = T.__module__ res[SCHEMA_ATT] = SCHEMA_ID res[JSC_TYPE] = JSC_OBJECT if hasattr(T, '__doc__') and T.__doc__: res[JSC_DESCRIPTION] = T.__doc__ res[JSC_PROPERTIES] = properties = {} classvars = {} classatts = {} required = [] fields_ = getattr(T, _FIELDS) # noinspection PyUnusedLocal afield: Field for name, afield in fields_.items(): t = afield.type try: if isinstance(t, str): t = eval_just_string(t, globals_) if is_ClassVar(t): tt = get_ClassVar_arg(t) result = eval_field(tt, globals_, p2) classvars[name] = result.schema the_att = getattr(T, name) if isinstance(the_att, type): classatts[name] = type_to_schema(the_att, globals_, processing) else: classatts[name] = object_to_ipce(the_att, globals_) else: result = eval_field(t, globals_, p2) if not result.optional: required.append(name) properties[name] = result.schema if not result.optional: if not isinstance(afield.default, dataclasses._MISSING_TYPE): # logger.info(f'default for {name} is {afield.default}') properties[name]['default'] = object_to_ipce(afield.default, globals_) except KeyboardInterrupt: raise except BaseException as e: msg = f'Cannot write schema for attribute {name} -> {t}' raise TypeError(msg) from e if required: # empty is error res[JSC_REQUIRED] = required if classvars: res[X_CLASSVARS] = classvars if classatts: res[X_CLASSATTS] = classatts return res if typing.TYPE_CHECKING: # pragma: no cover from .monkey_patching_typing import original_dataclass else: from dataclasses import dataclass as original_dataclass @original_dataclass class Result: schema: JSONSchema optional: Optional[bool] = False # TODO: make url generic def make_url(x: str): assert isinstance(x, str), x return f'http://invalid.json-schema.org/{x}#' def make_ref(x: str) -> JSONSchema: assert len(x) > 1, x assert isinstance(x, str), x return cast(JSONSchema, {REF_ATT: x}) def eval_field(t, globals_: GlobalsDict, processing: ProcessingDict) -> Result: debug_info2 = lambda: dict(globals_=globals_, processing=processing) if isinstance(t, str): te = eval_type_string(t, globals_, processing) return te if is_Type(t): res = cast(JSONSchema, make_ref(SCHEMA_ID)) return Result(res) if is_Tuple(t): res = Tuple_to_schema(t, globals_, processing) return Result(res) if is_List(t): res = List_to_schema(t, globals_, processing) return Result(res) if is_forward_ref(t): tn = get_forward_ref_arg(t) # tt = t._eval_type(globals_, processing) # print(f'tn: {tn!r} tt: {tt!r}') return eval_type_string(tn, globals_, processing) if is_optional(t): tt = get_optional_type(t) result = eval_field(tt, globals_, processing) return Result(result.schema, optional=True) if is_union(t): return Result(schema_Union(t, globals_, processing)) if is_Any(t): res = cast(JSONSchema, {}) return Result(res) if is_Dict(t): schema = dict_to_schema(t, globals_, processing) return Result(schema) if is_Set(t): schema = set_to_schema(t, globals_, processing) return Result(schema) if isinstance(t, TypeVar): l = t.__name__ if l in processing: return Result(processing[l]) # I am not sure why this is different in Python 3.6 if PYTHON_36 and (l in globals_): # pragma: no cover T = globals_[l] return Result(type_to_schema(T, globals_, processing)) m = f'Could not resolve the TypeVar {t}' msg = pretty_dict(m, debug_info2()) raise CannotResolveTypeVar(msg) if isinstance(t, type): # catch recursion here if t.__name__ in processing: return eval_field(t.__name__, globals_, processing) else: schema = type_to_schema(t, globals_, processing) return Result(schema) msg = f'Could not deal with {t}' msg += f'\nglobals: {globals_}' msg += f'\nprocessing: {processing}' raise NotImplementedError(msg) def schema_Union(t, globals_, processing): types = get_union_types(t) options = [type_to_schema(t, globals_, processing) for t in types] res = cast(JSONSchema, {SCHEMA_ATT: SCHEMA_ID, "anyOf": options}) return res def eval_type_string(t: str, globals_: GlobalsDict, processing: ProcessingDict) -> Result: check_isinstance(t, str) globals2 = dict(globals_) debug_info = lambda: dict(t=t, globals2=pretty_dict("", globals2), processing=pretty_dict("", processing)) if t in processing: schema: JSONSchema = make_ref(make_url(t)) return Result(schema) elif t in globals2: return eval_field(globals2[t], globals2, processing) else: try: res = eval_just_string(t, globals2) return eval_field(res, globals2, processing) except NotImplementedError as e: # pragma: no cover m = 'While evaluating string' msg = pretty_dict(m, debug_info()) raise NotImplementedError(msg) from e except KeyboardInterrupt: raise except BaseException as e: # pragma: no cover m = 'Could not evaluate type string' msg = pretty_dict(m, debug_info()) raise ValueError(msg) from e def eval_just_string(t: str, globals_): from typing import Optional eval_locals = {'Optional': Optional, 'List': List} # TODO: put more above? # do not pollute environment if t in globals_: return globals_[t] eval_globals = dict(globals_) try: res = eval(t, eval_globals, eval_locals) return res except (KeyboardInterrupt, RecursionError): raise except BaseException as e: m = f'Error while evaluating the string {t!r} using eval().' msg = pretty_dict(m, dict(eval_locals=eval_locals, eval_globals=eval_globals)) raise type(e)(msg) from e @loglevel def schema_to_type_dataclass(res: JSONSchema, global_symbols: dict, encountered: EncounteredDict, schema_id=None, rl: RecLogger = None) -> Type: rl = rl or RecLogger() # rl.pp('schema_to_type_dataclass', res=res, global_symbols=global_symbols, encountered=encountered) assert res[JSC_TYPE] == JSC_OBJECT cls_name = res[JSC_TITLE] # It's already done by the calling function # if ID_ATT in res: # # encountered[res[ID_ATT]] = ForwardRef(cls_name) # encountered[res[ID_ATT]] = cls_name required = res.get(JSC_REQUIRED, []) fields = [] # (name, type, Field) for pname, v in res.get(JSC_PROPERTIES, {}).items(): ptype = schema_to_type(v, global_symbols, encountered) # assert isinstance(ptype) if pname in required: _Field = field() else: _Field = field(default=None) ptype = Optional[ptype] if JSC_DEFAULT in v: default_value = ipce_to_object(v[JSC_DEFAULT], global_symbols, expect_type=ptype) _Field.default = default_value fields.append((pname, ptype, _Field)) # pprint('making dataclass with fields', fields=fields, res=res) for pname, v in res.get(X_CLASSVARS, {}).items(): ptype = schema_to_type(v, global_symbols, encountered) fields.append((pname, ClassVar[ptype], field())) unsafe_hash = True try: T = make_dataclass(cls_name, fields, bases=(), namespace=None, init=True, repr=True, eq=True, order=False, unsafe_hash=unsafe_hash, frozen=False) except TypeError: # pragma: no cover from . import logger msg = 'Cannot make dataclass with fields:' for f in fields: msg += f'\n {f}' logger.error(msg) raise fix_annotations_with_self_reference(T, cls_name) for pname, v in res.get(X_CLASSATTS, {}).items(): if isinstance(v, dict) and SCHEMA_ATT in v and v[SCHEMA_ATT] == SCHEMA_ID: interpreted = schema_to_type(cast(JSONSchema, v), global_symbols, encountered) else: interpreted = ipce_to_object(v, global_symbols) setattr(T, pname, interpreted) if JSC_DESCRIPTION in res: setattr(T, '__doc__', res[JSC_DESCRIPTION]) else: # the original one did not have it setattr(T, '__doc__', None) if ATT_PYTHON_NAME in res: setattr(T, '__qualname__', res[ATT_PYTHON_NAME]) if X_PYTHON_MODULE_ATT in res: setattr(T, '__module__', res[X_PYTHON_MODULE_ATT]) return T from . import logger def fix_annotations_with_self_reference(T, cls_name): for k, v in T.__annotations__.items(): if is_optional(v): a = get_optional_type(v) if is_forward_ref(a): arg = get_forward_ref_arg(a) if arg == cls_name: T.__annotations__[k] = Optional[T] else: logger.warning(f'Cannot fix annotation {a}') continue # raise Exception(a) for f in dataclasses.fields(T): f.type = T.__annotations__[f.name]
zuper-utils
/zuper-utils-3.0.3.tar.gz/zuper-utils-3.0.3/src/zuper_json/ipce.py
ipce.py
import sys import traceback import typing import warnings from abc import ABCMeta, abstractmethod from dataclasses import dataclass, fields # noinspection PyUnresolvedReferences from typing import Dict, Type, TypeVar, Any, ClassVar, Sequence, _eval_type, Tuple from zuper_commons.text import indent, pretty_dict from .constants import PYTHON_36, GENERIC_ATT2, BINDINGS_ATT from .logging import logger try: from typing import ForwardRef except ImportError: # pragma: no cover from typing import _ForwardRef as ForwardRef from .annotations_tricks import is_ClassVar, get_ClassVar_arg, is_Type, get_Type_arg, name_for_type_like, \ is_forward_ref, get_forward_ref_arg, is_optional, get_optional_type, is_List, get_List_arg, is_union, \ get_union_types def loglevel(f): def f2(*args, **kwargs): RecLogger.levels += 1 # if RecLogger.levels >= 10: # raise AssertionError() try: return f(*args, **kwargs) finally: RecLogger.levels -= 1 return f2 class RecLogger: levels = 0 prefix: Tuple[str, ...] count = 0 def __init__(self, prefix=None): if prefix is None: prefix = (str(RecLogger.count),) RecLogger.count += 1 self.prefix = prefix def p(self, s): p = ' ' * RecLogger.levels + ':' # p = '/'.join(('root',) + self.prefix) + ':' print(indent(s, p)) def pp(self, msg, **kwargs): self.p(pretty_dict(msg, kwargs)) def child(self, name=None): name = name or '-' prefix = self.prefix + (name,) return RecLogger(prefix) def get_name_without_brackets(name: str) -> str: if '[' in name: return name[:name.index('[')] else: return name def as_tuple(x) -> Tuple: return x if isinstance(x, tuple) else (x,) def get_type_spec(types) -> Dict[str, Type]: res = {} for x in types: if not isinstance(x, TypeVar): # pragma: no cover msg = f'Not sure what happened - but did you import zuper_json? {(x, types)}' raise ValueError(msg) res[x.__name__] = x.__bound__ or Any return res class ZenericFix: class CannotInstantiate(TypeError): ... @classmethod def __class_getitem__(cls, params): # pprint('ZenericFix.__class_getitem__', cls=cls, params=params) types = as_tuple(params) if PYTHON_36: # pragma: no cover class FakeGenericMeta(MyABC): def __getitem__(self, params2): # pprint('FakeGenericMeta.__getitem__', cls=cls, self=self, params2=params2) types2 = as_tuple(params2) if types == types2: return self bindings = {} for T, U in zip(types, types2): bindings[T] = U if T.__bound__ is not None and isinstance(T.__bound__, type): if not issubclass(U, T.__bound__): msg = (f'For type parameter "{T.__name__}", expected a' f'subclass of "{T.__bound__.__name__}", found {U}.') raise TypeError(msg) return make_type(self, bindings) else: FakeGenericMeta = MyABC class GenericProxy(metaclass=FakeGenericMeta): @abstractmethod def need(self): """""" @classmethod def __class_getitem__(cls, params2): types2 = as_tuple(params2) bindings = {} if types == types2: return cls for T, U in zip(types, types2): bindings[T] = U if T.__bound__ is not None and isinstance(T.__bound__, type): if not issubclass(U, T.__bound__): msg = (f'For type parameter "{T.__name__}", expected a' f'subclass of "{T.__bound__.__name__}", found {U}.') raise TypeError(msg) return make_type(cls, bindings) name = 'Generic[%s]' % ",".join(_.__name__ for _ in types) gp = type(name, (GenericProxy,), {GENERIC_ATT2: types}) setattr(gp, GENERIC_ATT2, types) return gp class MyABC(ABCMeta): def __new__(mcls, name, bases, namespace, **kwargs): # logger.info('name: %s' % name) # logger.info('namespace: %s' % namespace) # logger.info('bases: %s' % str(bases)) # if bases: # logger.info('bases[0]: %s' % str(bases[0].__dict__)) cls = super().__new__(mcls, name, bases, namespace, **kwargs) # logger.info(name) # logger.info(bases) # logger.info(kwargs) # logger.info(mcls.__dict__) if GENERIC_ATT2 in namespace: spec = namespace[GENERIC_ATT2] # elif 'types_' in namespace: # spec = namespace['types_'] elif bases and GENERIC_ATT2 in bases[0].__dict__: spec = bases[0].__dict__[GENERIC_ATT2] else: spec = {} if spec: name0 = get_name_without_brackets(name) name = f'{name0}[%s]' % (",".join(name_for_type_like(_) for _ in spec)) setattr(cls, '__name__', name) else: pass setattr(cls, '__module__', mcls.__module__) # logger.info('spec: %s' % spec) return cls class NoConstructorImplemented(TypeError): pass from typing import Optional, Union, List, Set def get_default_attrs(): return dict(Any=Any, Optional=Optional, Union=Union, Tuple=Tuple, List=List, Set=Set, Dict=Dict) class Fake: def __init__(self, myt, symbols): self.myt = myt self.name_without = get_name_without_brackets(myt.__name__) self.symbols = symbols def __getitem__(self, item): n = name_for_type_like(item) complete = f'{self.name_without}[{n}]' if complete in self.symbols: return self.symbols[complete] # noinspection PyUnresolvedReferences return self.myt[item] @loglevel def resolve_types(T, locals_=None, refs=()): assert is_dataclass(T) rl = RecLogger() # rl.p(f'resolving types for {T!r}') # g = dict(globals()) # g = {} # locals_ = {} # # if hasattr(T, GENERIC_ATT): # for k, v in getattr(T, GENERIC_ATT).items(): # g[k] = TypeVar(k) # if hasattr(T, '__name__'): # g[get_name_without_brackets(T.__name__)] = T # # g['Optional'] = typing.Optional # g['Any'] = Any # g['Union'] = typing.Union # # print('globals: %s' % g) symbols = dict(locals_ or {}) for t in (T,) + refs: symbols[t.__name__] = t name_without = get_name_without_brackets(t.__name__) if name_without not in symbols: symbols[name_without] = Fake(t, symbols) else: pass for x in getattr(T, GENERIC_ATT2, ()): if hasattr(x, '__name__'): symbols[x.__name__] = x annotations = getattr(T, '__annotations__', {}) for k, v in annotations.items(): if not isinstance(v, str) and is_ClassVar(v): continue # XXX try: r = replace_typevars(v, bindings={}, symbols=symbols, rl=None) # rl.p(f'{k!r} -> {v!r} -> {r!r}') annotations[k] = r except NameError as e: msg = f'resolve_type({T.__name__}): Cannot resolve names for attribute "{k}".' msg += f'\n symbols: {symbols}' msg += '\n\n' + indent(traceback.format_exc(), '', '> ') logger.warning(msg) continue except TypeError as e: msg = f'Cannot resolve type for attribute "{k}".' raise TypeError(msg) from e for f in fields(T): if not f.name in annotations: # msg = f'Cannot get annotation for field {f.name!r}' # logger.warning(msg) continue f.type = annotations[f.name] from dataclasses import is_dataclass @loglevel def replace_typevars(cls, *, bindings, symbols, rl: Optional[RecLogger], already=None): rl = rl or RecLogger() # rl.p(f'Replacing typevars {cls}') # rl.p(f' bindings {bindings}') # rl.p(f' symbols {symbols}') already = already or {} if id(cls) in already: return already[id(cls)] elif cls in bindings: return bindings[cls] elif isinstance(cls, str): if cls in symbols: return symbols[cls] g = dict(get_default_attrs()) g.update(symbols) # for t, u in zip(types, types2): # g[t.__name__] = u # g[u.__name__] = u g0 = dict(g) try: return eval(cls, g) except NameError as e: msg = f'Cannot resolve {cls!r}\ng: {list(g0)}' # msg += 'symbols: {list(g0)' raise NameError(msg) from e elif hasattr(cls, '__annotations__'): return make_type(cls, bindings) elif is_Type(cls): x = get_Type_arg(cls) r = replace_typevars(x, bindings=bindings, already=already, symbols=symbols, rl=rl.child('classvar arg')) return Type[r] elif is_ClassVar(cls): x = get_ClassVar_arg(cls) r = replace_typevars(x, bindings=bindings, already=already, symbols=symbols, rl=rl.child('classvar arg')) return typing.ClassVar[r] elif is_List(cls): arg = get_List_arg(cls) return typing.List[ replace_typevars(arg, bindings=bindings, already=already, symbols=symbols, rl=rl.child('list arg'))] elif is_optional(cls): x = get_optional_type(cls) return typing.Optional[ replace_typevars(x, bindings=bindings, already=already, symbols=symbols, rl=rl.child('optional arg'))] elif is_union(cls): xs = get_union_types(cls) ys = tuple(replace_typevars(_, bindings=bindings, already=already, symbols=symbols, rl=rl.child()) for _ in xs) return typing.Union[ys] elif is_forward_ref(cls): T = get_forward_ref_arg(cls) return replace_typevars(T, bindings=bindings, already=already, symbols=symbols, rl=rl.child('forward ')) else: return cls cache_enabled = True cache = {} if PYTHON_36: B = Dict[Any, Any] # bug in Python 3.6 else: B = Dict[TypeVar, Any] @loglevel def make_type(cls: type, bindings: B, rl: RecLogger = None) -> type: if not bindings: return cls cache_key = (str(cls), str(bindings)) if cache_enabled: if cache_key in cache: return cache[cache_key] rl = rl or RecLogger() generic_att2 = getattr(cls, GENERIC_ATT2, ()) assert isinstance(generic_att2, tuple) # rl.p(f'make_type for {cls.__name__}') # rl.p(f' dataclass {is_dataclass(cls)}') # rl.p(f' bindings: {bindings}') # rl.p(f' generic_att: {generic_att2}') symbols = {} annotations = getattr(cls, '__annotations__', {}) name_without = get_name_without_brackets(cls.__name__) def param_name(x): x2 = replace_typevars(x, bindings=bindings, symbols=symbols, rl=rl.child('param_name')) return name_for_type_like(x2) if generic_att2: name2 = '%s[%s]' % (name_without, ",".join(param_name(_) for _ in generic_att2)) else: name2 = name_without # rl.p(' name2: %s' % name2) try: cls2 = type(name2, (cls,), {'need': lambda: None}) except TypeError as e: msg = f'Cannot instantiate from {cls!r}' raise TypeError(msg) from e symbols[name2] = cls2 symbols[cls.__name__] = cls2 # also MyClass[X] should resolve to the same cache[cache_key] = cls2 # class Fake: def __getitem__(self, item): n = name_for_type_like(item) complete = f'{name_without}[{n}]' if complete in symbols: return symbols[complete] # noinspection PyUnresolvedReferences return cls[item] if name_without not in symbols: symbols[name_without] = Fake() else: pass for T, U in bindings.items(): symbols[T.__name__] = U if hasattr(U, '__name__'): # dict does not have name symbols[U.__name__] = U # first of all, replace the bindings in the generic_att generic_att2_new = tuple( replace_typevars(_, bindings=bindings, symbols=symbols, rl=rl.child('attribute')) for _ in generic_att2) # rl.p(f' generic_att2_new: {generic_att2_new}') # pprint(f'\n\n{cls.__name__}') # pprint(f'binding', bindings=str(bindings)) # pprint(f'symbols', **symbols) new_annotations = {} for k, v0 in annotations.items(): # v = eval_type(v0, bindings, symbols) # if hasattr(v, GENERIC_ATT): v = replace_typevars(v0, bindings=bindings, symbols=symbols, rl=rl.child(f'ann {k}')) # print(f'{v0!r} -> {v!r}') if is_ClassVar(v): s = get_ClassVar_arg(v) # s = eval_type(s, bindings, symbols) if is_Type(s): st = get_Type_arg(s) # concrete = eval_type(st, bindings, symbols) concrete = st new_annotations[k] = ClassVar[Type[st]] setattr(cls2, k, concrete) else: new_annotations[k] = ClassVar[s] else: new_annotations[k] = v # pprint(' new annotations', **new_annotations) original__post_init__ = getattr(cls, '__post_init__', None) def __post_init__(self): for k, v in new_annotations.items(): if is_ClassVar(v): continue if isinstance(v, type): val = getattr(self, k) try: if type(val).__name__ != v.__name__ and not isinstance(val, v): msg = f'Expected field "{k}" to be a "{v.__name__}" but found {type(val).__name__}' warnings.warn(msg, stacklevel=3) # raise ValueError(msg) except TypeError as e: msg = f'Cannot judge annotation of {k} (supposedly {v}.' if sys.version_info[:2] == (3, 6): # FIXME: warn continue logger.error(msg) raise TypeError(msg) from e if original__post_init__ is not None: original__post_init__(self) setattr(cls2, '__post_init__', __post_init__) # important: do it before dataclass cls2.__annotations__ = new_annotations # logger.info('new annotations: %s' % new_annotations) if is_dataclass(cls): # note: need to have set new annotations # pprint('creating dataclass from %s' % cls2) cls2 = dataclass(cls2) # setattr(cls2, _FIELDS, fields2) else: # print('Detected that cls = %s not a dataclass' % cls) # noinspection PyUnusedLocal def init_placeholder(self, *args, **kwargs): if args or kwargs: msg = f'Default constructor of {cls2.__name__} does not know what to do with arguments.' msg += f'\nargs: {args!r}\nkwargs: {kwargs!r}' msg += f'\nself: {self}' msg += f'\nself: {dir(type(self))}' msg += f'\nself: {type(self)}' raise NoConstructorImplemented(msg) setattr(cls2, '__init__', init_placeholder) cls2.__module__ = cls.__module__ setattr(cls2, '__name__', name2) setattr(cls2, BINDINGS_ATT, bindings) setattr(cls2, GENERIC_ATT2, generic_att2_new) setattr(cls2, '__post_init__', __post_init__) # rl.p(f' final {cls2.__name__} {cls2.__annotations__}') # rl.p(f' dataclass {is_dataclass(cls2)}') # return cls2
zuper-utils
/zuper-utils-3.0.3.tar.gz/zuper-utils-3.0.3/src/zuper_json/zeneric2.py
zeneric2.py
import typing from typing import Union, Any, Dict from .constants import NAME_ARG from .constants import PYTHON_36 # noinspection PyProtectedMember def is_optional(x): if PYTHON_36: # pragma: no cover return isinstance(x, typing._Union) and len(x.__args__) == 2 and x.__args__[-1] is type(None) else: return isinstance(x, typing._GenericAlias) and (x.__origin__ is Union) and len(x.__args__) == 2 and x.__args__[ -1] is type(None) def get_optional_type(x): assert is_optional(x) return x.__args__[0] def is_union(x): """ Union[X, None] is not considered a Union""" if PYTHON_36: # pragma: no cover return not is_optional(x) and isinstance(x, typing._Union) else: return not is_optional(x) and isinstance(x, typing._GenericAlias) and (x.__origin__ is Union) def get_union_types(x): assert is_union(x) return tuple(x.__args__) def _check_valid_arg(x): if isinstance(x, str): # pragma: no cover msg = f'The annotations must be resolved: {x!r}' raise ValueError(msg) def is_forward_ref(x): _check_valid_arg(x) if PYTHON_36: # pragma: no cover return isinstance(x, typing._ForwardRef) else: return isinstance(x, typing.ForwardRef) def get_forward_ref_arg(x) -> str: assert is_forward_ref(x) return x.__forward_arg__ def is_Any(x): _check_valid_arg(x) if PYTHON_36: # pragma: no cover return str(x) == 'typing.Any' else: # noinspection PyUnresolvedReferences return isinstance(x, typing._SpecialForm) and x._name == 'Any' def is_ClassVar(x): _check_valid_arg(x) if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences return isinstance(x, typing._ClassVar) else: return isinstance(x, typing._GenericAlias) and (x.__origin__ is typing.ClassVar) def get_ClassVar_arg(x): assert is_ClassVar(x) if PYTHON_36: # pragma: no cover return x.__type__ else: return x.__args__[0] def is_Type(x): _check_valid_arg(x) if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences return (x is typing.Type) or (isinstance(x, typing.GenericMeta) and (x.__origin__ is typing.Type)) else: return (x is typing.Type) or (isinstance(x, typing._GenericAlias) and (x.__origin__ is type)) def is_Tuple(x): _check_valid_arg(x) if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences return isinstance(x, typing.TupleMeta) else: return isinstance(x, typing._GenericAlias) and (x._name == 'Tuple') def is_List(x): _check_valid_arg(x) if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences return isinstance(x, typing.GenericMeta) and x.__origin__ is typing.List else: return isinstance(x, typing._GenericAlias) and (x._name == 'List') def get_List_arg(x): assert is_List(x) return x.__args__[0] def get_Type_arg(x): assert is_Type(x) return x.__args__[0] def is_Callable(x): _check_valid_arg(x) if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences return isinstance(x, typing.CallableMeta) else: return getattr(x, '_name', None) == 'Callable' # return hasattr(x, '__origin__') and x.__origin__ is typing.Callable # return isinstance(x, typing._GenericAlias) and x.__origin__.__name__ == "Callable" def is_MyNamedArg(x): return hasattr(x, NAME_ARG) def get_MyNamedArg_name(x): assert is_MyNamedArg(x) return getattr(x, NAME_ARG) def is_Dict(x: Any): _check_valid_arg(x) if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences return isinstance(x, typing.GenericMeta) and x.__origin__ is typing.Dict else: return isinstance(x, typing._GenericAlias) and x._name == 'Dict' def is_Set(x: Any): _check_valid_arg(x) if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences if x is typing.Set: return True return isinstance(x, typing.GenericMeta) and x.__origin__ is typing.Set else: return isinstance(x, typing._GenericAlias) and x._name == 'Set' def get_Set_arg(x): assert is_Set(x) if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences if x is typing.Set: return Any return x.__args__[0] def get_Dict_name(T): assert is_Dict(T) K, V = T.__args__ return get_Dict_name_K_V(K, V) def get_Dict_name_K_V(K, V): return 'Dict[%s,%s]' % (name_for_type_like(K), name_for_type_like(V)) def get_Set_name_V(V): return 'Set[%s]' % (name_for_type_like(V)) def name_for_type_like(x): if is_Any(x): return 'Any' elif isinstance(x, type): return x.__name__ elif isinstance(x, typing.TypeVar): return x.__name__ elif is_Dict(x): return get_Dict_name(x) elif is_Callable(x): info = get_Callable_info(x) params = ','.join(name_for_type_like(p) for p in info.parameters_by_position) ret = name_for_type_like(info.returns) return f'Callable[[{params}],{ret}' elif hasattr(x, '__name__'): return x.__name__ else: return str(x) from typing import Tuple # do not make a dataclass class CallableInfo: parameters_by_name: Dict[str, Any] parameters_by_position: Tuple ordering: Tuple[str, ...] returns: Any def __init__(self, parameters_by_name, parameters_by_position, ordering, returns): self.parameters_by_name = parameters_by_name self.parameters_by_position = parameters_by_position self.ordering = ordering self.returns = returns def get_Callable_info(x) -> CallableInfo: assert is_Callable(x) parameters_by_name = {} parameters_by_position = [] ordering = [] args = x.__args__ if args: returns = args[-1] rest = args[:-1] else: returns = Any rest = () for i, a in enumerate(rest): if is_MyNamedArg(a): name = get_MyNamedArg_name(a) t = a.original else: name = f'#{i}' t = a parameters_by_name[name] = t ordering.append(name) parameters_by_position.append(t) return CallableInfo(parameters_by_name=parameters_by_name, parameters_by_position=tuple(parameters_by_position), ordering=tuple(ordering), returns=returns)
zuper-utils
/zuper-utils-3.0.3.tar.gz/zuper-utils-3.0.3/src/zuper_json/annotations_tricks.py
annotations_tricks.py
elastic-apm -- ZUQA agent for Python =========================================== .. image:: https://apm-ci.elastic.co/buildStatus/icon?job=apm-agent-python%2Fapm-agent-python-mbp%2Fmaster :target: https://apm-ci.elastic.co/job/apm-agent-python/job/apm-agent-python-mbp/ :alt: Build Status .. image:: https://img.shields.io/pypi/v/elastic-apm.svg?style=flat :target: https://pypi.python.org/pypi/zuqa/ :alt: Latest Version .. image:: https://img.shields.io/pypi/pyversions/elastic-apm.svg?style=flat :target: https://pypi.python.org/pypi/elastic-apm/ :alt: Supported Python versions This is the official Python module for ZUQA. It provides full out-of-the-box support for many of the popular frameworks, including Django, and Flask. ZUQA is also easy to adapt for most WSGI-compatible web applications via `custom integrations`_. Your application doesn't live on the web? No problem! ZUQA is easy to use in any Python application. Read the documentation_. .. _documentation: https://www.elastic.co/guide/en/apm/agent/python/current/index.html .. _`custom integrations`: https://www.elastic.co/blog/creating-custom-framework-integrations-with-the-elastic-apm-python-agent License ------- BSD-3-Clause Made with ♥️ and ☕️ by Elastic and our community.
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/README.rst
README.rst
import re import warnings from collections import defaultdict from zuqa.conf.constants import ERROR, MASK, SPAN, TRANSACTION from zuqa.utils import compat, varmap from zuqa.utils.encoding import force_text from zuqa.utils.stacks import get_lines_from_file SANITIZE_FIELD_NAMES = frozenset( ["authorization", "password", "secret", "passwd", "token", "api_key", "access_token", "sessionid"] ) SANITIZE_VALUE_PATTERNS = [re.compile(r"^[- \d]{16,19}$")] # credit card numbers, with or without spacers def for_events(*events): """ :param events: list of event types Only calls wrapped function if given event_type is in list of events """ events = set(events) def wrap(func): func.event_types = events return func return wrap @for_events(ERROR, TRANSACTION) def remove_http_request_body(client, event): """ Removes request.body from context :param client: an ZUQA client :param event: a transaction or error event :return: The modified event """ if "context" in event and "request" in event["context"]: event["context"]["request"].pop("body", None) return event @for_events(ERROR, SPAN) def remove_stacktrace_locals(client, event): """ Removes local variables from any frames. :param client: an ZUQA client :param event: a transaction or error event :return: The modified event """ func = lambda frame: frame.pop("vars", None) return _process_stack_frames(event, func) @for_events(ERROR, SPAN) def sanitize_stacktrace_locals(client, event): """ Sanitizes local variables in all frames :param client: an ZUQA client :param event: a transaction or error event :return: The modified event """ def func(frame): if "vars" in frame: frame["vars"] = varmap(_sanitize, frame["vars"]) return _process_stack_frames(event, func) @for_events(ERROR, TRANSACTION) def sanitize_http_request_cookies(client, event): """ Sanitizes http request cookies :param client: an ZUQA client :param event: a transaction or error event :return: The modified event """ # sanitize request.cookies dict try: cookies = event["context"]["request"]["cookies"] event["context"]["request"]["cookies"] = varmap(_sanitize, cookies) except (KeyError, TypeError): pass # sanitize request.header.cookie string try: cookie_string = event["context"]["request"]["headers"]["cookie"] event["context"]["request"]["headers"]["cookie"] = _sanitize_string(cookie_string, "; ", "=") except (KeyError, TypeError): pass return event @for_events(ERROR, TRANSACTION) def sanitize_http_response_cookies(client, event): """ Sanitizes the set-cookie header of the response :param client: an ZUQA client :param event: a transaction or error event :return: The modified event """ try: cookie_string = event["context"]["response"]["headers"]["set-cookie"] event["context"]["response"]["headers"]["set-cookie"] = _sanitize_string(cookie_string, ";", "=") except (KeyError, TypeError): pass return event @for_events(ERROR, TRANSACTION) def sanitize_http_headers(client, event): """ Sanitizes http request/response headers :param client: an ZUQA client :param event: a transaction or error event :return: The modified event """ # request headers try: headers = event["context"]["request"]["headers"] event["context"]["request"]["headers"] = varmap(_sanitize, headers) except (KeyError, TypeError): pass # response headers try: headers = event["context"]["response"]["headers"] event["context"]["response"]["headers"] = varmap(_sanitize, headers) except (KeyError, TypeError): pass return event @for_events(ERROR, TRANSACTION) def sanitize_http_wsgi_env(client, event): """ Sanitizes WSGI environment variables :param client: an ZUQA client :param event: a transaction or error event :return: The modified event """ try: env = event["context"]["request"]["env"] event["context"]["request"]["env"] = varmap(_sanitize, env) except (KeyError, TypeError): pass return event @for_events(ERROR, TRANSACTION) def sanitize_http_request_querystring(client, event): """ Sanitizes http request query string :param client: an ZUQA client :param event: a transaction or error event :return: The modified event """ try: query_string = force_text(event["context"]["request"]["url"]["search"], errors="replace") except (KeyError, TypeError): return event if "=" in query_string: sanitized_query_string = _sanitize_string(query_string, "&", "=") full_url = event["context"]["request"]["url"]["full"] event["context"]["request"]["url"]["search"] = sanitized_query_string event["context"]["request"]["url"]["full"] = full_url.replace(query_string, sanitized_query_string) return event @for_events(ERROR, TRANSACTION) def sanitize_http_request_body(client, event): """ Sanitizes http request body. This only works if the request body is a query-encoded string. Other types (e.g. JSON) are not handled by this sanitizer. :param client: an ZUQA client :param event: a transaction or error event :return: The modified event """ try: body = force_text(event["context"]["request"]["body"], errors="replace") except (KeyError, TypeError): return event if "=" in body: sanitized_query_string = _sanitize_string(body, "&", "=") event["context"]["request"]["body"] = sanitized_query_string return event @for_events(ERROR, SPAN) def add_context_lines_to_frames(client, event): # divide frames up into source files before reading from disk. This should help # with utilizing the disk cache better # # TODO: further optimize by only opening each file once and reading all needed source # TODO: blocks at once. per_file = defaultdict(list) _process_stack_frames( event, lambda frame: per_file[frame["context_metadata"][0]].append(frame) if "context_metadata" in frame else None, ) for filename, frames in compat.iteritems(per_file): for frame in frames: # context_metadata key has been set in zuqa.utils.stacks.get_frame_info for # all frames for which we should gather source code context lines fname, lineno, context_lines, loader, module_name = frame.pop("context_metadata") pre_context, context_line, post_context = get_lines_from_file( fname, lineno, context_lines, loader, module_name ) if context_line: frame["pre_context"] = pre_context frame["context_line"] = context_line frame["post_context"] = post_context return event @for_events(ERROR, SPAN) def mark_in_app_frames(client, event): warnings.warn( "The mark_in_app_frames processor is deprecated and can be removed from your PROCESSORS setting", DeprecationWarning, ) return event def _sanitize(key, value): if value is None: return if isinstance(value, compat.string_types) and any(pattern.match(value) for pattern in SANITIZE_VALUE_PATTERNS): return MASK if isinstance(value, dict): # varmap will call _sanitize on each k:v pair of the dict, so we don't # have to do anything with dicts here return value if not key: # key can be a NoneType return value key = key.lower() for field in SANITIZE_FIELD_NAMES: if field in key: # store mask as a fixed length for security return MASK return value def _sanitize_string(unsanitized, itemsep, kvsep): """ sanitizes a string that contains multiple key/value items :param unsanitized: the unsanitized string :param itemsep: string that separates items :param kvsep: string that separates key from value :return: a sanitized string """ sanitized = [] kvs = unsanitized.split(itemsep) for kv in kvs: kv = kv.split(kvsep) if len(kv) == 2: sanitized.append((kv[0], _sanitize(kv[0], kv[1]))) else: sanitized.append(kv) return itemsep.join(kvsep.join(kv) for kv in sanitized) def _process_stack_frames(event, func): if "stacktrace" in event: for frame in event["stacktrace"]: func(frame) # an error can have two stacktraces, one in "exception", one in "log" if "exception" in event and "stacktrace" in event["exception"]: for frame in event["exception"]["stacktrace"]: func(frame) # check for chained exceptions cause = event["exception"].get("cause", None) while cause: if "stacktrace" in cause[0]: for frame in cause[0]["stacktrace"]: func(frame) cause = cause[0].get("cause", None) if "log" in event and "stacktrace" in event["log"]: for frame in event["log"]["stacktrace"]: func(frame) return event
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/processors.py
processors.py
import functools import random import re import threading import time import timeit import warnings from collections import defaultdict from zuqa.conf import constants from zuqa.conf.constants import LABEL_RE, SPAN, TRANSACTION from zuqa.context import init_execution_context from zuqa.metrics.base_metrics import Timer from zuqa.utils import compat, encoding, get_name_from_func from zuqa.utils.deprecation import deprecated from zuqa.utils.disttracing import TraceParent, TracingOptions from zuqa.utils.logging import get_logger __all__ = ("capture_span", "tag", "label", "set_transaction_name", "set_custom_context", "set_user_context") error_logger = get_logger("zuqa.errors") logger = get_logger("zuqa.traces") _time_func = timeit.default_timer execution_context = init_execution_context() class ChildDuration(object): __slots__ = ("obj", "_nesting_level", "_start", "_duration", "_lock") def __init__(self, obj): self.obj = obj self._nesting_level = 0 self._start = None self._duration = 0 self._lock = threading.Lock() def start(self, timestamp): with self._lock: self._nesting_level += 1 if self._nesting_level == 1: self._start = timestamp def stop(self, timestamp): with self._lock: self._nesting_level -= 1 if self._nesting_level == 0: self._duration += timestamp - self._start @property def duration(self): return self._duration class BaseSpan(object): def __init__(self, labels=None): self._child_durations = ChildDuration(self) self.labels = {} if labels: self.label(**labels) def child_started(self, timestamp): self._child_durations.start(timestamp) def child_ended(self, timestamp): self._child_durations.stop(timestamp) def end(self, skip_frames=0, duration=None): raise NotImplementedError() def label(self, **labels): """ Label this span with one or multiple key/value labels. Keys should be strings, values can be strings, booleans, or numerical values (int, float, Decimal) span_obj.label(key1="value1", key2=True, key3=42) Note that keys will be dedotted, replacing dot (.), star (*) and double quote (") with an underscore (_) :param labels: key/value pairs of labels :return: None """ labels = encoding.enforce_label_format(labels) self.labels.update(labels) @deprecated("transaction/span.label()") def tag(self, **tags): """ This method is deprecated, please use "label()" instead. Tag this span with one or multiple key/value tags. Both the values should be strings span_obj.tag(key1="value1", key2="value2") Note that keys will be dedotted, replacing dot (.), star (*) and double quote (") with an underscore (_) :param tags: key/value pairs of tags :return: None """ for key in tags.keys(): self.labels[LABEL_RE.sub("_", compat.text_type(key))] = encoding.keyword_field(compat.text_type(tags[key])) class Transaction(BaseSpan): def __init__(self, tracer, transaction_type="custom", trace_parent=None, is_sampled=True, start=None): self.id = "%016x" % random.getrandbits(64) self.trace_parent = trace_parent if start: self.timestamp = self.start_time = start else: self.timestamp, self.start_time = time.time(), _time_func() self.name = None self.duration = None self.result = None self.transaction_type = transaction_type self.tracer = tracer self.dropped_spans = 0 self.context = {} self.is_sampled = is_sampled self._span_counter = 0 self._span_timers = defaultdict(Timer) self._span_timers_lock = threading.Lock() try: self._breakdown = self.tracer._agent._metrics.get_metricset( "zuqa.metrics.sets.breakdown.BreakdownMetricSet" ) except (LookupError, AttributeError): self._breakdown = None try: self._transaction_metrics = self.tracer._agent._metrics.get_metricset( "zuqa.metrics.sets.transactions.TransactionsMetricSet" ) except (LookupError, AttributeError): self._transaction_metrics = None super(Transaction, self).__init__() def end(self, skip_frames=0, duration=None): self.duration = duration if duration is not None else (_time_func() - self.start_time) if self._transaction_metrics: self._transaction_metrics.timer( "transaction.duration", reset_on_collect=True, **{"transaction.name": self.name, "transaction.type": self.transaction_type} ).update(self.duration) if self._breakdown: for (span_type, span_subtype), timer in compat.iteritems(self._span_timers): labels = { "span.type": span_type, "transaction.name": self.name, "transaction.type": self.transaction_type, } if span_subtype: labels["span.subtype"] = span_subtype self._breakdown.timer("span.self_time", reset_on_collect=True, **labels).update(*timer.val) labels = {"transaction.name": self.name, "transaction.type": self.transaction_type} if self.is_sampled: self._breakdown.counter("transaction.breakdown.count", reset_on_collect=True, **labels).inc() self._breakdown.timer( "span.self_time", reset_on_collect=True, **{"span.type": "app", "transaction.name": self.name, "transaction.type": self.transaction_type} ).update(self.duration - self._child_durations.duration) def _begin_span( self, name, span_type, context=None, leaf=False, labels=None, parent_span_id=None, span_subtype=None, span_action=None, sync=True, start=None, ): parent_span = execution_context.get_span() tracer = self.tracer if parent_span and parent_span.leaf: span = DroppedSpan(parent_span, leaf=True) elif tracer.config.transaction_max_spans and self._span_counter > tracer.config.transaction_max_spans - 1: self.dropped_spans += 1 span = DroppedSpan(parent_span) self._span_counter += 1 else: span = Span( transaction=self, name=name, span_type=span_type or "code.custom", context=context, leaf=leaf, labels=labels, parent=parent_span, parent_span_id=parent_span_id, span_subtype=span_subtype, span_action=span_action, sync=sync, start=start, ) span.frames = tracer.frames_collector_func() self._span_counter += 1 execution_context.set_span(span) return span def begin_span( self, name, span_type, context=None, leaf=False, labels=None, span_subtype=None, span_action=None, sync=True, start=None, ): """ Begin a new span :param name: name of the span :param span_type: type of the span :param context: a context dict :param leaf: True if this is a leaf span :param labels: a flat string/string dict of labels :param span_subtype: sub type of the span, e.g. "postgresql" :param span_action: action of the span , e.g. "query" :param start: timestamp, mostly useful for testing :return: the Span object """ return self._begin_span( name, span_type, context=context, leaf=leaf, labels=labels, parent_span_id=None, span_subtype=span_subtype, span_action=span_action, sync=sync, start=start, ) def end_span(self, skip_frames=0, duration=None): """ End the currently active span :param skip_frames: numbers of frames to skip in the stack trace :param duration: override duration, mostly useful for testing :return: the ended span """ span = execution_context.get_span() if span is None: raise LookupError() span.end(skip_frames=skip_frames, duration=duration) return span def ensure_parent_id(self): """If current trace_parent has no span_id, generate one, then return it This is used to generate a span ID which the RUM agent will use to correlate the RUM transaction with the backend transaction. """ if self.trace_parent.span_id == self.id: self.trace_parent.span_id = "%016x" % random.getrandbits(64) logger.debug("Set parent id to generated %s", self.trace_parent.span_id) return self.trace_parent.span_id def to_dict(self): self.context["tags"] = self.labels result = { "id": self.id, "trace_id": self.trace_parent.trace_id, "name": encoding.keyword_field(self.name or ""), "type": encoding.keyword_field(self.transaction_type), "duration": self.duration * 1000, # milliseconds "result": encoding.keyword_field(str(self.result)), "timestamp": int(self.timestamp * 1000000), # microseconds "sampled": self.is_sampled, "span_count": {"started": self._span_counter - self.dropped_spans, "dropped": self.dropped_spans}, } if self.trace_parent: result["trace_id"] = self.trace_parent.trace_id # only set parent_id if this transaction isn't the root if self.trace_parent.span_id and self.trace_parent.span_id != self.id: result["parent_id"] = self.trace_parent.span_id if self.is_sampled: result["context"] = self.context return result def track_span_duration(self, span_type, span_subtype, self_duration): # TODO: once asynchronous spans are supported, we should check if the transaction is already finished # TODO: and, if it has, exit without tracking. with self._span_timers_lock: self._span_timers[(span_type, span_subtype)].update(self_duration) class Span(BaseSpan): __slots__ = ( "id", "transaction", "name", "type", "subtype", "action", "context", "leaf", "timestamp", "start_time", "duration", "parent", "parent_span_id", "frames", "labels", "sync", "_child_durations", ) def __init__( self, transaction, name, span_type, context=None, leaf=False, labels=None, parent=None, parent_span_id=None, span_subtype=None, span_action=None, sync=True, start=None, ): """ Create a new Span :param transaction: transaction object that this span relates to :param name: Generic name of the span :param span_type: type of the span, e.g. db :param context: context dictionary :param leaf: is this span a leaf span? :param labels: a dict of labels :param parent_span_id: override of the span ID :param span_subtype: sub type of the span, e.g. mysql :param span_action: sub type of the span, e.g. query :param sync: indicate if the span was executed synchronously or asynchronously :param start: timestamp, mostly useful for testing """ self.start_time = start or _time_func() self.id = "%016x" % random.getrandbits(64) self.transaction = transaction self.name = name self.context = context if context is not None else {} self.leaf = leaf # timestamp is bit of a mix of monotonic and non-monotonic time sources. # we take the (non-monotonic) transaction timestamp, and add the (monotonic) difference of span # start time and transaction start time. In this respect, the span timestamp is guaranteed to grow # monotonically with respect to the transaction timestamp self.timestamp = transaction.timestamp + (self.start_time - transaction.start_time) self.duration = None self.parent = parent self.parent_span_id = parent_span_id self.frames = None self.sync = sync if span_subtype is None and "." in span_type: # old style dottet type, let's split it up type_bits = span_type.split(".") if len(type_bits) == 2: span_type, span_subtype = type_bits[:2] else: span_type, span_subtype, span_action = type_bits[:3] self.type = span_type self.subtype = span_subtype self.action = span_action if self.transaction._breakdown: p = self.parent if self.parent else self.transaction p.child_started(self.start_time) super(Span, self).__init__(labels=labels) def to_dict(self): result = { "id": self.id, "transaction_id": self.transaction.id, "trace_id": self.transaction.trace_parent.trace_id, # use either the explicitly set parent_span_id, or the id of the parent, or finally the transaction id "parent_id": self.parent_span_id or (self.parent.id if self.parent else self.transaction.id), "name": encoding.keyword_field(self.name), "type": encoding.keyword_field(self.type), "subtype": encoding.keyword_field(self.subtype), "action": encoding.keyword_field(self.action), "sync": self.sync, "timestamp": int(self.timestamp * 1000000), # microseconds "duration": self.duration * 1000, # milliseconds } if self.labels: if self.context is None: self.context = {} self.context["tags"] = self.labels if self.context: result["context"] = self.context if self.frames: result["stacktrace"] = self.frames return result def end(self, skip_frames=0, duration=None): """ End this span and queue it for sending. :param skip_frames: amount of frames to skip from the beginning of the stack trace :param duration: override duration, mostly useful for testing :return: None """ tracer = self.transaction.tracer timestamp = _time_func() self.duration = duration if duration is not None else (timestamp - self.start_time) if not tracer.span_frames_min_duration or self.duration >= tracer.span_frames_min_duration: self.frames = tracer.frames_processing_func(self.frames)[skip_frames:] else: self.frames = None execution_context.set_span(self.parent) tracer.queue_func(SPAN, self.to_dict()) if self.transaction._breakdown: p = self.parent if self.parent else self.transaction p.child_ended(self.start_time + self.duration) self.transaction.track_span_duration( self.type, self.subtype, self.duration - self._child_durations.duration ) def update_context(self, key, data): """ Update the context data for given key :param key: the key, e.g. "db" :param data: a dictionary :return: None """ current = self.context.get(key, {}) current.update(data) self.context[key] = current def __str__(self): return u"{}/{}/{}".format(self.name, self.type, self.subtype) class DroppedSpan(BaseSpan): __slots__ = ("leaf", "parent", "id") def __init__(self, parent, leaf=False): self.parent = parent self.leaf = leaf self.id = None super(DroppedSpan, self).__init__() def end(self, skip_frames=0, duration=None): execution_context.set_span(self.parent) def child_started(self, timestamp): pass def child_ended(self, timestamp): pass def update_context(self, key, data): pass @property def type(self): return None @property def subtype(self): return None @property def action(self): return None @property def context(self): return None class Tracer(object): def __init__(self, frames_collector_func, frames_processing_func, queue_func, config, agent): self.config = config self.queue_func = queue_func self.frames_processing_func = frames_processing_func self.frames_collector_func = frames_collector_func self._agent = agent self._ignore_patterns = [re.compile(p) for p in config.transactions_ignore_patterns or []] @property def span_frames_min_duration(self): if self.config.span_frames_min_duration in (-1, None): return None else: return self.config.span_frames_min_duration / 1000.0 def begin_transaction(self, transaction_type, trace_parent=None, start=None): """ Start a new transactions and bind it in a thread-local variable :param transaction_type: type of the transaction, e.g. "request" :param trace_parent: an optional TraceParent object :param start: override the start timestamp, mostly useful for testing :returns the Transaction object """ if trace_parent: is_sampled = bool(trace_parent.trace_options.recorded) else: is_sampled = ( self.config.transaction_sample_rate == 1.0 or self.config.transaction_sample_rate > random.random() ) transaction = Transaction(self, transaction_type, trace_parent=trace_parent, is_sampled=is_sampled, start=start) if trace_parent is None: transaction.trace_parent = TraceParent( constants.TRACE_CONTEXT_VERSION, "%032x" % random.getrandbits(128), transaction.id, TracingOptions(recorded=is_sampled), ) execution_context.set_transaction(transaction) return transaction def _should_ignore(self, transaction_name): for pattern in self._ignore_patterns: if pattern.search(transaction_name): return True return False def end_transaction(self, result=None, transaction_name=None, duration=None): """ End the current transaction and queue it for sending :param result: result of the transaction, e.g. "OK" or 200 :param transaction_name: name of the transaction :param duration: override duration, mostly useful for testing :return: """ transaction = execution_context.get_transaction(clear=True) if transaction: if transaction.name is None: transaction.name = transaction_name if transaction_name is not None else "" transaction.end(duration=duration) if self._should_ignore(transaction.name): return if transaction.result is None: transaction.result = result self.queue_func(TRANSACTION, transaction.to_dict()) return transaction class capture_span(object): __slots__ = ("name", "type", "subtype", "action", "extra", "skip_frames", "leaf", "labels", "duration", "start") def __init__( self, name=None, span_type="code.custom", extra=None, skip_frames=0, leaf=False, tags=None, labels=None, span_subtype=None, span_action=None, start=None, duration=None, ): self.name = name self.type = span_type self.subtype = span_subtype self.action = span_action self.extra = extra self.skip_frames = skip_frames self.leaf = leaf if tags and not labels: warnings.warn( 'The tags argument to capture_span is deprecated, use "labels" instead', category=DeprecationWarning, stacklevel=2, ) labels = tags self.labels = labels self.start = start self.duration = duration def __call__(self, func): self.name = self.name or get_name_from_func(func) @functools.wraps(func) def decorated(*args, **kwds): with self: return func(*args, **kwds) return decorated def __enter__(self): transaction = execution_context.get_transaction() if transaction and transaction.is_sampled: return transaction.begin_span( self.name, self.type, context=self.extra, leaf=self.leaf, labels=self.labels, span_subtype=self.subtype, span_action=self.action, start=self.start, ) def __exit__(self, exc_type, exc_val, exc_tb): transaction = execution_context.get_transaction() if transaction and transaction.is_sampled: try: span = transaction.end_span(self.skip_frames, duration=self.duration) if exc_val and not isinstance(span, DroppedSpan): try: exc_val._zuqa_span_id = span.id except AttributeError: # could happen if the exception has __slots__ pass except LookupError: logger.info("ended non-existing span %s of type %s", self.name, self.type) def label(**labels): """ Labels current transaction. Keys should be strings, values can be strings, booleans, or numerical values (int, float, Decimal) :param labels: key/value map of labels """ transaction = execution_context.get_transaction() if not transaction: error_logger.warning("Ignored labels %s. No transaction currently active.", ", ".join(labels.keys())) else: transaction.label(**labels) @deprecated("zuqa.label") def tag(**tags): """ Tags current transaction. Both key and value of the label should be strings. """ transaction = execution_context.get_transaction() if not transaction: error_logger.warning("Ignored tags %s. No transaction currently active.", ", ".join(tags.keys())) else: transaction.tag(**tags) def set_transaction_name(name, override=True): transaction = execution_context.get_transaction() if not transaction: return if transaction.name is None or override: transaction.name = name def set_transaction_result(result, override=True): transaction = execution_context.get_transaction() if not transaction: return if transaction.result is None or override: transaction.result = result def get_transaction_id(): """ Returns the current transaction ID """ transaction = execution_context.get_transaction() if not transaction: return return transaction.id def get_trace_id(): """ Returns the current trace ID """ transaction = execution_context.get_transaction() if not transaction: return return transaction.trace_parent.trace_id if transaction.trace_parent else None def get_span_id(): """ Returns the current span ID """ span = execution_context.get_span() if not span: return return span.id def set_context(data, key="custom"): """ Attach contextual data to the current transaction and errors that happen during the current transaction. If the transaction is not sampled, this function becomes a no-op. :param data: a dictionary, or a callable that returns a dictionary :param key: the namespace for this data """ transaction = execution_context.get_transaction() if not (transaction and transaction.is_sampled): return if callable(data): data = data() # remove invalid characters from key names for k in list(data.keys()): if LABEL_RE.search(k): data[LABEL_RE.sub("_", k)] = data.pop(k) if key in transaction.context: transaction.context[key].update(data) else: transaction.context[key] = data set_custom_context = functools.partial(set_context, key="custom") def set_user_context(username=None, email=None, user_id=None): data = {} if username is not None: data["username"] = encoding.keyword_field(username) if email is not None: data["email"] = encoding.keyword_field(email) if user_id is not None: data["id"] = encoding.keyword_field(user_id) set_context(data, "user")
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/traces.py
traces.py
from __future__ import absolute_import import inspect import itertools import logging import os import platform import sys import threading import time import warnings from copy import deepcopy import zuqa from zuqa.conf import Config, VersionedConfig, constants from zuqa.conf.constants import ERROR from zuqa.metrics.base_metrics import MetricsRegistry from zuqa.traces import Tracer, execution_context from zuqa.utils import cgroup, compat, is_master_process, stacks, varmap from zuqa.utils.encoding import enforce_label_format, keyword_field, shorten, transform from zuqa.utils.logging import get_logger from zuqa.utils.module_import import import_string __all__ = ("Client",) class Client(object): """ The base ZUQA client, which handles communication over the HTTP API to the APM Server. Will read default configuration from the environment variable ``ZUQA_APP_NAME`` and ``ZUQA_SECRET_TOKEN`` if available. :: >>> from zuqa import Client >>> # Read configuration from environment >>> client = Client() >>> # Configure the client manually >>> client = Client( >>> include_paths=['my.package'], >>> service_name='myapp', >>> secret_token='secret_token', >>> ) >>> # Record an exception >>> try: >>> 1/0 >>> except ZeroDivisionError: >>> ident = client.capture_exception() >>> print ("Exception caught; reference is %%s" %% ident) """ logger = get_logger("zuqa") def __init__(self, config=None, **inline): # configure loggers first cls = self.__class__ self.logger = get_logger("%s.%s" % (cls.__module__, cls.__name__)) self.error_logger = get_logger("zuqa.errors") self._pid = None self._thread_starter_lock = threading.Lock() self._thread_managers = {} self.tracer = None self.processors = [] self.filter_exception_types_dict = {} self._service_info = None self.check_python_version() config = Config(config, inline_dict=inline) if config.errors: for msg in config.errors.values(): self.error_logger.error(msg) config.disable_send = True self.config = VersionedConfig(config, version=None) # Insert the log_record_factory into the logging library # The LogRecordFactory functionality is only available on python 3.2+ if compat.PY3 and not self.config.disable_log_record_factory: record_factory = logging.getLogRecordFactory() # Only way to know if it's wrapped is to create a log record throwaway_record = record_factory(__name__, logging.DEBUG, __file__, 252, "dummy_msg", [], None) if not hasattr(throwaway_record, "zuqa_labels"): self.logger.debug("Inserting zuqa log_record_factory into logging") # Late import due to circular imports import zuqa.handlers.logging as elastic_logging new_factory = elastic_logging.log_record_factory(record_factory) logging.setLogRecordFactory(new_factory) headers = { "Content-Type": "application/x-ndjson", "Content-Encoding": "gzip", "User-Agent": "zuqa-python/%s" % zuqa.VERSION, } transport_kwargs = { "metadata": self._build_metadata(), "headers": headers, "verify_server_cert": self.config.verify_server_cert, "server_cert": self.config.server_cert, "timeout": self.config.server_timeout, "processors": self.load_processors(), } self._api_endpoint_url = compat.urlparse.urljoin( self.config.server_url if self.config.server_url.endswith("/") else self.config.server_url + "/", constants.EVENTS_API_PATH, ) transport_class = import_string(self.config.transport_class) self._transport = transport_class(self._api_endpoint_url, self, **transport_kwargs) self.config.transport = self._transport self._thread_managers["transport"] = self._transport for exc_to_filter in self.config.filter_exception_types or []: exc_to_filter_type = exc_to_filter.split(".")[-1] exc_to_filter_module = ".".join(exc_to_filter.split(".")[:-1]) self.filter_exception_types_dict[exc_to_filter_type] = exc_to_filter_module if platform.python_implementation() == "PyPy": # PyPy introduces a `_functools.partial.__call__` frame due to our use # of `partial` in AbstractInstrumentedModule skip_modules = ("zuqa.", "_functools") else: skip_modules = ("zuqa.",) self.tracer = Tracer( frames_collector_func=lambda: list( stacks.iter_stack_frames( start_frame=inspect.currentframe(), skip_top_modules=skip_modules, config=self.config ) ), frames_processing_func=lambda frames: self._get_stack_info_for_trace( frames, library_frame_context_lines=self.config.source_lines_span_library_frames, in_app_frame_context_lines=self.config.source_lines_span_app_frames, with_locals=self.config.collect_local_variables in ("all", "transactions"), locals_processor_func=lambda local_var: varmap( lambda k, v: shorten( v, list_length=self.config.local_var_list_max_length, string_length=self.config.local_var_max_length, dict_length=self.config.local_var_dict_max_length, ), local_var, ), ), queue_func=self.queue, config=self.config, agent=self, ) self.include_paths_re = stacks.get_path_regex(self.config.include_paths) if self.config.include_paths else None self.exclude_paths_re = stacks.get_path_regex(self.config.exclude_paths) if self.config.exclude_paths else None self._metrics = MetricsRegistry(self) for path in self.config.metrics_sets: self._metrics.register(path) if self.config.breakdown_metrics: self._metrics.register("zuqa.metrics.sets.breakdown.BreakdownMetricSet") self._thread_managers["metrics"] = self._metrics compat.atexit_register(self.close) if self.config.central_config: self._thread_managers["config"] = self.config else: self._config_updater = None if config.enabled: self.start_threads() def start_threads(self): with self._thread_starter_lock: current_pid = os.getpid() if self._pid != current_pid: self.logger.debug("Detected PID change from %r to %r, starting threads", self._pid, current_pid) for manager_type, manager in self._thread_managers.items(): self.logger.debug("Starting %s thread", manager_type) manager.start_thread(pid=current_pid) self._pid = current_pid def get_handler(self, name): return import_string(name) def capture(self, event_type, date=None, context=None, custom=None, stack=None, handled=True, **kwargs): """ Captures and processes an event and pipes it off to Client.send. """ if not self.config.is_recording: return if event_type == "Exception": # never gather log stack for exceptions stack = False data = self._build_msg_for_logging( event_type, date=date, context=context, custom=custom, stack=stack, handled=handled, **kwargs ) if data: # queue data, and flush the queue if this is an unhandled exception self.queue(ERROR, data, flush=not handled) return data["id"] def capture_message(self, message=None, param_message=None, **kwargs): """ Creates an event from ``message``. >>> client.capture_message('My event just happened!') """ return self.capture("Message", message=message, param_message=param_message, **kwargs) def capture_exception(self, exc_info=None, handled=True, **kwargs): """ Creates an event from an exception. >>> try: >>> exc_info = sys.exc_info() >>> client.capture_exception(exc_info) >>> finally: >>> del exc_info If exc_info is not provided, or is set to True, then this method will perform the ``exc_info = sys.exc_info()`` and the requisite clean-up for you. """ return self.capture("Exception", exc_info=exc_info, handled=handled, **kwargs) def queue(self, event_type, data, flush=False): if self.config.disable_send: return self.start_threads() if flush and is_master_process(): # don't flush in uWSGI master process to avoid ending up in an unpredictable threading state flush = False self._transport.queue(event_type, data, flush) def begin_transaction(self, transaction_type, trace_parent=None, start=None): """ Register the start of a transaction on the client :param transaction_type: type of the transaction, e.g. "request" :param trace_parent: an optional TraceParent object for distributed tracing :param start: override the start timestamp, mostly useful for testing :return: the started transaction object """ self._metrics.collect_actively = True if self.config.is_recording: return self.tracer.begin_transaction(transaction_type, trace_parent=trace_parent, start=start) def end_transaction(self, name=None, result="", duration=None): """ End the current transaction. :param name: optional name of the transaction :param result: result of the transaction, e.g. "OK" or "HTTP 2xx" :param duration: override duration, mostly useful for testing :return: the ended transaction object """ transaction = self.tracer.end_transaction(result, name, duration=duration) self._metrics.last_transaction_name = transaction.name self._metrics.collect_actively = False return transaction def close(self): if self.config.enabled: with self._thread_starter_lock: for _, manager in self._thread_managers.items(): manager.stop_thread() def get_service_info(self): if self._service_info: return self._service_info language_version = platform.python_version() if hasattr(sys, "pypy_version_info"): runtime_version = ".".join(map(str, sys.pypy_version_info[:3])) else: runtime_version = language_version result = { "name": keyword_field(self.config.service_name), "environment": keyword_field(self.config.environment), "version": keyword_field(self.config.service_version), "agent": {"name": "python", "version": zuqa.VERSION}, "language": {"name": "python", "version": keyword_field(platform.python_version())}, "runtime": { "name": keyword_field(platform.python_implementation()), "version": keyword_field(runtime_version), }, } if self.config.framework_name: result["framework"] = { "name": keyword_field(self.config.framework_name), "version": keyword_field(self.config.framework_version), } if self.config.service_node_name: result["node"] = {"configured_name": keyword_field(self.config.service_node_name)} self._service_info = result return result def get_process_info(self): return { "pid": os.getpid(), "ppid": os.getppid() if hasattr(os, "getppid") else None, "argv": sys.argv, "title": None, # Note: if we implement this, the value needs to be wrapped with keyword_field } def get_system_info(self): system_data = { "hostname": keyword_field(self.config.hostname), "architecture": platform.machine(), "platform": platform.system().lower(), } system_data.update(cgroup.get_cgroup_container_metadata()) pod_name = os.environ.get("KUBERNETES_POD_NAME") or system_data["hostname"] changed = False if "kubernetes" in system_data: k8s = system_data["kubernetes"] k8s["pod"]["name"] = pod_name else: k8s = {"pod": {"name": pod_name}} # get kubernetes metadata from environment if "KUBERNETES_NODE_NAME" in os.environ: k8s["node"] = {"name": os.environ["KUBERNETES_NODE_NAME"]} changed = True if "KUBERNETES_NAMESPACE" in os.environ: k8s["namespace"] = os.environ["KUBERNETES_NAMESPACE"] changed = True if "KUBERNETES_POD_UID" in os.environ: # this takes precedence over any value from /proc/self/cgroup k8s["pod"]["uid"] = os.environ["KUBERNETES_POD_UID"] changed = True if changed: system_data["kubernetes"] = k8s return system_data def _build_metadata(self): data = { "service": self.get_service_info(), "process": self.get_process_info(), "system": self.get_system_info(), } if self.config.global_labels: data["labels"] = enforce_label_format(self.config.global_labels) return data def _build_msg_for_logging( self, event_type, date=None, context=None, custom=None, stack=None, handled=True, **kwargs ): """ Captures, processes and serializes an event into a dict object """ transaction = execution_context.get_transaction() span = execution_context.get_span() if transaction: transaction_context = deepcopy(transaction.context) else: transaction_context = {} event_data = {} if custom is None: custom = {} if date is not None: warnings.warn( "The date argument is no longer evaluated and will be removed in a future release", DeprecationWarning ) date = time.time() if stack is None: stack = self.config.auto_log_stacks if context: transaction_context.update(context) context = transaction_context else: context = transaction_context event_data["context"] = context if transaction and transaction.labels: context["tags"] = deepcopy(transaction.labels) # if '.' not in event_type: # Assume it's a builtin event_type = "zuqa.events.%s" % event_type handler = self.get_handler(event_type) result = handler.capture(self, **kwargs) if self._filter_exception_type(result): return # data (explicit) culprit takes over auto event detection culprit = result.pop("culprit", None) if custom.get("culprit"): culprit = custom.pop("culprit") for k, v in compat.iteritems(result): if k not in event_data: event_data[k] = v log = event_data.get("log", {}) if stack and "stacktrace" not in log: if stack is True: frames = stacks.iter_stack_frames(skip=3, config=self.config) else: frames = stack frames = stacks.get_stack_info( frames, with_locals=self.config.collect_local_variables in ("errors", "all"), library_frame_context_lines=self.config.source_lines_error_library_frames, in_app_frame_context_lines=self.config.source_lines_error_app_frames, include_paths_re=self.include_paths_re, exclude_paths_re=self.exclude_paths_re, locals_processor_func=lambda local_var: varmap( lambda k, v: shorten( v, list_length=self.config.local_var_list_max_length, string_length=self.config.local_var_max_length, dict_length=self.config.local_var_dict_max_length, ), local_var, ), ) log["stacktrace"] = frames if "stacktrace" in log and not culprit: culprit = stacks.get_culprit(log["stacktrace"], self.config.include_paths, self.config.exclude_paths) if "level" in log and isinstance(log["level"], compat.integer_types): log["level"] = logging.getLevelName(log["level"]).lower() if log: event_data["log"] = log if culprit: event_data["culprit"] = culprit if "custom" in context: context["custom"].update(custom) else: context["custom"] = custom # Make sure all data is coerced event_data = transform(event_data) if "exception" in event_data: event_data["exception"]["handled"] = bool(handled) event_data["timestamp"] = int(date * 1000000) if transaction: if transaction.trace_parent: event_data["trace_id"] = transaction.trace_parent.trace_id # parent id might already be set in the handler event_data.setdefault("parent_id", span.id if span else transaction.id) event_data["transaction_id"] = transaction.id event_data["transaction"] = {"sampled": transaction.is_sampled, "type": transaction.transaction_type} return event_data def _filter_exception_type(self, data): exception = data.get("exception") if not exception: return False exc_type = exception.get("type") exc_module = exception.get("module") if exc_module == "None": exc_module = None if exc_type in self.filter_exception_types_dict: exc_to_filter_module = self.filter_exception_types_dict[exc_type] if not exc_to_filter_module or exc_to_filter_module == exc_module: if exc_module: exc_name = "%s.%s" % (exc_module, exc_type) else: exc_name = exc_type self.logger.info("Ignored %s exception due to exception type filter", exc_name) return True return False def _get_stack_info_for_trace( self, frames, library_frame_context_lines=None, in_app_frame_context_lines=None, with_locals=True, locals_processor_func=None, ): """Overrideable in derived clients to add frames/info, e.g. templates""" return stacks.get_stack_info( frames, library_frame_context_lines=library_frame_context_lines, in_app_frame_context_lines=in_app_frame_context_lines, with_locals=with_locals, include_paths_re=self.include_paths_re, exclude_paths_re=self.exclude_paths_re, locals_processor_func=locals_processor_func, ) def load_processors(self): """ Loads processors from self.config.processors, as well as constants.HARDCODED_PROCESSORS. Duplicate processors (based on the path) will be discarded. :return: a list of callables """ processors = itertools.chain(self.config.processors, constants.HARDCODED_PROCESSORS) seen = {} # setdefault has the nice property that it returns the value that it just set on the dict return [seen.setdefault(path, import_string(path)) for path in processors if path not in seen] def check_python_version(self): v = tuple(map(int, platform.python_version_tuple()[:2])) if v == (2, 7): warnings.warn( ( "The ZUQA agent will stop supporting Python 2.7 starting in 6.0.0 -- " "Please upgrade to Python 3.5+ to continue to use the latest features." ), PendingDeprecationWarning, ) elif v < (3, 5): warnings.warn("The ZUQA agent only supports Python 3.5+", DeprecationWarning) class DummyClient(Client): """Sends messages into an empty void""" def send(self, url, **kwargs): return None
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/base.py
base.py
import random import sys from zuqa.conf.constants import EXCEPTION_CHAIN_MAX_DEPTH from zuqa.utils import compat, varmap from zuqa.utils.encoding import keyword_field, shorten, to_unicode from zuqa.utils.logging import get_logger from zuqa.utils.stacks import get_culprit, get_stack_info, iter_traceback_frames __all__ = ("BaseEvent", "Exception", "Message") logger = get_logger("zuqa.events") class BaseEvent(object): @staticmethod def to_string(client, data): raise NotImplementedError @staticmethod def capture(client, **kwargs): return {} class Exception(BaseEvent): """ Exceptions store the following metadata: - value: 'My exception value' - type: 'ClassName' - module '__builtin__' (i.e. __builtin__.TypeError) - frames: a list of serialized frames (see _get_traceback_frames) """ @staticmethod def to_string(client, data): exc = data["exception"] if exc["value"]: return "%s: %s" % (exc["type"], exc["value"]) return exc["type"] @staticmethod def get_hash(data): exc = data["exception"] output = [exc["type"]] for frame in data["stacktrace"]["frames"]: output.append(frame["module"]) output.append(frame["function"]) return output @staticmethod def capture(client, exc_info=None, **kwargs): culprit = exc_value = exc_type = exc_module = frames = exc_traceback = None new_exc_info = False if not exc_info or exc_info is True: new_exc_info = True exc_info = sys.exc_info() if exc_info == (None, None, None): raise ValueError("No exception found: capture_exception requires an active exception.") try: exc_type, exc_value, exc_traceback = exc_info frames = get_stack_info( iter_traceback_frames(exc_traceback, config=client.config), with_locals=client.config.collect_local_variables in ("errors", "all"), library_frame_context_lines=client.config.source_lines_error_library_frames, in_app_frame_context_lines=client.config.source_lines_error_app_frames, include_paths_re=client.include_paths_re, exclude_paths_re=client.exclude_paths_re, locals_processor_func=lambda local_var: varmap( lambda k, val: shorten( val, list_length=client.config.local_var_list_max_length, string_length=client.config.local_var_max_length, dict_length=client.config.local_var_dict_max_length, ), local_var, ), ) culprit = kwargs.get("culprit", None) or get_culprit( frames, client.config.include_paths, client.config.exclude_paths ) if hasattr(exc_type, "__module__"): exc_module = exc_type.__module__ exc_type = exc_type.__name__ else: exc_module = None exc_type = exc_type.__name__ finally: if new_exc_info: try: del exc_info del exc_traceback except Exception as e: logger.exception(e) if "message" in kwargs: message = kwargs["message"] else: message = "%s: %s" % (exc_type, to_unicode(exc_value)) if exc_value else str(exc_type) data = { "id": "%032x" % random.getrandbits(128), "culprit": keyword_field(culprit), "exception": { "message": message, "type": keyword_field(str(exc_type)), "module": keyword_field(str(exc_module)), "stacktrace": frames, }, } if hasattr(exc_value, "_zuqa_span_id"): data["parent_id"] = exc_value._zuqa_span_id del exc_value._zuqa_span_id if compat.PY3: depth = kwargs.get("_exc_chain_depth", 0) if depth > EXCEPTION_CHAIN_MAX_DEPTH: return cause = exc_value.__cause__ chained_context = exc_value.__context__ # we follow the pattern of Python itself here and only capture the chained exception # if cause is not None and __suppress_context__ is False if chained_context and not (exc_value.__suppress_context__ and cause is None): if cause: chained_exc_type = type(cause) chained_exc_value = cause else: chained_exc_type = type(chained_context) chained_exc_value = chained_context chained_exc_info = chained_exc_type, chained_exc_value, chained_context.__traceback__ chained_cause = Exception.capture( client, exc_info=chained_exc_info, culprit="None", _exc_chain_depth=depth + 1 ) if chained_cause: data["exception"]["cause"] = [chained_cause["exception"]] return data class Message(BaseEvent): """ Messages store the following metadata: - message: 'My message from %s about %s' - params: ('foo', 'bar') """ @staticmethod def to_string(client, data): return data["log"]["message"] @staticmethod def get_hash(data): msg = data["param_message"] return [msg["message"]] @staticmethod def capture(client, param_message=None, message=None, level=None, logger_name=None, **kwargs): if message: param_message = {"message": message} params = param_message.get("params") message = param_message["message"] % params if params else param_message["message"] data = kwargs.get("data", {}) message_data = { "id": "%032x" % random.getrandbits(128), "log": { "level": keyword_field(level or "error"), "logger_name": keyword_field(logger_name or "__root__"), "message": message, "param_message": keyword_field(param_message["message"]), }, } if isinstance(data.get("stacktrace"), dict): message_data["log"]["stacktrace"] = data["stacktrace"]["frames"] if kwargs.get("exception"): message_data["culprit"] = kwargs["exception"]["culprit"] message_data["exception"] = kwargs["exception"]["exception"] return message_data
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/events.py
events.py
import aiohttp from aiohttp.web import HTTPException, Response, middleware import zuqa from zuqa.conf import constants from zuqa.contrib.aiohttp.utils import get_data_from_request, get_data_from_response from zuqa.utils.disttracing import TraceParent class AioHttpTraceParent(TraceParent): @classmethod def merge_duplicate_headers(cls, headers, key): return ",".join(headers.getall(key, [])) or None def tracing_middleware(app): from zuqa.contrib.aiohttp import CLIENT_KEY # noqa async def handle_request(request, handler): zuqa_client = app.get(CLIENT_KEY) if zuqa_client: request[CLIENT_KEY] = zuqa_client trace_parent = AioHttpTraceParent.from_headers(request.headers) zuqa_client.begin_transaction("request", trace_parent=trace_parent) resource = request.match_info.route.resource name = request.method if resource: # canonical has been added in 3.3, and returns one of path, formatter, prefix for attr in ("canonical", "_path", "_formatter", "_prefix"): if hasattr(resource, attr): name += " " + getattr(resource, attr) break else: name += " unknown route" else: name += " unknown route" zuqa.set_transaction_name(name, override=False) zuqa.set_context( lambda: get_data_from_request(request, zuqa_client.config, constants.TRANSACTION), "request" ) try: response = await handler(request) zuqa.set_transaction_result("HTTP {}xx".format(response.status // 100), override=False) zuqa.set_context( lambda: get_data_from_response(response, zuqa_client.config, constants.TRANSACTION), "response" ) return response except Exception as exc: if zuqa_client: zuqa_client.capture_exception( context={"request": get_data_from_request(request, zuqa_client.config, constants.ERROR)} ) zuqa.set_transaction_result("HTTP 5xx", override=False) zuqa.set_context({"status_code": 500}, "response") # some exceptions are response-like, e.g. have headers and status code. Let's try and capture them if isinstance(exc, (Response, HTTPException)): zuqa.set_context( lambda: get_data_from_response(exc, zuqa_client.config, constants.ERROR), # noqa: F821 "response", ) raise finally: zuqa_client.end_transaction() # decorating with @middleware is only required in aiohttp < 4.0, and we only support 3+ if aiohttp.__version__.startswith("3"): return middleware(handle_request) return handle_request
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/contrib/aiohttp/middleware.py
middleware.py
from celery import signals from zuqa.utils import get_name_from_func class CeleryFilter(object): def filter(self, record): if record.funcName in ("_log_error",): return 0 else: return 1 def register_exception_tracking(client): dispatch_uid = "zuqa-exc-tracking" def process_failure_signal(sender, task_id, exception, args, kwargs, traceback, einfo, **kw): client.capture_exception( extra={"task_id": task_id, "task": sender, "args": args, "kwargs": kwargs}, handled=False ) signals.task_failure.disconnect(process_failure_signal, dispatch_uid=dispatch_uid) signals.task_failure.connect(process_failure_signal, weak=False, dispatch_uid=dispatch_uid) _register_worker_signals(client) def register_instrumentation(client): def begin_transaction(*args, **kwargs): client.begin_transaction("celery") def end_transaction(task_id, task, *args, **kwargs): name = get_name_from_func(task) client.end_transaction(name, kwargs.get("state", "None")) dispatch_uid = "zuqa-tracing-%s" # unregister any existing clients signals.task_prerun.disconnect(begin_transaction, dispatch_uid=dispatch_uid % "prerun") signals.task_postrun.disconnect(end_transaction, dispatch_uid=dispatch_uid % "postrun") # register for this client signals.task_prerun.connect(begin_transaction, dispatch_uid=dispatch_uid % "prerun", weak=False) signals.task_postrun.connect(end_transaction, weak=False, dispatch_uid=dispatch_uid % "postrun") _register_worker_signals(client) def _register_worker_signals(client): def worker_shutdown(*args, **kwargs): client.close() def connect_worker_process_init(*args, **kwargs): signals.worker_process_shutdown.connect(worker_shutdown, dispatch_uid="zuqa-shutdown-worker", weak=False) signals.worker_init.connect( connect_worker_process_init, dispatch_uid="zuqa-connect-start-threads", weak=False )
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/contrib/celery/__init__.py
__init__.py
from werkzeug.exceptions import ClientDisconnected from zuqa.conf import constants from zuqa.utils import compat, get_url_dict from zuqa.utils.wsgi import get_environ, get_headers def get_data_from_request(request, config, event_type): result = { "env": dict(get_environ(request.environ)), "method": request.method, "socket": {"remote_address": request.environ.get("REMOTE_ADDR"), "encrypted": request.is_secure}, "cookies": request.cookies, } if config.capture_headers: result["headers"] = dict(get_headers(request.environ)) if request.method in constants.HTTP_WITH_BODY: if config.capture_body not in ("all", event_type): result["body"] = "[REDACTED]" else: body = None if request.content_type == "application/x-www-form-urlencoded": body = compat.multidict_to_dict(request.form) elif request.content_type and request.content_type.startswith("multipart/form-data"): body = compat.multidict_to_dict(request.form) if request.files: body["_files"] = { field: val[0].filename if len(val) == 1 else [f.filename for f in val] for field, val in compat.iterlists(request.files) } else: try: body = request.get_data(as_text=True) except ClientDisconnected: pass if body is not None: result["body"] = body result["url"] = get_url_dict(request.url) return result def get_data_from_response(response, config, event_type): result = {} if isinstance(getattr(response, "status_code", None), compat.integer_types): result["status_code"] = response.status_code if config.capture_headers and getattr(response, "headers", None): headers = response.headers result["headers"] = {key: ";".join(headers.getlist(key)) for key in compat.iterkeys(headers)} return result
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/contrib/flask/utils.py
utils.py
from __future__ import absolute_import import logging import flask from flask import request, signals import zuqa import zuqa.instrumentation.control from zuqa.base import Client from zuqa.conf import constants, setup_logging from zuqa.contrib.flask.utils import get_data_from_request, get_data_from_response from zuqa.handlers.logging import LoggingHandler from zuqa.traces import execution_context from zuqa.utils import build_name_with_http_method_prefix from zuqa.utils.disttracing import TraceParent from zuqa.utils.logging import get_logger logger = get_logger("zuqa.errors.client") def make_client(client_cls, app, **defaults): config = app.config.get("ZUQA", {}) if "framework_name" not in defaults: defaults["framework_name"] = "flask" defaults["framework_version"] = getattr(flask, "__version__", "<0.7") client = client_cls(config, **defaults) return client class ZUQA(object): """ Flask application for ZUQA. Look up configuration from ``os.environ.get('ZUQA_APP_NAME')`` and ``os.environ.get('ZUQA_SECRET_TOKEN')``:: >>> zuqa = ZUQA(app) Pass an arbitrary APP_NAME and SECRET_TOKEN:: >>> zuqa = ZUQA(app, service_name='myapp', secret_token='asdasdasd') Pass an explicit client:: >>> zuqa = ZUQA(app, client=client) Automatically configure logging:: >>> zuqa = ZUQA(app, logging=True) Capture an exception:: >>> try: >>> 1 / 0 >>> except ZeroDivisionError: >>> zuqa.capture_exception() Capture a message:: >>> zuqa.capture_message('hello, world!') """ def __init__(self, app=None, client=None, client_cls=Client, logging=False, **defaults): self.app = app self.logging = logging self.client_cls = client_cls self.client = client if app: self.init_app(app, **defaults) def handle_exception(self, *args, **kwargs): if not self.client: return if self.app.debug and not self.client.config.debug: return self.client.capture_exception( exc_info=kwargs.get("exc_info"), context={"request": get_data_from_request(request, self.client.config, constants.ERROR)}, custom={"app": self.app}, handled=False, ) # End the transaction here, as `request_finished` won't be called when an # unhandled exception occurs. # # Unfortunately, that also means that we can't capture any response data, # as the response isn't ready at this point in time. self.client.end_transaction(result="HTTP 5xx") def init_app(self, app, **defaults): self.app = app if not self.client: self.client = make_client(self.client_cls, app, **defaults) # 0 is a valid log level (NOTSET), so we need to check explicitly for it if self.logging or self.logging is logging.NOTSET: if self.logging is not True: kwargs = {"level": self.logging} else: kwargs = {} setup_logging(LoggingHandler(self.client, **kwargs)) signals.got_request_exception.connect(self.handle_exception, sender=app, weak=False) try: from zuqa.contrib.celery import register_exception_tracking register_exception_tracking(self.client) except ImportError: pass # Instrument to get spans if self.client.config.instrument and self.client.config.enabled: zuqa.instrumentation.control.instrument() signals.request_started.connect(self.request_started, sender=app) signals.request_finished.connect(self.request_finished, sender=app) try: from zuqa.contrib.celery import register_instrumentation register_instrumentation(self.client) except ImportError: pass else: logger.debug("Skipping instrumentation. INSTRUMENT is set to False.") @app.context_processor def rum_tracing(): """ Adds APM related IDs to the context used for correlating the backend transaction with the RUM transaction """ transaction = execution_context.get_transaction() if transaction and transaction.trace_parent: return { "apm": { "trace_id": transaction.trace_parent.trace_id, "span_id": lambda: transaction.ensure_parent_id(), "is_sampled": transaction.is_sampled, "is_sampled_js": "true" if transaction.is_sampled else "false", } } return {} def request_started(self, app): if not self.app.debug or self.client.config.debug: trace_parent = TraceParent.from_headers(request.headers) self.client.begin_transaction("request", trace_parent=trace_parent) zuqa.set_context( lambda: get_data_from_request(request, self.client.config, constants.TRANSACTION), "request" ) rule = request.url_rule.rule if request.url_rule is not None else "" rule = build_name_with_http_method_prefix(rule, request) zuqa.set_transaction_name(rule, override=False) def request_finished(self, app, response): if not self.app.debug or self.client.config.debug: zuqa.set_context( lambda: get_data_from_response(response, self.client.config, constants.TRANSACTION), "response" ) if response.status_code: result = "HTTP {}xx".format(response.status_code // 100) else: result = response.status zuqa.set_transaction_result(result, override=False) # Instead of calling end_transaction here, we defer the call until the response is closed. # This ensures that we capture things that happen until the WSGI server closes the response. response.call_on_close(self.client.end_transaction) def capture_exception(self, *args, **kwargs): assert self.client, "capture_exception called before application configured" return self.client.capture_exception(*args, **kwargs) def capture_message(self, *args, **kwargs): assert self.client, "capture_message called before application configured" return self.client.capture_message(*args, **kwargs)
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/contrib/flask/__init__.py
__init__.py
import inspect from zuqa.base import Client class Middleware(object): """ZUQA middleware for ZeroRPC. >>> zuqa = Middleware(service_name='..', secret_token='...') >>> zerorpc.Context.get_instance().register_middleware(zuqa) Exceptions detected server-side in ZeroRPC will be submitted to the apm server (and propagated to the client as well). """ def __init__(self, hide_zerorpc_frames=True, client=None, **kwargs): """Create a middleware object that can be injected in a ZeroRPC server. - hide_zerorpc_frames: modify the exception stacktrace to remove the internal zerorpc frames (True by default to make the stacktrace as readable as possible); - client: use an existing raven.Client object, otherwise one will be instantiated from the keyword arguments. """ self._zuqa_client = client or Client(**kwargs) self._hide_zerorpc_frames = hide_zerorpc_frames def server_inspect_exception(self, req_event, rep_event, task_ctx, exc_info): """Called when an exception has been raised in the code run by ZeroRPC""" # Hide the zerorpc internal frames for readability, for a REQ/REP or # REQ/STREAM server the frames to hide are: # - core.ServerBase._async_task # - core.Pattern*.process_call # - core.DecoratorBase.__call__ # # For a PUSH/PULL or PUB/SUB server the frame to hide is: # - core.Puller._receiver if self._hide_zerorpc_frames: traceback = exc_info[2] while traceback: zerorpc_frame = traceback.tb_frame zerorpc_frame.f_locals["__traceback_hide__"] = True frame_info = inspect.getframeinfo(zerorpc_frame) # Is there a better way than this (or looking up the filenames # or hardcoding the number of frames to skip) to know when we # are out of zerorpc? if frame_info.function == "__call__" or frame_info.function == "_receiver": break traceback = traceback.tb_next self._zuqa_client.capture_exception(exc_info, extra=task_ctx, handled=False)
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/contrib/zerorpc/__init__.py
__init__.py
from functools import partial from django.apps import AppConfig from django.conf import settings as django_settings from zuqa.conf import constants from zuqa.contrib.django.client import get_client from zuqa.utils.disttracing import TraceParent from zuqa.utils.logging import get_logger logger = get_logger("zuqa.traces") ERROR_DISPATCH_UID = "zuqa-exceptions" REQUEST_START_DISPATCH_UID = "zuqa-request-start" REQUEST_FINISH_DISPATCH_UID = "zuqa-request-stop" MIDDLEWARE_NAME = "zuqa.contrib.django.middleware.TracingMiddleware" TRACEPARENT_HEADER_NAME_WSGI = "HTTP_" + constants.TRACEPARENT_HEADER_NAME.upper().replace("-", "_") TRACEPARENT_LEGACY_HEADER_NAME_WSGI = "HTTP_" + constants.TRACEPARENT_LEGACY_HEADER_NAME.upper().replace("-", "_") TRACESTATE_HEADER_NAME_WSGI = "HTTP_" + constants.TRACESTATE_HEADER_NAME.upper().replace("-", "_") class ZuqaConfig(AppConfig): name = "zuqa.contrib.django" label = "zuqa.contrib.django" verbose_name = "ZUQA" def __init__(self, *args, **kwargs): super(ZuqaConfig, self).__init__(*args, **kwargs) self.client = None def ready(self): self.client = get_client() if self.client.config.autoinsert_django_middleware: self.insert_middleware(django_settings) register_handlers(self.client) if self.client.config.instrument and self.client.config.enabled: instrument(self.client) else: self.client.logger.debug("Skipping instrumentation. INSTRUMENT is set to False.") @staticmethod def insert_middleware(settings): if hasattr(settings, "MIDDLEWARE"): middleware_list = settings.MIDDLEWARE middleware_attr = "MIDDLEWARE" elif hasattr(settings, "MIDDLEWARE_CLASSES"): # can be removed when we drop support for Django 1.x middleware_list = settings.MIDDLEWARE_CLASSES middleware_attr = "MIDDLEWARE_CLASSES" else: logger.debug("Could not find middleware setting, not autoinserting tracing middleware") return is_tuple = isinstance(middleware_list, tuple) if is_tuple: middleware_list = list(middleware_list) elif not isinstance(middleware_list, list): logger.debug("%s setting is not of type list or tuple, not autoinserting tracing middleware") return if middleware_list is not None and MIDDLEWARE_NAME not in middleware_list: logger.debug("Inserting tracing middleware into settings.%s", middleware_attr) middleware_list.insert(0, MIDDLEWARE_NAME) if is_tuple: middleware_list = tuple(middleware_list) if middleware_list: setattr(settings, middleware_attr, middleware_list) def register_handlers(client): from django.core.signals import got_request_exception, request_started, request_finished from zuqa.contrib.django.handlers import exception_handler # Connect to Django's internal signal handlers got_request_exception.disconnect(dispatch_uid=ERROR_DISPATCH_UID) got_request_exception.connect(partial(exception_handler, client), dispatch_uid=ERROR_DISPATCH_UID, weak=False) request_started.disconnect(dispatch_uid=REQUEST_START_DISPATCH_UID) request_started.connect( partial(_request_started_handler, client), dispatch_uid=REQUEST_START_DISPATCH_UID, weak=False ) request_finished.disconnect(dispatch_uid=REQUEST_FINISH_DISPATCH_UID) request_finished.connect( lambda sender, **kwargs: client.end_transaction() if _should_start_transaction(client) else None, dispatch_uid=REQUEST_FINISH_DISPATCH_UID, weak=False, ) # If we can import celery, register ourselves as exception handler try: import celery # noqa F401 from zuqa.contrib.celery import register_exception_tracking try: register_exception_tracking(client) except Exception as e: client.logger.exception("Failed installing django-celery hook: %s" % e) except ImportError: client.logger.debug("Not instrumenting Celery, couldn't import") def _request_started_handler(client, sender, *args, **kwargs): if not _should_start_transaction(client): return # try to find trace id if "environ" in kwargs: trace_parent = TraceParent.from_headers( kwargs["environ"], TRACEPARENT_HEADER_NAME_WSGI, TRACEPARENT_LEGACY_HEADER_NAME_WSGI, TRACESTATE_HEADER_NAME_WSGI, ) elif "scope" in kwargs and "headers" in kwargs["scope"]: trace_parent = TraceParent.from_headers(kwargs["scope"]["headers"]) else: trace_parent = None client.begin_transaction("request", trace_parent=trace_parent) def instrument(client): """ Auto-instruments code to get nice spans """ from zuqa.instrumentation.control import instrument instrument() try: import celery # noqa F401 from zuqa.contrib.celery import register_instrumentation register_instrumentation(client) except ImportError: client.logger.debug("Not instrumenting Celery, couldn't import") def _should_start_transaction(client): middleware_attr = "MIDDLEWARE" if getattr(django_settings, "MIDDLEWARE", None) is not None else "MIDDLEWARE_CLASSES" middleware = getattr(django_settings, middleware_attr) return ( (not django_settings.DEBUG or client.config.debug) and middleware and "zuqa.contrib.django.middleware.TracingMiddleware" in middleware )
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/contrib/django/apps.py
apps.py
from __future__ import absolute_import import django from django.conf import settings as django_settings from django.core.exceptions import DisallowedHost from django.db import DatabaseError from django.http import HttpRequest from zuqa.base import Client from zuqa.conf import constants from zuqa.contrib.django.utils import iterate_with_template_sources from zuqa.utils import compat, encoding, get_url_dict from zuqa.utils.logging import get_logger from zuqa.utils.module_import import import_string from zuqa.utils.wsgi import get_environ, get_headers __all__ = ("DjangoClient",) default_client_class = "zuqa.contrib.django.DjangoClient" _client = (None, None) def get_client(client=None): """ Get an ZUQA client. :param client: :return: :rtype: zuqa.base.Client """ global _client tmp_client = client is not None if not tmp_client: config = getattr(django_settings, "ZUQA", {}) client = config.get("CLIENT", default_client_class) if _client[0] != client: client_class = import_string(client) instance = client_class() if not tmp_client: _client = (client, instance) return instance return _client[1] class DjangoClient(Client): logger = get_logger("zuqa.errors.client.django") def __init__(self, config=None, **inline): if config is None: config = getattr(django_settings, "ZUQA", {}) if "framework_name" not in inline: inline["framework_name"] = "django" inline["framework_version"] = django.get_version() super(DjangoClient, self).__init__(config, **inline) def get_user_info(self, request): user_info = {} if not hasattr(request, "user"): return user_info try: user = request.user if hasattr(user, "is_authenticated"): if callable(user.is_authenticated): user_info["is_authenticated"] = user.is_authenticated() else: user_info["is_authenticated"] = bool(user.is_authenticated) if hasattr(user, "id"): user_info["id"] = encoding.keyword_field(user.id) if hasattr(user, "get_username"): user_info["username"] = encoding.keyword_field(encoding.force_text(user.get_username())) elif hasattr(user, "username"): user_info["username"] = encoding.keyword_field(encoding.force_text(user.username)) if hasattr(user, "email"): user_info["email"] = encoding.force_text(user.email) except DatabaseError: # If the connection is closed or similar, we'll just skip this return {} return user_info def get_data_from_request(self, request, event_type): result = { "env": dict(get_environ(request.META)), "method": request.method, "socket": {"remote_address": request.META.get("REMOTE_ADDR"), "encrypted": request.is_secure()}, "cookies": dict(request.COOKIES), } if self.config.capture_headers: request_headers = dict(get_headers(request.META)) for key, value in request_headers.items(): if isinstance(value, (int, float)): request_headers[key] = str(value) result["headers"] = request_headers if request.method in constants.HTTP_WITH_BODY: capture_body = self.config.capture_body in ("all", event_type) if not capture_body: result["body"] = "[REDACTED]" else: content_type = request.META.get("CONTENT_TYPE") if content_type == "application/x-www-form-urlencoded": data = compat.multidict_to_dict(request.POST) elif content_type and content_type.startswith("multipart/form-data"): data = compat.multidict_to_dict(request.POST) if request.FILES: data["_files"] = {field: file.name for field, file in compat.iteritems(request.FILES)} else: try: data = request.body except Exception as e: self.logger.debug("Can't capture request body: %s", compat.text_type(e)) data = "<unavailable>" if data is not None: result["body"] = data if hasattr(request, "get_raw_uri"): # added in Django 1.9 url = request.get_raw_uri() else: try: # Requires host to be in ALLOWED_HOSTS, might throw a # DisallowedHost exception url = request.build_absolute_uri() except DisallowedHost: # We can't figure out the real URL, so we have to set it to # DisallowedHost result["url"] = {"full": "DisallowedHost"} url = None if url: result["url"] = get_url_dict(url) return result def get_data_from_response(self, response, event_type): result = {"status_code": response.status_code} if self.config.capture_headers and hasattr(response, "items"): response_headers = dict(response.items()) for key, value in response_headers.items(): if isinstance(value, (int, float)): response_headers[key] = str(value) result["headers"] = response_headers return result def capture(self, event_type, request=None, **kwargs): if "context" not in kwargs: kwargs["context"] = context = {} else: context = kwargs["context"] is_http_request = isinstance(request, HttpRequest) if is_http_request: context["request"] = self.get_data_from_request(request, constants.ERROR) context["user"] = self.get_user_info(request) result = super(DjangoClient, self).capture(event_type, **kwargs) if is_http_request: # attach the zuqa object to the request request._zuqa = {"service_name": self.config.service_name, "id": result} return result def _get_stack_info_for_trace( self, frames, library_frame_context_lines=None, in_app_frame_context_lines=None, with_locals=True, locals_processor_func=None, ): """If the stacktrace originates within the zuqa module, it will skip frames until some other module comes up.""" return list( iterate_with_template_sources( frames, with_locals=with_locals, library_frame_context_lines=library_frame_context_lines, in_app_frame_context_lines=in_app_frame_context_lines, include_paths_re=self.include_paths_re, exclude_paths_re=self.exclude_paths_re, locals_processor_func=locals_processor_func, ) ) def send(self, url, **kwargs): """ Serializes and signs ``data`` and passes the payload off to ``send_remote`` If ``server`` was passed into the constructor, this will serialize the data and pipe it to the server using ``send_remote()``. """ if self.config.server_url: return super(DjangoClient, self).send(url, **kwargs) else: self.error_logger.error("No server configured, and zuqa not installed. Cannot send message") return None class ProxyClient(object): """ A proxy which represents the current client at all times. """ # introspection support: __members__ = property(lambda x: x.__dir__()) # Need to pretend to be the wrapped class, for the sake of objects that care # about this (especially in equality tests) __class__ = property(lambda x: get_client().__class__) __dict__ = property(lambda o: get_client().__dict__) __repr__ = lambda: repr(get_client()) __getattr__ = lambda x, o: getattr(get_client(), o) __setattr__ = lambda x, o, v: setattr(get_client(), o, v) __delattr__ = lambda x, o: delattr(get_client(), o) __lt__ = lambda x, o: get_client() < o __le__ = lambda x, o: get_client() <= o __eq__ = lambda x, o: get_client() == o __ne__ = lambda x, o: get_client() != o __gt__ = lambda x, o: get_client() > o __ge__ = lambda x, o: get_client() >= o if compat.PY2: __cmp__ = lambda x, o: cmp(get_client(), o) # noqa F821 __hash__ = lambda x: hash(get_client()) # attributes are currently not callable # __call__ = lambda x, *a, **kw: get_client()(*a, **kw) __nonzero__ = lambda x: bool(get_client()) __len__ = lambda x: len(get_client()) __getitem__ = lambda x, i: get_client()[i] __iter__ = lambda x: iter(get_client()) __contains__ = lambda x, i: i in get_client() __getslice__ = lambda x, i, j: get_client()[i:j] __add__ = lambda x, o: get_client() + o __sub__ = lambda x, o: get_client() - o __mul__ = lambda x, o: get_client() * o __floordiv__ = lambda x, o: get_client() // o __mod__ = lambda x, o: get_client() % o __divmod__ = lambda x, o: get_client().__divmod__(o) __pow__ = lambda x, o: get_client() ** o __lshift__ = lambda x, o: get_client() << o __rshift__ = lambda x, o: get_client() >> o __and__ = lambda x, o: get_client() & o __xor__ = lambda x, o: get_client() ^ o __or__ = lambda x, o: get_client() | o __div__ = lambda x, o: get_client().__div__(o) __truediv__ = lambda x, o: get_client().__truediv__(o) __neg__ = lambda x: -(get_client()) __pos__ = lambda x: +(get_client()) __abs__ = lambda x: abs(get_client()) __invert__ = lambda x: ~(get_client()) __complex__ = lambda x: complex(get_client()) __int__ = lambda x: int(get_client()) if compat.PY2: __long__ = lambda x: long(get_client()) # noqa F821 __float__ = lambda x: float(get_client()) __str__ = lambda x: str(get_client()) __unicode__ = lambda x: compat.text_type(get_client()) __oct__ = lambda x: oct(get_client()) __hex__ = lambda x: hex(get_client()) __index__ = lambda x: get_client().__index__() __coerce__ = lambda x, o: x.__coerce__(x, o) __enter__ = lambda x: x.__enter__() __exit__ = lambda x, *a, **kw: x.__exit__(*a, **kw) client = ProxyClient() def _get_installed_apps_paths(): """ Generate a list of modules in settings.INSTALLED_APPS. """ out = set() for app in django_settings.INSTALLED_APPS: out.add(app) return out
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/contrib/django/client.py
client.py
from django.template.base import Node from zuqa.utils.stacks import get_frame_info try: from django.template.base import Template except ImportError: class Template(object): pass def iterate_with_template_sources( frames, with_locals=True, library_frame_context_lines=None, in_app_frame_context_lines=None, include_paths_re=None, exclude_paths_re=None, locals_processor_func=None, ): template = None for frame, lineno in frames: f_code = getattr(frame, "f_code", None) if f_code: function_name = frame.f_code.co_name if function_name == "render": renderer = getattr(frame, "f_locals", {}).get("self") if renderer and isinstance(renderer, Node): if getattr(renderer, "token", None) is not None: if hasattr(renderer, "source"): # up to Django 1.8 yield {"lineno": renderer.token.lineno, "filename": renderer.source[0].name} else: template = {"lineno": renderer.token.lineno} # Django 1.9 doesn't have the origin on the Node instance, # so we have to get it a bit further down the stack from the # Template instance elif renderer and isinstance(renderer, Template): if template and getattr(renderer, "origin", None): template["filename"] = renderer.origin.name yield template template = None yield get_frame_info( frame, lineno, library_frame_context_lines=library_frame_context_lines, in_app_frame_context_lines=in_app_frame_context_lines, with_locals=with_locals, include_paths_re=include_paths_re, exclude_paths_re=exclude_paths_re, locals_processor_func=locals_processor_func, )
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/contrib/django/utils.py
utils.py
from __future__ import absolute_import import logging import sys import warnings from django.apps import apps from django.conf import settings as django_settings from zuqa.handlers.logging import LoggingHandler as BaseLoggingHandler from zuqa.utils.logging import get_logger logger = get_logger("zuqa.logging") class LoggingHandler(BaseLoggingHandler): def __init__(self, level=logging.NOTSET): # skip initialization of BaseLoggingHandler logging.Handler.__init__(self, level=level) @property def client(self): try: app = apps.get_app_config("zuqa.contrib.django") if not app.client: logger.warning("Can't send log message to APM server, Django apps not initialized yet") return app.client except LookupError: logger.warning("Can't send log message to APM server, zuqa.contrib.django not in INSTALLED_APPS") def _emit(self, record, **kwargs): from zuqa.contrib.django.middleware import LogMiddleware # Fetch the request from a threadlocal variable, if available request = getattr(LogMiddleware.thread, "request", None) request = getattr(record, "request", request) return super(LoggingHandler, self)._emit(record, request=request, **kwargs) def exception_handler(client, request=None, **kwargs): def actually_do_stuff(request=None, **kwargs): exc_info = sys.exc_info() try: if (django_settings.DEBUG and not client.config.debug) or getattr(exc_info[1], "skip_zuqa", False): return client.capture("Exception", exc_info=exc_info, request=request, handled=False) except Exception as exc: try: client.error_logger.exception(u"Unable to process log entry: %s" % (exc,)) except Exception as exc: warnings.warn(u"Unable to process log entry: %s" % (exc,)) finally: try: del exc_info except Exception as e: client.error_logger.exception(e) return actually_do_stuff(request, **kwargs)
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/contrib/django/handlers.py
handlers.py
from __future__ import absolute_import import sys from django.conf import settings from django.core.management.base import BaseCommand from django.core.management.color import color_style from django.utils import termcolors from zuqa.contrib.django.client import DjangoClient from zuqa.utils.compat import urlparse try: from django.core.management.base import OutputWrapper except ImportError: OutputWrapper = None blue = termcolors.make_style(opts=("bold",), fg="blue") cyan = termcolors.make_style(opts=("bold",), fg="cyan") green = termcolors.make_style(fg="green") magenta = termcolors.make_style(opts=("bold",), fg="magenta") red = termcolors.make_style(opts=("bold",), fg="red") white = termcolors.make_style(opts=("bold",), fg="white") yellow = termcolors.make_style(opts=("bold",), fg="yellow") class TestException(Exception): pass class ColoredLogger(object): def __init__(self, stream): self.stream = stream self.errors = [] self.color = color_style() def log(self, level, *args, **kwargs): style = kwargs.pop("style", self.color.NOTICE) msg = " ".join((level.upper(), args[0] % args[1:], "\n")) if OutputWrapper is None: self.stream.write(msg) else: self.stream.write(msg, style_func=style) def error(self, *args, **kwargs): kwargs["style"] = red self.log("error", *args, **kwargs) self.errors.append((args,)) def warning(self, *args, **kwargs): kwargs["style"] = yellow self.log("warning", *args, **kwargs) def info(self, *args, **kwargs): kwargs["style"] = green self.log("info", *args, **kwargs) CONFIG_EXAMPLE = """ You can set it in your settings file: ZUQA = { 'SERVICE_NAME': '<YOUR-SERVICE-NAME>', 'SECRET_TOKEN': '<YOUR-SECRET-TOKEN>', } or with environment variables: $ export ZUQA_SERVICE_NAME="<YOUR-SERVICE-NAME>" $ export ZUQA_SECRET_TOKEN="<YOUR-SECRET-TOKEN>" $ python manage.py zuqa check """ class Command(BaseCommand): arguments = ( (("-s", "--service-name"), {"default": None, "dest": "service_name", "help": "Specifies the service name."}), (("-t", "--token"), {"default": None, "dest": "secret_token", "help": "Specifies the secret token."}), ) args = "test check" def add_arguments(self, parser): parser.add_argument("subcommand") for args, kwargs in self.arguments: parser.add_argument(*args, **kwargs) def handle(self, *args, **options): if "subcommand" in options: subcommand = options["subcommand"] else: return self.handle_command_not_found("No command specified.") if subcommand not in self.dispatch: self.handle_command_not_found('No such command "%s".' % subcommand) else: self.dispatch.get(subcommand, self.handle_command_not_found)(self, subcommand, **options) def handle_test(self, command, **options): """Send a test error to APM Server""" # can't be async for testing config = {"async_mode": False} for key in ("service_name", "secret_token"): if options.get(key): config[key] = options[key] client = DjangoClient(**config) client.error_logger = ColoredLogger(self.stderr) client.logger = ColoredLogger(self.stderr) self.write( "Trying to send a test error to APM Server using these settings:\n\n" "SERVICE_NAME:\t%s\n" "SECRET_TOKEN:\t%s\n" "SERVER:\t\t%s\n\n" % (client.config.service_name, client.config.secret_token, client.config.server_url) ) try: raise TestException("Hi there!") except TestException: client.capture_exception() if not client.error_logger.errors: self.write( "Success! We tracked the error successfully! \n" "You should see it in the APM app in Kibana momentarily. \n" 'Look for "TestException: Hi there!" in the Errors tab of the %s app' % client.config.service_name ) finally: client.close() def handle_check(self, command, **options): """Check your settings for common misconfigurations""" passed = True client = DjangoClient(metrics_interval="0ms") def is_set(x): return x and x != "None" # check if org/app is set: if is_set(client.config.service_name): self.write("Service name is set, good job!", green) else: passed = False self.write("Configuration errors detected!", red, ending="\n\n") self.write(" * SERVICE_NAME not set! ", red, ending="\n") self.write(CONFIG_EXAMPLE) # secret token is optional but recommended if not is_set(client.config.secret_token): self.write(" * optional SECRET_TOKEN not set", yellow, ending="\n") self.write("") server_url = client.config.server_url if server_url: parsed_url = urlparse.urlparse(server_url) if parsed_url.scheme.lower() in ("http", "https"): # parse netloc, making sure people did not supply basic auth if "@" in parsed_url.netloc: credentials, _, path = parsed_url.netloc.rpartition("@") passed = False self.write("Configuration errors detected!", red, ending="\n\n") if ":" in credentials: self.write(" * SERVER_URL cannot contain authentication " "credentials", red, ending="\n") else: self.write( " * SERVER_URL contains an unexpected at-sign!" " This is usually used for basic authentication, " "but the colon is left out", red, ending="\n", ) else: self.write("SERVER_URL {0} looks fine".format(server_url), green) # secret token in the clear not recommended if is_set(client.config.secret_token) and parsed_url.scheme.lower() == "http": self.write(" * SECRET_TOKEN set but server not using https", yellow, ending="\n") else: self.write( " * SERVER_URL has scheme {0} and we require " "http or https!".format(parsed_url.scheme), red, ending="\n", ) passed = False else: self.write("Configuration errors detected!", red, ending="\n\n") self.write(" * SERVER_URL appears to be empty", red, ending="\n") passed = False self.write("") # check if we're disabled due to DEBUG: if settings.DEBUG: if getattr(settings, "ZUQA", {}).get("DEBUG"): self.write( "Note: even though you are running in DEBUG mode, we will " 'send data to the APM Server, because you set ZUQA["DEBUG"] to ' "True. You can disable ZUQA while in DEBUG mode like this" "\n\n", yellow, ) self.write( " ZUQA = {\n" ' "DEBUG": False,\n' " # your other ZUQA settings\n" " }" ) else: self.write( "Looks like you're running in DEBUG mode. ZUQA will NOT " "gather any data while DEBUG is set to True.\n\n", red, ) self.write( "If you want to test ZUQA while DEBUG is set to True, you" " can force ZUQA to gather data by setting" ' ZUQA["DEBUG"] to True, like this\n\n' " ZUQA = {\n" ' "DEBUG": True,\n' " # your other ZUQA settings\n" " }" ) passed = False else: self.write("DEBUG mode is disabled! Looking good!", green) self.write("") # check if middleware is set, and if it is at the first position middleware_attr = "MIDDLEWARE" if getattr(settings, "MIDDLEWARE", None) is not None else "MIDDLEWARE_CLASSES" middleware = list(getattr(settings, middleware_attr)) try: pos = middleware.index("zuqa.contrib.django.middleware.TracingMiddleware") if pos == 0: self.write("Tracing middleware is configured! Awesome!", green) else: self.write("Tracing middleware is configured, but not at the first position\n", yellow) self.write("ZUQA works best if you add it at the top of your %s setting" % middleware_attr) except ValueError: self.write("Tracing middleware not configured!", red) self.write( "\n" "Add it to your %(name)s setting like this:\n\n" " %(name)s = (\n" ' "zuqa.contrib.django.middleware.TracingMiddleware",\n' " # your other middleware classes\n" " )\n" % {"name": middleware_attr} ) self.write("") if passed: self.write("Looks like everything should be ready!", green) else: self.write("Please fix the above errors.", red) self.write("") client.close() return passed def handle_command_not_found(self, message): self.write(message, red, ending="") self.write(" Please use one of the following commands:\n\n", red) self.write("".join(" * %s\t%s\n" % (k.ljust(8), v.__doc__) for k, v in self.dispatch.items())) self.write("\n") argv = self._get_argv() self.write("Usage:\n\t%s zuqa <command>" % (" ".join(argv[: argv.index("zuqa")]))) def write(self, msg, style_func=None, ending=None, stream=None): """ wrapper around self.stdout/stderr to ensure Django 1.4 compatibility """ if stream is None: stream = self.stdout if OutputWrapper is None: ending = "\n" if ending is None else ending msg += ending stream.write(msg) else: stream.write(msg, style_func=style_func, ending=ending) def _get_argv(self): """allow cleaner mocking of sys.argv""" return sys.argv dispatch = {"test": handle_test, "check": handle_check}
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/contrib/django/management/commands/elasticapm.py
elasticapm.py
from __future__ import absolute_import import logging import threading from django.apps import apps from django.conf import settings as django_settings import zuqa from zuqa.conf import constants from zuqa.contrib.django.client import client, get_client from zuqa.utils import build_name_with_http_method_prefix, get_name_from_func, wrapt try: from importlib import import_module except ImportError: from django.utils.importlib import import_module try: from django.utils.deprecation import MiddlewareMixin except ImportError: # no-op class for Django < 1.10 class MiddlewareMixin(object): pass def _is_ignorable_404(uri): """ Returns True if the given request *shouldn't* notify the site managers. """ urls = getattr(django_settings, "IGNORABLE_404_URLS", ()) return any(pattern.search(uri) for pattern in urls) class ZuqaClientMiddlewareMixin(object): @property def client(self): try: app = apps.get_app_config("zuqa.contrib.django") return app.client except LookupError: return get_client() class Catch404Middleware(MiddlewareMixin, ZuqaClientMiddlewareMixin): def process_response(self, request, response): if response.status_code != 404 or _is_ignorable_404(request.get_full_path()): return response if django_settings.DEBUG and not self.client.config.debug: return response data = {"level": logging.INFO, "logger": "http404"} result = self.client.capture( "Message", request=request, param_message={"message": "Page Not Found: %s", "params": [request.build_absolute_uri()]}, logger_name="http404", level=logging.INFO, ) request._zuqa = {"service_name": data.get("service_name", self.client.config.service_name), "id": result} return response def get_name_from_middleware(wrapped, instance): name = [type(instance).__name__, wrapped.__name__] if type(instance).__module__: name = [type(instance).__module__] + name return ".".join(name) def process_request_wrapper(wrapped, instance, args, kwargs): response = wrapped(*args, **kwargs) try: if response is not None: request = args[0] zuqa.set_transaction_name( build_name_with_http_method_prefix(get_name_from_middleware(wrapped, instance), request) ) finally: return response def process_response_wrapper(wrapped, instance, args, kwargs): response = wrapped(*args, **kwargs) try: request, original_response = args # if there's no view_func on the request, and this middleware created # a new response object, it's logged as the responsible transaction # name if not hasattr(request, "_zuqa_view_func") and response is not original_response: zuqa.set_transaction_name( build_name_with_http_method_prefix(get_name_from_middleware(wrapped, instance), request) ) finally: return response class TracingMiddleware(MiddlewareMixin, ZuqaClientMiddlewareMixin): _zuqa_instrumented = False _instrumenting_lock = threading.Lock() def __init__(self, *args, **kwargs): super(TracingMiddleware, self).__init__(*args, **kwargs) if not self._zuqa_instrumented: with self._instrumenting_lock: if not self._zuqa_instrumented: if self.client.config.instrument_django_middleware: self.instrument_middlewares() TracingMiddleware._zuqa_instrumented = True def instrument_middlewares(self): middlewares = getattr(django_settings, "MIDDLEWARE", None) or getattr( django_settings, "MIDDLEWARE_CLASSES", None ) if middlewares: for middleware_path in middlewares: module_path, class_name = middleware_path.rsplit(".", 1) try: module = import_module(module_path) middleware_class = getattr(module, class_name) if middleware_class == type(self): # don't instrument ourselves continue if hasattr(middleware_class, "process_request"): wrapt.wrap_function_wrapper(middleware_class, "process_request", process_request_wrapper) if hasattr(middleware_class, "process_response"): wrapt.wrap_function_wrapper(middleware_class, "process_response", process_response_wrapper) except ImportError: client.logger.info("Can't instrument middleware %s", middleware_path) def process_view(self, request, view_func, view_args, view_kwargs): request._zuqa_view_func = view_func def process_response(self, request, response): if django_settings.DEBUG and not self.client.config.debug: return response try: if hasattr(response, "status_code"): transaction_name = None if self.client.config.django_transaction_name_from_route and hasattr(request.resolver_match, "route"): transaction_name = request.resolver_match.route elif getattr(request, "_zuqa_view_func", False): transaction_name = get_name_from_func(request._zuqa_view_func) if transaction_name: transaction_name = build_name_with_http_method_prefix(transaction_name, request) zuqa.set_transaction_name(transaction_name, override=False) zuqa.set_context( lambda: self.client.get_data_from_request(request, constants.TRANSACTION), "request" ) zuqa.set_context( lambda: self.client.get_data_from_response(response, constants.TRANSACTION), "response" ) zuqa.set_context(lambda: self.client.get_user_info(request), "user") zuqa.set_transaction_result("HTTP {}xx".format(response.status_code // 100), override=False) except Exception: self.client.error_logger.error("Exception during timing of request", exc_info=True) return response class ErrorIdMiddleware(MiddlewareMixin): """ Appends the X-ZUQA-ErrorId response header for referencing a message within the ZUQA datastore. """ def process_response(self, request, response): if not getattr(request, "_zuqa", None): return response response["X-ZUQA-ErrorId"] = request._zuqa["id"] return response class LogMiddleware(MiddlewareMixin): # Create a thread local variable to store the session in for logging thread = threading.local() def process_request(self, request): self.thread.request = request
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/contrib/django/middleware/__init__.py
__init__.py
import functools from zuqa.conf.constants import LABEL_RE from zuqa.traces import DroppedSpan, capture_span, error_logger, execution_context from zuqa.utils import get_name_from_func class async_capture_span(capture_span): def __call__(self, func): self.name = self.name or get_name_from_func(func) @functools.wraps(func) async def decorated(*args, **kwds): async with self: return await func(*args, **kwds) return decorated async def __aenter__(self): transaction = execution_context.get_transaction() if transaction and transaction.is_sampled: return transaction.begin_span( self.name, self.type, context=self.extra, leaf=self.leaf, labels=self.labels, span_subtype=self.subtype, span_action=self.action, sync=False, start=self.start, ) async def __aexit__(self, exc_type, exc_val, exc_tb): transaction = execution_context.get_transaction() if transaction and transaction.is_sampled: try: span = transaction.end_span(self.skip_frames) if exc_val and not isinstance(span, DroppedSpan): try: exc_val._zuqa_span_id = span.id except AttributeError: # could happen if the exception has __slots__ pass except LookupError: error_logger.info("ended non-existing span %s of type %s", self.name, self.type) async def set_context(data, key="custom"): """ Asynchronous copy of zuqa.traces.set_context(). Attach contextual data to the current transaction and errors that happen during the current transaction. If the transaction is not sampled, this function becomes a no-op. :param data: a dictionary, or a callable that returns a dictionary :param key: the namespace for this data """ transaction = execution_context.get_transaction() if not (transaction and transaction.is_sampled): return if callable(data): data = await data() # remove invalid characters from key names for k in list(data.keys()): if LABEL_RE.search(k): data[LABEL_RE.sub("_", k)] = data.pop(k) if key in transaction.context: transaction.context[key].update(data) else: transaction.context[key] = data
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/contrib/asyncio/traces.py
traces.py
import json from starlette.requests import Request from starlette.responses import Response from starlette.types import Message from zuqa.conf import Config, constants from zuqa.utils import compat, get_url_dict async def get_data_from_request(request: Request, config: Config, event_type: str) -> dict: """Loads data from incoming request for APM capturing. Args: request (Request) config (Config) event_type (str) Returns: dict """ result = { "method": request.method, "socket": {"remote_address": _get_client_ip(request), "encrypted": request.url.is_secure}, "cookies": request.cookies, } if config.capture_headers: result["headers"] = dict(request.headers) if request.method in constants.HTTP_WITH_BODY: if config.capture_body not in ("all", event_type): result["body"] = "[REDACTED]" else: body = None try: body = await get_body(request) if request.headers.get("content-type") == "application/x-www-form-urlencoded": body = await query_params_to_dict(body) else: body = json.loads(body) except Exception: pass if body is not None: result["body"] = body result["url"] = get_url_dict(str(request.url)) return result async def get_data_from_response(response: Response, config: Config, event_type: str) -> dict: """Loads data from response for APM capturing. Args: response (Response) config (Config) event_type (str) Returns: dict """ result = {} if isinstance(getattr(response, "status_code", None), compat.integer_types): result["status_code"] = response.status_code if config.capture_headers and getattr(response, "headers", None): headers = response.headers result["headers"] = {key: ";".join(headers.getlist(key)) for key in compat.iterkeys(headers)} if config.capture_body in ("all", event_type) and hasattr(response, "body"): result["body"] = response.body.decode("utf-8") return result async def set_body(request: Request, body: bytes): """Overwrites body in Starlette. Args: request (Request) body (bytes) """ async def receive() -> Message: return {"type": "http.request", "body": body} request._receive = receive async def get_body(request: Request) -> str: """Gets body from the request. todo: This is not very pretty however it is not usual to get request body out of the target method (business logic). Args: request (Request) Returns: str """ body = await request.body() await set_body(request, body) request._stream_consumed = False return body.decode("utf-8") async def query_params_to_dict(query_params: str) -> dict: """Transforms query params from URL to dictionary Args: query_params (str) Returns: dict Examples: >>> print(query_params_to_dict(b"key=val&key2=val2")) {"key": "val", "key2": "val2"} """ query_params = query_params.split("&") res = {} for param in query_params: key, val = param.split("=") res[key] = val return res def _get_client_ip(request: Request): x_forwarded_for = request.headers.get("HTTP_X_FORWARDED_FOR") if x_forwarded_for: ip = x_forwarded_for.split(",")[0] else: ip = request.headers.get("REMOTE_ADDR") return ip
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/contrib/starlette/utils.py
utils.py
from __future__ import absolute_import import starlette from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint from starlette.requests import Request from starlette.responses import Response from starlette.types import ASGIApp import zuqa import zuqa.instrumentation.control from zuqa.base import Client from zuqa.conf import constants from zuqa.contrib.asyncio.traces import set_context from zuqa.contrib.starlette.utils import get_data_from_request, get_data_from_response from zuqa.utils.disttracing import TraceParent from zuqa.utils.logging import get_logger logger = get_logger("zuqa.errors.client") def make_apm_client(config: dict, client_cls=Client, **defaults) -> Client: """Builds ZUQA client. Args: config (dict): Dictionary of Client configuration. All keys must be uppercase. See `zuqa.conf.Config`. client_cls (Client): Must be Client or its child. **defaults: Additional parameters for Client. See `zuqa.base.Client` Returns: Client """ if "framework_name" not in defaults: defaults["framework_name"] = "starlette" defaults["framework_version"] = starlette.__version__ return client_cls(config, **defaults) class ZUQA(BaseHTTPMiddleware): """ Starlette / FastAPI middleware for ZUQA capturing. >>> zuqa = make_apm_client({ >>> 'SERVICE_NAME': 'myapp', >>> 'DEBUG': True, >>> 'SERVER_URL': 'http://localhost:32140', >>> 'CAPTURE_HEADERS': True, >>> 'CAPTURE_BODY': 'all' >>> }) >>> app.add_middleware(ZUQA, client=zuqa) Pass an arbitrary APP_NAME and SECRET_TOKEN:: >>> zuqa = ZUQA(app, service_name='myapp', secret_token='asdasdasd') Pass an explicit client:: >>> zuqa = ZUQA(app, client=client) Automatically configure logging:: >>> zuqa = ZUQA(app, logging=True) Capture an exception:: >>> try: >>> 1 / 0 >>> except ZeroDivisionError: >>> zuqa.capture_exception() Capture a message:: >>> zuqa.capture_message('hello, world!') """ def __init__(self, app: ASGIApp, client: Client): """ Args: app (ASGIApp): Starlette app client (Client): ZUQA Client """ self.client = client if self.client.config.instrument: zuqa.instrumentation.control.instrument() super().__init__(app) async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response: """Processes the whole request APM capturing. Args: request (Request) call_next (RequestResponseEndpoint): Next request process in Starlette. Returns: Response """ await self._request_started(request) try: response = await call_next(request) except Exception: await self.capture_exception( context={"request": await get_data_from_request(request, self.client.config, constants.ERROR)} ) zuqa.set_transaction_result("HTTP 5xx", override=False) zuqa.set_context({"status_code": 500}, "response") raise else: await self._request_finished(response) finally: self.client.end_transaction() return response async def capture_exception(self, *args, **kwargs): """Captures your exception. Args: *args: **kwargs: """ self.client.capture_exception(*args, **kwargs) async def capture_message(self, *args, **kwargs): """Captures your message. Args: *args: Whatever **kwargs: Whatever """ self.client.capture_message(*args, **kwargs) async def _request_started(self, request: Request): """Captures the begin of the request processing to APM. Args: request (Request) """ trace_parent = TraceParent.from_headers(dict(request.headers)) self.client.begin_transaction("request", trace_parent=trace_parent) await set_context(lambda: get_data_from_request(request, self.client.config, constants.TRANSACTION), "request") zuqa.set_transaction_name("{} {}".format(request.method, request.url.path), override=False) async def _request_finished(self, response: Response): """Captures the end of the request processing to APM. Args: response (Response) """ await set_context( lambda: get_data_from_response(response, self.client.config, constants.TRANSACTION), "response" ) result = "HTTP {}xx".format(response.status_code // 100) zuqa.set_transaction_result(result, override=False)
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/contrib/starlette/__init__.py
__init__.py
import warnings from opentracing import Format, InvalidCarrierException, SpanContextCorruptedException, UnsupportedFormatException from opentracing.scope_managers import ThreadLocalScopeManager from opentracing.tracer import ReferenceType from opentracing.tracer import Tracer as TracerBase import zuqa from zuqa import instrument, traces from zuqa.conf import constants from zuqa.contrib.opentracing.span import OTSpan, OTSpanContext from zuqa.utils import compat, disttracing class Tracer(TracerBase): _zuqa_client_class = zuqa.Client def __init__(self, client_instance=None, config=None, scope_manager=None): self._agent = client_instance or self._zuqa_client_class(config=config) if scope_manager and not isinstance(scope_manager, ThreadLocalScopeManager): warnings.warn( "Currently, the ZUQA opentracing bridge only supports the ThreadLocalScopeManager. " "Usage of other scope managers will lead to unpredictable results." ) self._scope_manager = scope_manager or ThreadLocalScopeManager() if self._agent.config.instrument and self._agent.config.enabled: instrument() def start_active_span( self, operation_name, child_of=None, references=None, tags=None, start_time=None, ignore_active_span=False, finish_on_close=True, ): ot_span = self.start_span( operation_name, child_of=child_of, references=references, tags=tags, start_time=start_time, ignore_active_span=ignore_active_span, ) scope = self._scope_manager.activate(ot_span, finish_on_close) return scope def start_span( self, operation_name=None, child_of=None, references=None, tags=None, start_time=None, ignore_active_span=False ): if isinstance(child_of, OTSpanContext): parent_context = child_of elif isinstance(child_of, OTSpan): parent_context = child_of.context elif references and references[0].type == ReferenceType.CHILD_OF: parent_context = references[0].referenced_context else: parent_context = None transaction = traces.execution_context.get_transaction() if not transaction: trace_parent = parent_context.trace_parent if parent_context else None transaction = self._agent.begin_transaction("custom", trace_parent=trace_parent) transaction.name = operation_name span_context = OTSpanContext(trace_parent=transaction.trace_parent) ot_span = OTSpan(self, span_context, transaction) else: # to allow setting an explicit parent span, we check if the parent_context is set # and if it is a span. In all other cases, the parent is found implicitly through the # execution context. parent_span_id = ( parent_context.span.zuqa_ref.id if parent_context and parent_context.span and not parent_context.span.is_transaction else None ) span = transaction._begin_span(operation_name, None, parent_span_id=parent_span_id) trace_parent = parent_context.trace_parent if parent_context else transaction.trace_parent span_context = OTSpanContext(trace_parent=trace_parent.copy_from(span_id=span.id)) ot_span = OTSpan(self, span_context, span) if tags: for k, v in compat.iteritems(tags): ot_span.set_tag(k, v) return ot_span def extract(self, format, carrier): if format in (Format.HTTP_HEADERS, Format.TEXT_MAP): trace_parent = disttracing.TraceParent.from_headers(carrier) if not trace_parent: raise SpanContextCorruptedException("could not extract span context from carrier") return OTSpanContext(trace_parent=trace_parent) raise UnsupportedFormatException def inject(self, span_context, format, carrier): if format in (Format.HTTP_HEADERS, Format.TEXT_MAP): if not isinstance(carrier, dict): raise InvalidCarrierException("carrier for {} format should be dict-like".format(format)) val = span_context.trace_parent.to_ascii() carrier[constants.TRACEPARENT_HEADER_NAME] = val if self._agent.config.use_elastic_traceparent_header: carrier[constants.TRACEPARENT_LEGACY_HEADER_NAME] = val return raise UnsupportedFormatException
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/contrib/opentracing/tracer.py
tracer.py
from opentracing.span import Span as OTSpanBase from opentracing.span import SpanContext as OTSpanContextBase from zuqa import traces from zuqa.utils import compat, get_url_dict from zuqa.utils.logging import get_logger try: # opentracing-python 2.1+ from opentracing import tags from opentracing import logs as ot_logs except ImportError: # opentracing-python <2.1 from opentracing.ext import tags ot_logs = None logger = get_logger("zuqa.contrib.opentracing") class OTSpan(OTSpanBase): def __init__(self, tracer, context, zuqa_ref): super(OTSpan, self).__init__(tracer, context) self.zuqa_ref = zuqa_ref self.is_transaction = isinstance(zuqa_ref, traces.Transaction) self.is_dropped = isinstance(zuqa_ref, traces.DroppedSpan) if not context.span: context.span = self def log_kv(self, key_values, timestamp=None): exc_type, exc_val, exc_tb = None, None, None if "python.exception.type" in key_values: exc_type = key_values["python.exception.type"] exc_val = key_values.get("python.exception.val") exc_tb = key_values.get("python.exception.tb") elif ot_logs and key_values.get(ot_logs.EVENT) == tags.ERROR: exc_type = key_values[ot_logs.ERROR_KIND] exc_val = key_values.get(ot_logs.ERROR_OBJECT) exc_tb = key_values.get(ot_logs.STACK) else: logger.debug("Can't handle non-exception type opentracing logs") if exc_type: agent = self.tracer._agent agent.capture_exception(exc_info=(exc_type, exc_val, exc_tb)) return self def set_operation_name(self, operation_name): self.zuqa_ref.name = operation_name return self def set_tag(self, key, value): if self.is_transaction: if key == "type": self.zuqa_ref.transaction_type = value elif key == "result": self.zuqa_ref.result = value elif key == tags.HTTP_STATUS_CODE: self.zuqa_ref.result = "HTTP {}xx".format(compat.text_type(value)[0]) traces.set_context({"status_code": value}, "response") elif key == "user.id": traces.set_user_context(user_id=value) elif key == "user.username": traces.set_user_context(username=value) elif key == "user.email": traces.set_user_context(email=value) elif key == tags.HTTP_URL: traces.set_context({"url": get_url_dict(value)}, "request") elif key == tags.HTTP_METHOD: traces.set_context({"method": value}, "request") elif key == tags.COMPONENT: traces.set_context({"framework": {"name": value}}, "service") else: self.zuqa_ref.label(**{key: value}) elif not self.is_dropped: if key.startswith("db."): span_context = self.zuqa_ref.context or {} if "db" not in span_context: span_context["db"] = {} if key == tags.DATABASE_STATEMENT: span_context["db"]["statement"] = value elif key == tags.DATABASE_USER: span_context["db"]["user"] = value elif key == tags.DATABASE_TYPE: span_context["db"]["type"] = value self.zuqa_ref.type = "db." + value else: self.zuqa_ref.label(**{key: value}) self.zuqa_ref.context = span_context elif key == tags.SPAN_KIND: self.zuqa_ref.type = value else: self.zuqa_ref.label(**{key: value}) return self def finish(self, finish_time=None): if self.is_transaction: self.tracer._agent.end_transaction() elif not self.is_dropped: self.zuqa_ref.transaction.end_span() class OTSpanContext(OTSpanContextBase): def __init__(self, trace_parent, span=None): self.trace_parent = trace_parent self.span = span
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/contrib/opentracing/span.py
span.py
from __future__ import absolute_import import logging import sys import traceback from zuqa.base import Client from zuqa.traces import execution_context from zuqa.utils import compat, wrapt from zuqa.utils.encoding import to_unicode from zuqa.utils.stacks import iter_stack_frames class LoggingHandler(logging.Handler): def __init__(self, *args, **kwargs): client = kwargs.pop("client_cls", Client) if len(args) == 1: arg = args[0] args = args[1:] if isinstance(arg, Client): self.client = arg else: raise ValueError( "The first argument to %s must be a Client instance, " "got %r instead." % (self.__class__.__name__, arg) ) elif "client" in kwargs: self.client = kwargs.pop("client") else: self.client = client(*args, **kwargs) logging.Handler.__init__(self, level=kwargs.get("level", logging.NOTSET)) def emit(self, record): self.format(record) # Avoid typical config issues by overriding loggers behavior if record.name.startswith(("zuqa.errors",)): sys.stderr.write(to_unicode(record.message) + "\n") return try: return self._emit(record) except Exception: sys.stderr.write("Top level ZUQA exception caught - failed creating log record.\n") sys.stderr.write(to_unicode(record.msg + "\n")) sys.stderr.write(to_unicode(traceback.format_exc() + "\n")) try: self.client.capture("Exception") except Exception: pass def _emit(self, record, **kwargs): data = {} for k, v in compat.iteritems(record.__dict__): if "." not in k and k not in ("culprit",): continue data[k] = v stack = getattr(record, "stack", None) if stack is True: stack = iter_stack_frames(config=self.client.config) if stack: frames = [] started = False last_mod = "" for item in stack: if isinstance(item, (list, tuple)): frame, lineno = item else: frame, lineno = item, item.f_lineno if not started: f_globals = getattr(frame, "f_globals", {}) module_name = f_globals.get("__name__", "") if last_mod.startswith("logging") and not module_name.startswith("logging"): started = True else: last_mod = module_name continue frames.append((frame, lineno)) stack = frames custom = getattr(record, "data", {}) # Add in all of the data from the record that we aren't already capturing for k in record.__dict__.keys(): if k in ( "stack", "name", "args", "msg", "levelno", "exc_text", "exc_info", "data", "created", "levelname", "msecs", "relativeCreated", ): continue if k.startswith("_"): continue custom[k] = record.__dict__[k] # If there's no exception being processed, # exc_info may be a 3-tuple of None # http://docs.python.org/library/sys.html#sys.exc_info if record.exc_info and all(record.exc_info): handler = self.client.get_handler("zuqa.events.Exception") exception = handler.capture(self.client, exc_info=record.exc_info) else: exception = None return self.client.capture( "Message", param_message={"message": compat.text_type(record.msg), "params": record.args}, stack=stack, custom=custom, exception=exception, level=record.levelno, logger_name=record.name, **kwargs ) class LoggingFilter(logging.Filter): """ This filter doesn't actually do any "filtering" -- rather, it just adds three new attributes to any "filtered" LogRecord objects: * zuqa_transaction_id * zuqa_trace_id * zuqa_span_id These attributes can then be incorporated into your handlers and formatters, so that you can tie log messages to transactions in elasticsearch. This filter also adds these fields to a dictionary attribute, `zuqa_labels`, using the official tracing fields names as documented here: https://www.elastic.co/guide/en/ecs/current/ecs-tracing.html Note that if you're using Python 3.2+, by default we will add a LogRecordFactory to your root logger which will add these attributes automatically. """ def filter(self, record): """ Add zuqa attributes to `record`. """ _add_attributes_to_log_record(record) return True @wrapt.decorator def log_record_factory(wrapped, instance, args, kwargs): """ Decorator, designed to wrap the python log record factory (fetched by logging.getLogRecordFactory), adding the same custom attributes as in the LoggingFilter provided above. :return: LogRecord object, with custom attributes for APM tracing fields """ record = wrapped(*args, **kwargs) return _add_attributes_to_log_record(record) def _add_attributes_to_log_record(record): """ Add custom attributes for APM tracing fields to a LogRecord object :param record: LogRecord object :return: Updated LogRecord object with new APM tracing fields """ transaction = execution_context.get_transaction() transaction_id = transaction.id if transaction else None record.zuqa_transaction_id = transaction_id trace_id = transaction.trace_parent.trace_id if transaction and transaction.trace_parent else None record.zuqa_trace_id = trace_id span = execution_context.get_span() span_id = span.id if span else None record.zuqa_span_id = span_id record.zuqa_labels = {"transaction.id": transaction_id, "trace.id": trace_id, "span.id": span_id} return record class Formatter(logging.Formatter): """ Custom formatter to automatically append the zuqa format string, as well as ensure that LogRecord objects actually have the required fields (so as to avoid errors which could occur for logs before we override the LogRecordFactory): formatstring = "%(asctime)s - %(name)s - %(levelname)s - %(message)s" formatstring = formatstring + " | zuqa " \ "transaction.id=%(zuqa_transaction_id)s " \ "trace.id=%(zuqa_trace_id)s " \ "span.id=%(zuqa_span_id)s" """ def __init__(self, fmt=None, datefmt=None, style="%"): if fmt is None: fmt = "%(message)s" fmt = ( fmt + " | zuqa " "transaction.id=%(zuqa_transaction_id)s " "trace.id=%(zuqa_trace_id)s " "span.id=%(zuqa_span_id)s" ) if compat.PY3: super(Formatter, self).__init__(fmt=fmt, datefmt=datefmt, style=style) else: super(Formatter, self).__init__(fmt=fmt, datefmt=datefmt) def format(self, record): if not hasattr(record, "zuqa_transaction_id"): record.zuqa_transaction_id = None record.zuqa_trace_id = None record.zuqa_span_id = None return super(Formatter, self).format(record=record) def formatTime(self, record, datefmt=None): if not hasattr(record, "zuqa_transaction_id"): record.zuqa_transaction_id = None record.zuqa_trace_id = None record.zuqa_span_id = None return super(Formatter, self).formatTime(record=record, datefmt=datefmt)
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/handlers/logging.py
logging.py
from __future__ import absolute_import import sys import traceback import logbook from zuqa.base import Client from zuqa.utils import compat from zuqa.utils.encoding import to_unicode LOOKBOOK_LEVELS = { logbook.DEBUG: "debug", logbook.INFO: "info", logbook.NOTICE: "info", logbook.WARNING: "warning", logbook.ERROR: "error", logbook.CRITICAL: "fatal", } class LogbookHandler(logbook.Handler): def __init__(self, *args, **kwargs): if len(args) == 1: arg = args[0] # if isinstance(arg, compat.string_types): # self.client = kwargs.pop('client_cls', Client)(dsn=arg) if isinstance(arg, Client): self.client = arg else: raise ValueError( "The first argument to %s must be a Client instance, " "got %r instead." % (self.__class__.__name__, arg) ) args = [] else: try: self.client = kwargs.pop("client") except KeyError: raise TypeError("Expected keyword argument for LoggingHandler: client") super(LogbookHandler, self).__init__(*args, **kwargs) def emit(self, record): self.format(record) # Avoid typical config issues by overriding loggers behavior if record.channel.startswith("zuqa.errors"): sys.stderr.write(to_unicode(record.message + "\n")) return try: return self._emit(record) except Exception: sys.stderr.write("Top level ZUQA exception caught - failed creating log record.\n") sys.stderr.write(to_unicode(record.msg + "\n")) sys.stderr.write(to_unicode(traceback.format_exc() + "\n")) try: self.client.capture("Exception") except Exception: pass def _emit(self, record): # If there's no exception being processed, # exc_info may be a 3-tuple of None # http://docs.python.org/library/sys.html#sys.exc_info if record.exc_info is True or (record.exc_info and all(record.exc_info)): handler = self.client.get_handler("zuqa.events.Exception") exception = handler.capture(self.client, exc_info=record.exc_info) else: exception = None return self.client.capture_message( param_message={"message": compat.text_type(record.msg), "params": record.args}, exception=exception, level=LOOKBOOK_LEVELS[record.level], logger_name=record.channel, custom=record.extra, stack=record.kwargs.get("stack"), )
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/handlers/logbook.py
logbook.py
import sys from zuqa.utils.module_import import import_string _cls_register = { "zuqa.instrumentation.packages.botocore.BotocoreInstrumentation", "zuqa.instrumentation.packages.jinja2.Jinja2Instrumentation", "zuqa.instrumentation.packages.psycopg2.Psycopg2Instrumentation", "zuqa.instrumentation.packages.psycopg2.Psycopg2ExtensionsInstrumentation", "zuqa.instrumentation.packages.mysql.MySQLInstrumentation", "zuqa.instrumentation.packages.mysql_connector.MySQLConnectorInstrumentation", "zuqa.instrumentation.packages.pymysql.PyMySQLConnectorInstrumentation", "zuqa.instrumentation.packages.pylibmc.PyLibMcInstrumentation", "zuqa.instrumentation.packages.pymongo.PyMongoInstrumentation", "zuqa.instrumentation.packages.pymongo.PyMongoBulkInstrumentation", "zuqa.instrumentation.packages.pymongo.PyMongoCursorInstrumentation", "zuqa.instrumentation.packages.python_memcached.PythonMemcachedInstrumentation", "zuqa.instrumentation.packages.pymemcache.PyMemcacheInstrumentation", "zuqa.instrumentation.packages.redis.RedisInstrumentation", "zuqa.instrumentation.packages.redis.RedisPipelineInstrumentation", "zuqa.instrumentation.packages.redis.RedisConnectionInstrumentation", "zuqa.instrumentation.packages.requests.RequestsInstrumentation", "zuqa.instrumentation.packages.sqlite.SQLiteInstrumentation", "zuqa.instrumentation.packages.urllib3.Urllib3Instrumentation", "zuqa.instrumentation.packages.elasticsearch.ElasticsearchConnectionInstrumentation", "zuqa.instrumentation.packages.elasticsearch.ElasticsearchInstrumentation", "zuqa.instrumentation.packages.cassandra.CassandraInstrumentation", "zuqa.instrumentation.packages.pymssql.PyMSSQLInstrumentation", "zuqa.instrumentation.packages.pyodbc.PyODBCInstrumentation", "zuqa.instrumentation.packages.django.template.DjangoTemplateInstrumentation", "zuqa.instrumentation.packages.django.template.DjangoTemplateSourceInstrumentation", "zuqa.instrumentation.packages.urllib.UrllibInstrumentation", } if sys.version_info >= (3, 5): _cls_register.update( [ "zuqa.instrumentation.packages.asyncio.sleep.AsyncIOSleepInstrumentation", "zuqa.instrumentation.packages.asyncio.aiohttp_client.AioHttpClientInstrumentation", "zuqa.instrumentation.packages.asyncio.elasticsearch.ElasticSearchAsyncConnection", "zuqa.instrumentation.packages.asyncio.aiopg.AioPGInstrumentation", "zuqa.instrumentation.packages.tornado.TornadoRequestExecuteInstrumentation", "zuqa.instrumentation.packages.tornado.TornadoHandleRequestExceptionInstrumentation", "zuqa.instrumentation.packages.tornado.TornadoRenderInstrumentation", ] ) def register(cls): _cls_register.add(cls) _instrumentation_singletons = {} def get_instrumentation_objects(): for cls_str in _cls_register: if cls_str not in _instrumentation_singletons: cls = import_string(cls_str) _instrumentation_singletons[cls_str] = cls() obj = _instrumentation_singletons[cls_str] yield obj
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/instrumentation/register.py
register.py
import zuqa from zuqa.conf import constants from zuqa.instrumentation.packages.asyncio.base import AbstractInstrumentedModule, AsyncAbstractInstrumentedModule from zuqa.traces import capture_span from zuqa.utils.disttracing import TraceParent class TornadoRequestExecuteInstrumentation(AsyncAbstractInstrumentedModule): name = "tornado_request_execute" creates_transactions = True instrument_list = [("tornado.web", "RequestHandler._execute")] async def call(self, module, method, wrapped, instance, args, kwargs): if not hasattr(instance.application, "zuqa_client"): # If tornado was instrumented but not as the main framework # (i.e. in Flower), we should skip it. return await wrapped(*args, **kwargs) # Late import to avoid ImportErrors from zuqa.contrib.tornado.utils import get_data_from_request, get_data_from_response request = instance.request trace_parent = TraceParent.from_headers(request.headers) client = instance.application.zuqa_client client.begin_transaction("request", trace_parent=trace_parent) zuqa.set_context( lambda: get_data_from_request(instance, request, client.config, constants.TRANSACTION), "request" ) # TODO: Can we somehow incorporate the routing rule itself here? zuqa.set_transaction_name("{} {}".format(request.method, type(instance).__name__), override=False) ret = await wrapped(*args, **kwargs) zuqa.set_context( lambda: get_data_from_response(instance, client.config, constants.TRANSACTION), "response" ) result = "HTTP {}xx".format(instance.get_status() // 100) zuqa.set_transaction_result(result, override=False) client.end_transaction() return ret class TornadoHandleRequestExceptionInstrumentation(AbstractInstrumentedModule): name = "tornado_handle_request_exception" instrument_list = [("tornado.web", "RequestHandler._handle_request_exception")] def call(self, module, method, wrapped, instance, args, kwargs): if not hasattr(instance.application, "zuqa_client"): # If tornado was instrumented but not as the main framework # (i.e. in Flower), we should skip it. return wrapped(*args, **kwargs) # Late import to avoid ImportErrors from tornado.web import Finish, HTTPError from zuqa.contrib.tornado.utils import get_data_from_request e = args[0] if isinstance(e, Finish): # Not an error; Finish is an exception that ends a request without an error response return wrapped(*args, **kwargs) client = instance.application.zuqa_client request = instance.request client.capture_exception( context={"request": get_data_from_request(instance, request, client.config, constants.ERROR)} ) if isinstance(e, HTTPError): zuqa.set_transaction_result("HTTP {}xx".format(int(e.status_code / 100)), override=False) zuqa.set_context({"status_code": e.status_code}, "response") else: zuqa.set_transaction_result("HTTP 5xx", override=False) zuqa.set_context({"status_code": 500}, "response") return wrapped(*args, **kwargs) class TornadoRenderInstrumentation(AbstractInstrumentedModule): name = "tornado_render" instrument_list = [("tornado.web", "RequestHandler.render")] def call(self, module, method, wrapped, instance, args, kwargs): if "template_name" in kwargs: name = kwargs["template_name"] else: name = args[0] with capture_span(name, span_type="template", span_subtype="tornado", span_action="render"): return wrapped(*args, **kwargs)
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/instrumentation/packages/tornado.py
tornado.py
from zuqa.instrumentation.packages.base import AbstractInstrumentedModule from zuqa.instrumentation.packages.dbapi2 import extract_signature from zuqa.traces import capture_span from zuqa.utils import compat class CassandraInstrumentation(AbstractInstrumentedModule): name = "cassandra" instrument_list = [("cassandra.cluster", "Session.execute"), ("cassandra.cluster", "Cluster.connect")] def call(self, module, method, wrapped, instance, args, kwargs): name = self.get_wrapped_name(wrapped, instance, method) context = {} if method == "Cluster.connect": span_action = "connect" if hasattr(instance, "contact_points_resolved"): # < cassandra-driver 3.18 host = instance.contact_points_resolved[0] port = instance.port else: host = instance.endpoints_resolved[0].address port = instance.endpoints_resolved[0].port else: hosts = list(instance.hosts) if hasattr(hosts[0], "endpoint"): host = hosts[0].endpoint.address port = hosts[0].endpoint.port else: # < cassandra-driver 3.18 host = hosts[0].address port = instance.cluster.port span_action = "query" query = args[0] if args else kwargs.get("query") if hasattr(query, "query_string"): query_str = query.query_string elif hasattr(query, "prepared_statement") and hasattr(query.prepared_statement, "query"): query_str = query.prepared_statement.query elif isinstance(query, compat.string_types): query_str = query else: query_str = None if query_str: name = extract_signature(query_str) context["db"] = {"type": "sql", "statement": query_str} context["destination"] = { "address": host, "port": port, "service": {"name": "cassandra", "resource": "cassandra", "type": "db"}, } with capture_span(name, span_type="db", span_subtype="cassandra", span_action=span_action, extra=context): return wrapped(*args, **kwargs)
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/instrumentation/packages/cassandra.py
cassandra.py
from __future__ import absolute_import from zuqa.instrumentation.packages.base import AbstractInstrumentedModule from zuqa.traces import capture_span, execution_context class Redis3CheckMixin(object): instrument_list_3 = [] instrument_list = [] def get_instrument_list(self): try: from redis import VERSION if VERSION[0] >= 3: return self.instrument_list_3 return self.instrument_list except ImportError: return self.instrument_list class RedisInstrumentation(Redis3CheckMixin, AbstractInstrumentedModule): name = "redis" # no need to instrument StrictRedis in redis-py >= 3.0 instrument_list_3 = [("redis.client", "Redis.execute_command")] instrument_list = [("redis.client", "Redis.execute_command"), ("redis.client", "StrictRedis.execute_command")] def call(self, module, method, wrapped, instance, args, kwargs): if len(args) > 0: wrapped_name = str(args[0]) else: wrapped_name = self.get_wrapped_name(wrapped, instance, method) with capture_span(wrapped_name, span_type="db", span_subtype="redis", span_action="query", leaf=True): return wrapped(*args, **kwargs) class RedisPipelineInstrumentation(Redis3CheckMixin, AbstractInstrumentedModule): name = "redis" # BasePipeline has been renamed to Pipeline in redis-py 3 instrument_list_3 = [("redis.client", "Pipeline.execute")] instrument_list = [("redis.client", "BasePipeline.execute")] def call(self, module, method, wrapped, instance, args, kwargs): wrapped_name = self.get_wrapped_name(wrapped, instance, method) with capture_span(wrapped_name, span_type="db", span_subtype="redis", span_action="query", leaf=True): return wrapped(*args, **kwargs) class RedisConnectionInstrumentation(AbstractInstrumentedModule): name = "redis" instrument_list = (("redis.connection", "Connection.send_packed_command"),) def call(self, module, method, wrapped, instance, args, kwargs): span = execution_context.get_span() if span and span.subtype == "redis": span.context["destination"] = get_destination_info(instance) return wrapped(*args, **kwargs) def get_destination_info(connection): destination_info = {"service": {"name": "redis", "resource": "redis", "type": "db"}} if hasattr(connection, "port"): destination_info["port"] = connection.port destination_info["address"] = connection.host elif hasattr(connection, "path"): destination_info["port"] = None destination_info["address"] = "unix://" + connection.path return destination_info
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/instrumentation/packages/redis.py
redis.py
from __future__ import absolute_import import json import zuqa from zuqa.instrumentation.packages.base import AbstractInstrumentedModule from zuqa.utils import compat from zuqa.utils.logging import get_logger logger = get_logger("zuqa.instrument") API_METHOD_KEY_NAME = "__zuqa_api_method_name" BODY_REF_NAME = "__zuqa_body_ref" class ElasticSearchConnectionMixin(object): query_methods = ("Elasticsearch.search", "Elasticsearch.count", "Elasticsearch.delete_by_query") def get_signature(self, args, kwargs): args_len = len(args) http_method = args[0] if args_len else kwargs.get("method") http_path = args[1] if args_len > 1 else kwargs.get("url") return "ES %s %s" % (http_method, http_path) def get_context(self, instance, args, kwargs): args_len = len(args) params = args[2] if args_len > 2 else kwargs.get("params") body = params.pop(BODY_REF_NAME, None) if params else None api_method = params.pop(API_METHOD_KEY_NAME, None) if params else None context = {"db": {"type": "elasticsearch"}} if api_method in self.query_methods: query = [] # using both q AND body is allowed in some API endpoints / ES versions, # but not in others. We simply capture both if they are there so the # user can see it. if params and "q" in params: # 'q' is already encoded to a byte string at this point # we assume utf8, which is the default query.append("q=" + params["q"].decode("utf-8", errors="replace")) if isinstance(body, dict) and "query" in body: query.append(json.dumps(body["query"], default=compat.text_type)) if query: context["db"]["statement"] = "\n\n".join(query) elif api_method == "Elasticsearch.update": if isinstance(body, dict) and "script" in body: # only get the `script` field from the body context["db"]["statement"] = json.dumps({"script": body["script"]}) context["destination"] = { "address": instance.host, "service": {"name": "elasticsearch", "resource": "elasticsearch", "type": "db"}, } return context class ElasticsearchConnectionInstrumentation(ElasticSearchConnectionMixin, AbstractInstrumentedModule): name = "elasticsearch_connection" instrument_list = [ ("elasticsearch.connection.http_urllib3", "Urllib3HttpConnection.perform_request"), ("elasticsearch.connection.http_requests", "RequestsHttpConnection.perform_request"), ] def call(self, module, method, wrapped, instance, args, kwargs): signature = self.get_signature(args, kwargs) context = self.get_context(instance, args, kwargs) with zuqa.capture_span( signature, span_type="db", span_subtype="elasticsearch", span_action="query", extra=context, skip_frames=2, leaf=True, ): return wrapped(*args, **kwargs) class ElasticsearchInstrumentation(AbstractInstrumentedModule): name = "elasticsearch" instrument_list = [ ("elasticsearch.client", "Elasticsearch.delete_by_query"), ("elasticsearch.client", "Elasticsearch.search"), ("elasticsearch.client", "Elasticsearch.count"), ("elasticsearch.client", "Elasticsearch.update"), ] def __init__(self): super(ElasticsearchInstrumentation, self).__init__() try: from elasticsearch import VERSION self.version = VERSION[0] except ImportError: self.version = None def instrument(self): if self.version and not 2 <= self.version < 8: logger.debug("Instrumenting version %s of Elasticsearch is not supported by ZUQA", self.version) return super(ElasticsearchInstrumentation, self).instrument() def call(self, module, method, wrapped, instance, args, kwargs): params = kwargs.pop("params", {}) # make a copy of params in case the caller reuses them for some reason params = params.copy() if params is not None else {} cls_name, method_name = method.split(".", 1) # store a reference to the non-serialized body so we can use it in the connection layer body = kwargs.get("body") params[BODY_REF_NAME] = body params[API_METHOD_KEY_NAME] = method kwargs["params"] = params return wrapped(*args, **kwargs)
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/instrumentation/packages/elasticsearch.py
elasticsearch.py
import functools import os from zuqa.traces import execution_context from zuqa.utils import wrapt from zuqa.utils.logging import get_logger logger = get_logger("zuqa.instrument") class ZuqaFunctionWrapper(wrapt.FunctionWrapper): # used to differentiate between our own function wrappers and 1st/3rd party wrappers pass class AbstractInstrumentedModule(object): """ This class is designed to reduce the amount of code required to instrument library functions using wrapt. Instrumentation modules inherit from this class and override pieces as needed. Only `name`, `instrumented_list`, and `call` are required in the inheriting class. The `instrument_list` is a list of (module, method) pairs that will be instrumented. The module/method need not be imported -- in fact, because instrumentation modules are all processed during the instrumentation process, lazy imports should be used in order to avoid ImportError exceptions. The `instrument()` method will be called for each InstrumentedModule listed in the instrument register (zuqa.instrumentation.register), and each method in the `instrument_list` will be wrapped (using wrapt) with the `call_if_sampling()` function, which (by default) will either call the wrapped function by itself, or pass it into `call()` to be called if there is a transaction active. For simple span-wrapping of instrumented libraries, a very simple InstrumentedModule might look like this:: from zuqa.instrumentation.packages.base import AbstractInstrumentedModule from zuqa.traces import capture_span class Jinja2Instrumentation(AbstractInstrumentedModule): name = "jinja2" instrument_list = [("jinja2", "Template.render")] def call(self, module, method, wrapped, instance, args, kwargs): signature = instance.name or instance.filename with capture_span(signature, span_type="template", span_subtype="jinja2", span_action="render"): return wrapped(*args, **kwargs) This class can also be used to instrument callables which are expected to create their own transactions (rather than spans within a transaction). In this case, set `creates_transaction = True` next to your `name` and `instrument_list`. This tells the instrumenting code to always wrap the method with `call()`, even if there is no transaction active. It is expected in this case that a new transaction will be created as part of your `call()` method. """ name = None mutates_unsampled_arguments = False creates_transactions = False instrument_list = [ # List of (module, method) pairs to instrument. E.g.: # ("requests.sessions", "Session.send"), ] def __init__(self): self.originals = {} self.instrumented = False assert self.name is not None def get_wrapped_name(self, wrapped, instance, fallback_method=None): wrapped_name = [] if hasattr(instance, "__class__") and hasattr(instance.__class__, "__name__"): wrapped_name.append(instance.__class__.__name__) if hasattr(wrapped, "__name__"): wrapped_name.append(wrapped.__name__) elif fallback_method: attribute = fallback_method.split(".") if len(attribute) == 2: wrapped_name.append(attribute[1]) return ".".join(wrapped_name) def get_instrument_list(self): return self.instrument_list def instrument(self): if self.instrumented: return skip_env_var = "SKIP_INSTRUMENT_" + str(self.name.upper()) if skip_env_var in os.environ: logger.debug("Skipping instrumentation of %s. %s is set.", self.name, skip_env_var) return try: instrument_list = self.get_instrument_list() skipped_modules = set() instrumented_methods = [] for module, method in instrument_list: try: # Skip modules we already failed to load if module in skipped_modules: continue # We jump through hoop here to get the original # `module`/`method` in the call to `call_if_sampling` parent, attribute, original = wrapt.resolve_path(module, method) if isinstance(original, ZuqaFunctionWrapper): logger.debug("%s.%s already instrumented, skipping", module, method) continue self.originals[(module, method)] = original wrapper = ZuqaFunctionWrapper( original, functools.partial(self.call_if_sampling, module, method) ) wrapt.apply_patch(parent, attribute, wrapper) instrumented_methods.append((module, method)) except ImportError: # Could not import module logger.debug("Skipping instrumentation of %s. Module %s not found", self.name, module) # Keep track of modules we couldn't load so we don't # try to instrument anything in that module again skipped_modules.add(module) except AttributeError as ex: # Could not find thing in module logger.debug("Skipping instrumentation of %s.%s: %s", module, method, ex) if instrumented_methods: logger.debug("Instrumented %s, %s", self.name, ", ".join(".".join(m) for m in instrumented_methods)) except ImportError as ex: logger.debug("Skipping instrumentation of %s. %s", self.name, ex) self.instrumented = True def uninstrument(self): if not self.instrumented or not self.originals: return uninstrumented_methods = [] for module, method in self.get_instrument_list(): if (module, method) in self.originals: parent, attribute, wrapper = wrapt.resolve_path(module, method) wrapt.apply_patch(parent, attribute, self.originals[(module, method)]) uninstrumented_methods.append((module, method)) if uninstrumented_methods: logger.debug("Uninstrumented %s, %s", self.name, ", ".join(".".join(m) for m in uninstrumented_methods)) self.instrumented = False self.originals = {} def call_if_sampling(self, module, method, wrapped, instance, args, kwargs): """ This is the function which will wrap the instrumented method/function. By default, will call the instrumented method/function, via `call()`, only if a transaction is active and sampled. This behavior can be overridden by setting `creates_transactions = True` at the class level. If `creates_transactions == False` and there's an active transaction with `transaction.is_sampled == False`, then the `mutate_unsampled_call_args()` method is called, and the resulting args and kwargs are passed into the wrapped function directly, not via `call()`. This can e.g. be used to add traceparent headers to the underlying http call for HTTP instrumentations, even if we're not sampling the transaction. """ if self.creates_transactions: return self.call(module, method, wrapped, instance, args, kwargs) transaction = execution_context.get_transaction() if not transaction: return wrapped(*args, **kwargs) elif not transaction.is_sampled: args, kwargs = self.mutate_unsampled_call_args(module, method, wrapped, instance, args, kwargs, transaction) return wrapped(*args, **kwargs) else: return self.call(module, method, wrapped, instance, args, kwargs) def mutate_unsampled_call_args(self, module, method, wrapped, instance, args, kwargs, transaction): """ Method called for unsampled wrapped calls. This can e.g. be used to add traceparent headers to the underlying http call for HTTP instrumentations. :param module: :param method: :param wrapped: :param instance: :param args: :param kwargs: :param transaction: :return: """ return args, kwargs def call(self, module, method, wrapped, instance, args, kwargs): """ Wrapped call. This method should gather all necessary data, then call `wrapped` in a `capture_span` context manager. Note that by default this wrapper will only be used if a transaction is currently active. If you want the ability to create a transaction in your `call()` method, set `create_transactions = True` at the class level. :param module: Name of the wrapped module :param method: Name of the wrapped method/function :param wrapped: the wrapped method/function object :param instance: the wrapped instance :param args: arguments to the wrapped method/function :param kwargs: keyword arguments to the wrapped method/function :return: the result of calling the wrapped method/function """ raise NotImplementedError
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/instrumentation/packages/base.py
base.py
from zuqa.instrumentation.packages.base import AbstractInstrumentedModule from zuqa.traces import capture_span class PyMemcacheInstrumentation(AbstractInstrumentedModule): name = "pymemcache" method_list = [ "add", "append", "cas", "decr", "delete", "delete_many", "delete_multi", "flush_all", "get", "get_many", "get_multi", "gets", "gets_many", "incr", "prepend", "quit", "replace", "set", "set_many", "set_multi", "stats", "touch", ] def get_instrument_list(self): return ( [("pymemcache.client.base", "Client." + method) for method in self.method_list] + [("pymemcache.client.base", "PooledClient." + method) for method in self.method_list] + [("pymemcache.client.hash", "HashClient." + method) for method in self.method_list] ) def call(self, module, method, wrapped, instance, args, kwargs): name = self.get_wrapped_name(wrapped, instance, method) # Since HashClient uses Client/PooledClient for the actual calls, we # don't need to get address/port info for that class address, port = None, None if getattr(instance, "server", None): if isinstance(instance.server, (list, tuple)): # Address/port are a tuple address, port = instance.server else: # Server is a UNIX domain socket address = instance.server destination = { "address": address, "port": port, "service": {"name": "memcached", "resource": "memcached", "type": "cache"}, } if "PooledClient" in name: # PooledClient calls out to Client for the "work", but only once, # so we don't care about the "duplicate" spans from Client in that # case with capture_span( name, span_type="cache", span_subtype="memcached", span_action="query", extra={"destination": destination}, leaf=True, ): return wrapped(*args, **kwargs) else: with capture_span( name, span_type="cache", span_subtype="memcached", span_action="query", extra={"destination": destination}, ): return wrapped(*args, **kwargs)
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/instrumentation/packages/pymemcache.py
pymemcache.py
import re from zuqa.instrumentation.packages.base import AbstractInstrumentedModule from zuqa.traces import capture_span from zuqa.utils import compat, wrapt from zuqa.utils.encoding import force_text class Literal(object): def __init__(self, literal_type, content): self.literal_type = literal_type self.content = content def __eq__(self, other): return isinstance(other, Literal) and self.literal_type == other.literal_type and self.content == other.content def __repr__(self): return "<Literal {}{}{}>".format(self.literal_type, self.content, self.literal_type) def skip_to(start, tokens, value_sequence): i = start while i < len(tokens): for idx, token in enumerate(value_sequence): if tokens[i + idx] != token: break else: # Match return tokens[start : i + len(value_sequence)] i += 1 # Not found return None def look_for_table(sql, keyword): tokens = tokenize(sql) table_name = _scan_for_table_with_tokens(tokens, keyword) if isinstance(table_name, Literal): table_name = table_name.content.strip(table_name.literal_type) return table_name def _scan_for_table_with_tokens(tokens, keyword): seen_keyword = False for idx, lexeme in scan(tokens): if seen_keyword: if lexeme == "(": return _scan_for_table_with_tokens(tokens[idx:], keyword) else: return lexeme if isinstance(lexeme, compat.string_types) and lexeme.upper() == keyword: seen_keyword = True def tokenize(sql): # split on anything that is not a word character, excluding dots return [t for t in re.split(r"([^\w.])", sql) if t != ""] def scan(tokens): literal_start_idx = None literal_started = None prev_was_escape = False lexeme = [] i = 0 while i < len(tokens): token = tokens[i] if literal_start_idx: if prev_was_escape: prev_was_escape = False lexeme.append(token) else: if token == literal_started: if literal_started == "'" and len(tokens) > i + 1 and tokens[i + 1] == "'": # double quotes i += 1 lexeme.append("'") else: yield i, Literal(literal_started, "".join(lexeme)) literal_start_idx = None literal_started = None lexeme = [] else: if token == "\\": prev_was_escape = token else: prev_was_escape = False lexeme.append(token) elif literal_start_idx is None: if token in ["'", '"', "`"]: literal_start_idx = i literal_started = token elif token == "$": # Postgres can use arbitrary characters between two $'s as a # literal separation token, e.g.: $fish$ literal $fish$ # This part will detect that and skip over the literal. skipped_token = skip_to(i + 1, tokens, "$") if skipped_token is not None: dollar_token = ["$"] + skipped_token skipped = skip_to(i + len(dollar_token), tokens, dollar_token) if skipped: # end wasn't found. yield i, Literal("".join(dollar_token), "".join(skipped[: -len(dollar_token)])) i = i + len(skipped) + len(dollar_token) else: if token != " ": yield i, token i += 1 if lexeme: yield i, lexeme def extract_signature(sql): """ Extracts a minimal signature from a given SQL query :param sql: the SQL statement :return: a string representing the signature """ sql = force_text(sql) sql = sql.strip() first_space = sql.find(" ") if first_space < 0: return sql second_space = sql.find(" ", first_space + 1) sql_type = sql[0:first_space].upper() if sql_type in ["INSERT", "DELETE"]: keyword = "INTO" if sql_type == "INSERT" else "FROM" sql_type = sql_type + " " + keyword table_name = look_for_table(sql, keyword) elif sql_type in ["CREATE", "DROP"]: # 2nd word is part of SQL type sql_type = sql_type + sql[first_space:second_space] table_name = "" elif sql_type == "UPDATE": table_name = look_for_table(sql, "UPDATE") elif sql_type == "SELECT": # Name is first table try: sql_type = "SELECT FROM" table_name = look_for_table(sql, "FROM") except Exception: table_name = "" else: # No name table_name = "" signature = " ".join(filter(bool, [sql_type, table_name])) return signature QUERY_ACTION = "query" EXEC_ACTION = "exec" class CursorProxy(wrapt.ObjectProxy): provider_name = None DML_QUERIES = ("INSERT", "DELETE", "UPDATE") def __init__(self, wrapped, destination_info=None): super(CursorProxy, self).__init__(wrapped) self._self_destination_info = destination_info def callproc(self, procname, params=None): return self._trace_sql(self.__wrapped__.callproc, procname, params, action=EXEC_ACTION) def execute(self, sql, params=None): return self._trace_sql(self.__wrapped__.execute, sql, params) def executemany(self, sql, param_list): return self._trace_sql(self.__wrapped__.executemany, sql, param_list) def _bake_sql(self, sql): """ Method to turn the "sql" argument into a string. Most database backends simply return the given object, as it is already a string """ return sql def _trace_sql(self, method, sql, params, action=QUERY_ACTION): sql_string = self._bake_sql(sql) if action == EXEC_ACTION: signature = sql_string + "()" else: signature = self.extract_signature(sql_string) with capture_span( signature, span_type="db", span_subtype=self.provider_name, span_action=action, extra={"db": {"type": "sql", "statement": sql_string}, "destination": self._self_destination_info}, skip_frames=1, ) as span: if params is None: result = method(sql) else: result = method(sql, params) # store "rows affected", but only for DML queries like insert/update/delete if span and self.rowcount not in (-1, None) and signature.startswith(self.DML_QUERIES): span.update_context("db", {"rows_affected": self.rowcount}) return result def extract_signature(self, sql): raise NotImplementedError() class ConnectionProxy(wrapt.ObjectProxy): cursor_proxy = CursorProxy def __init__(self, wrapped, destination_info=None): super(ConnectionProxy, self).__init__(wrapped) self._self_destination_info = destination_info def cursor(self, *args, **kwargs): return self.cursor_proxy(self.__wrapped__.cursor(*args, **kwargs), self._self_destination_info) class DbApi2Instrumentation(AbstractInstrumentedModule): connect_method = None def call(self, module, method, wrapped, instance, args, kwargs): return ConnectionProxy(wrapped(*args, **kwargs)) def call_if_sampling(self, module, method, wrapped, instance, args, kwargs): # Contrasting to the superclass implementation, we *always* want to # return a proxied connection, even if there is no ongoing zuqa # transaction yet. This ensures that we instrument the cursor once # the transaction started. return self.call(module, method, wrapped, instance, args, kwargs)
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/instrumentation/packages/dbapi2.py
dbapi2.py
from zuqa.conf import constants from zuqa.instrumentation.packages.base import AbstractInstrumentedModule from zuqa.traces import DroppedSpan, capture_span, execution_context from zuqa.utils import default_ports, url_to_destination from zuqa.utils.disttracing import TracingOptions class Urllib3Instrumentation(AbstractInstrumentedModule): name = "urllib3" instrument_list = [ ("urllib3.connectionpool", "HTTPConnectionPool.urlopen"), # packages that vendor or vendored urllib3 in the past ("requests.packages.urllib3.connectionpool", "HTTPConnectionPool.urlopen"), ("botocore.vendored.requests.packages.urllib3.connectionpool", "HTTPConnectionPool.urlopen"), ] def call(self, module, method, wrapped, instance, args, kwargs): if "method" in kwargs: method = kwargs["method"] else: method = args[0] headers = None if "headers" in kwargs: headers = kwargs["headers"] if headers is None: headers = {} kwargs["headers"] = headers host = instance.host if instance.port != default_ports.get(instance.scheme): host += ":" + str(instance.port) if "url" in kwargs: url = kwargs["url"] else: url = args[1] signature = method.upper() + " " + host url = "%s://%s%s" % (instance.scheme, host, url) destination = url_to_destination(url) transaction = execution_context.get_transaction() with capture_span( signature, span_type="external", span_subtype="http", extra={"http": {"url": url}, "destination": destination}, leaf=True, ) as span: # if urllib3 has been called in a leaf span, this span might be a DroppedSpan. leaf_span = span while isinstance(leaf_span, DroppedSpan): leaf_span = leaf_span.parent if headers is not None: # It's possible that there are only dropped spans, e.g. if we started dropping spans. # In this case, the transaction.id is used parent_id = leaf_span.id if leaf_span else transaction.id trace_parent = transaction.trace_parent.copy_from( span_id=parent_id, trace_options=TracingOptions(recorded=True) ) self._set_disttracing_headers(headers, trace_parent, transaction) return wrapped(*args, **kwargs) def mutate_unsampled_call_args(self, module, method, wrapped, instance, args, kwargs, transaction): # since we don't have a span, we set the span id to the transaction id trace_parent = transaction.trace_parent.copy_from( span_id=transaction.id, trace_options=TracingOptions(recorded=False) ) if "headers" in kwargs: headers = kwargs["headers"] if headers is None: headers = {} kwargs["headers"] = headers self._set_disttracing_headers(headers, trace_parent, transaction) return args, kwargs def _set_disttracing_headers(self, headers, trace_parent, transaction): trace_parent_str = trace_parent.to_string() headers[constants.TRACEPARENT_HEADER_NAME] = trace_parent_str if transaction.tracer.config.use_elastic_traceparent_header: headers[constants.TRACEPARENT_LEGACY_HEADER_NAME] = trace_parent_str if trace_parent.tracestate: headers[constants.TRACESTATE_HEADER_NAME] = trace_parent.tracestate
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/instrumentation/packages/urllib3.py
urllib3.py
from zuqa.instrumentation.packages.dbapi2 import ( ConnectionProxy, CursorProxy, DbApi2Instrumentation, extract_signature, ) from zuqa.traces import capture_span from zuqa.utils import compat, default_ports class PGCursorProxy(CursorProxy): provider_name = "postgresql" def _bake_sql(self, sql): # if this is a Composable object, use its `as_string` method # see http://initd.org/psycopg/docs/sql.html if hasattr(sql, "as_string"): return sql.as_string(self.__wrapped__) return sql def extract_signature(self, sql): return extract_signature(sql) def __enter__(self): return PGCursorProxy(self.__wrapped__.__enter__(), destination_info=self._self_destination_info) class PGConnectionProxy(ConnectionProxy): cursor_proxy = PGCursorProxy def __enter__(self): return PGConnectionProxy(self.__wrapped__.__enter__(), destination_info=self._self_destination_info) class Psycopg2Instrumentation(DbApi2Instrumentation): name = "psycopg2" instrument_list = [("psycopg2", "connect")] def call(self, module, method, wrapped, instance, args, kwargs): signature = "psycopg2.connect" host = kwargs.get("host") if host: signature += " " + compat.text_type(host) port = kwargs.get("port") if port: port = str(port) if int(port) != default_ports.get("postgresql"): host += ":" + port signature += " " + compat.text_type(host) else: # Parse connection string and extract host/port pass destination_info = { "address": kwargs.get("host", "localhost"), "port": int(kwargs.get("port", default_ports.get("postgresql"))), "service": {"name": "postgresql", "resource": "postgresql", "type": "db"}, } with capture_span( signature, span_type="db", span_subtype="postgresql", span_action="connect", extra={"destination": destination_info}, ): return PGConnectionProxy(wrapped(*args, **kwargs), destination_info=destination_info) class Psycopg2ExtensionsInstrumentation(DbApi2Instrumentation): """ Some extensions do a type check on the Connection/Cursor in C-code, which our proxy fails. For these extensions, we need to ensure that the unwrapped Connection/Cursor is passed. """ name = "psycopg2" instrument_list = [ ("psycopg2.extensions", "register_type"), # specifically instrument `register_json` as it bypasses `register_type` ("psycopg2._json", "register_json"), ("psycopg2.extensions", "quote_ident"), ("psycopg2.extensions", "encrypt_password"), ] def call(self, module, method, wrapped, instance, args, kwargs): if "conn_or_curs" in kwargs and hasattr(kwargs["conn_or_curs"], "__wrapped__"): kwargs["conn_or_curs"] = kwargs["conn_or_curs"].__wrapped__ # register_type takes the connection as second argument elif len(args) == 2 and hasattr(args[1], "__wrapped__"): args = (args[0], args[1].__wrapped__) # register_json takes the connection as first argument, and can have # several more arguments elif method == "register_json": if args and hasattr(args[0], "__wrapped__"): args = (args[0].__wrapped__,) + args[1:] elif method == "encrypt_password": # connection/cursor is either 3rd argument, or "scope" keyword argument if len(args) >= 3 and hasattr(args[2], "__wrapped__"): args = args[:2] + (args[2].__wrapped__,) + args[3:] elif "scope" in kwargs and hasattr(kwargs["scope"], "__wrapped__"): kwargs["scope"] = kwargs["scope"].__wrapped__ return wrapped(*args, **kwargs)
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/instrumentation/packages/psycopg2.py
psycopg2.py
from zuqa.conf import constants from zuqa.instrumentation.packages.base import AbstractInstrumentedModule from zuqa.traces import DroppedSpan, capture_span, execution_context from zuqa.utils import compat, default_ports, sanitize_url, url_to_destination from zuqa.utils.disttracing import TracingOptions # copied and adapted from urllib.request def request_host(request): """Return request-host, as defined by RFC 2965. Variation from RFC: returned value is lowercased, for convenient comparison. """ url = request.get_full_url() parse_result = compat.urlparse.urlparse(url) scheme, host, port = parse_result.scheme, parse_result.hostname, parse_result.port try: port = int(port) except (ValueError, TypeError): pass if host == "": host = request.get_header("Host", "") if port and port != default_ports.get(scheme): host = "%s:%s" % (host, port) return host class UrllibInstrumentation(AbstractInstrumentedModule): name = "urllib" if compat.PY2: instrument_list = [("urllib2", "AbstractHTTPHandler.do_open")] else: instrument_list = [("urllib.request", "AbstractHTTPHandler.do_open")] def call(self, module, method, wrapped, instance, args, kwargs): request_object = args[1] if len(args) > 1 else kwargs["req"] method = request_object.get_method() host = request_host(request_object) url = sanitize_url(request_object.get_full_url()) destination = url_to_destination(url) signature = method.upper() + " " + host transaction = execution_context.get_transaction() with capture_span( signature, span_type="external", span_subtype="http", extra={"http": {"url": url}, "destination": destination}, leaf=True, ) as span: # if urllib has been called in a leaf span, this span might be a DroppedSpan. leaf_span = span while isinstance(leaf_span, DroppedSpan): leaf_span = leaf_span.parent parent_id = leaf_span.id if leaf_span else transaction.id trace_parent = transaction.trace_parent.copy_from( span_id=parent_id, trace_options=TracingOptions(recorded=True) ) self._set_disttracing_headers(request_object, trace_parent, transaction) return wrapped(*args, **kwargs) def mutate_unsampled_call_args(self, module, method, wrapped, instance, args, kwargs, transaction): request_object = args[1] if len(args) > 1 else kwargs["req"] # since we don't have a span, we set the span id to the transaction id trace_parent = transaction.trace_parent.copy_from( span_id=transaction.id, trace_options=TracingOptions(recorded=False) ) self._set_disttracing_headers(request_object, trace_parent, transaction) return args, kwargs def _set_disttracing_headers(self, request_object, trace_parent, transaction): trace_parent_str = trace_parent.to_string() request_object.add_header(constants.TRACEPARENT_HEADER_NAME, trace_parent_str) if transaction.tracer.config.use_elastic_traceparent_header: request_object.add_header(constants.TRACEPARENT_LEGACY_HEADER_NAME, trace_parent_str) if trace_parent.tracestate: request_object.add_header(constants.TRACESTATE_HEADER_NAME, trace_parent.tracestate)
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/instrumentation/packages/urllib.py
urllib.py
from zuqa.instrumentation.packages.base import AbstractInstrumentedModule from zuqa.traces import capture_span class PyMongoInstrumentation(AbstractInstrumentedModule): name = "pymongo" instrument_list = [ ("pymongo.collection", "Collection.aggregate"), ("pymongo.collection", "Collection.bulk_write"), ("pymongo.collection", "Collection.count"), ("pymongo.collection", "Collection.create_index"), ("pymongo.collection", "Collection.create_indexes"), ("pymongo.collection", "Collection.delete_many"), ("pymongo.collection", "Collection.delete_one"), ("pymongo.collection", "Collection.distinct"), ("pymongo.collection", "Collection.drop"), ("pymongo.collection", "Collection.drop_index"), ("pymongo.collection", "Collection.drop_indexes"), ("pymongo.collection", "Collection.ensure_index"), ("pymongo.collection", "Collection.find_and_modify"), ("pymongo.collection", "Collection.find_one"), ("pymongo.collection", "Collection.find_one_and_delete"), ("pymongo.collection", "Collection.find_one_and_replace"), ("pymongo.collection", "Collection.find_one_and_update"), ("pymongo.collection", "Collection.group"), ("pymongo.collection", "Collection.inline_map_reduce"), ("pymongo.collection", "Collection.insert"), ("pymongo.collection", "Collection.insert_many"), ("pymongo.collection", "Collection.insert_one"), ("pymongo.collection", "Collection.map_reduce"), ("pymongo.collection", "Collection.reindex"), ("pymongo.collection", "Collection.remove"), ("pymongo.collection", "Collection.rename"), ("pymongo.collection", "Collection.replace_one"), ("pymongo.collection", "Collection.save"), ("pymongo.collection", "Collection.update"), ("pymongo.collection", "Collection.update_many"), ("pymongo.collection", "Collection.update_one"), ] def call(self, module, method, wrapped, instance, args, kwargs): cls_name, method_name = method.split(".", 1) signature = ".".join([instance.full_name, method_name]) nodes = instance.database.client.nodes if nodes: host, port = list(nodes)[0] else: host, port = None, None destination_info = { "address": host, "port": port, "service": {"name": "mongodb", "resource": "mongodb", "type": "db"}, } with capture_span( signature, span_type="db", span_subtype="mongodb", span_action="query", leaf=True, extra={"destination": destination_info}, ): return wrapped(*args, **kwargs) class PyMongoBulkInstrumentation(AbstractInstrumentedModule): name = "pymongo" instrument_list = [("pymongo.bulk", "BulkOperationBuilder.execute")] def call(self, module, method, wrapped, instance, args, kwargs): collection = instance._BulkOperationBuilder__bulk.collection signature = ".".join([collection.full_name, "bulk.execute"]) with capture_span( signature, span_type="db", span_subtype="mongodb", span_action="query", extra={"destination": {"service": {"name": "mongodb", "resource": "mongodb", "type": "db"}}}, ): return wrapped(*args, **kwargs) class PyMongoCursorInstrumentation(AbstractInstrumentedModule): name = "pymongo" instrument_list = [("pymongo.cursor", "Cursor._refresh")] def call(self, module, method, wrapped, instance, args, kwargs): collection = instance.collection signature = ".".join([collection.full_name, "cursor.refresh"]) with capture_span( signature, span_type="db", span_subtype="mongodb", span_action="query", extra={"destination": {"service": {"name": "mongodb", "resource": "mongodb", "type": "db"}}}, ) as span: response = wrapped(*args, **kwargs) if span.context and instance.address: host, port = instance.address span.context["destination"]["address"] = host span.context["destination"]["port"] = port else: pass return response
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/instrumentation/packages/pymongo.py
pymongo.py
from zuqa import async_capture_span from zuqa.conf import constants from zuqa.instrumentation.packages.asyncio.base import AsyncAbstractInstrumentedModule from zuqa.traces import DroppedSpan, execution_context from zuqa.utils import get_host_from_url, sanitize_url, url_to_destination from zuqa.utils.disttracing import TracingOptions class AioHttpClientInstrumentation(AsyncAbstractInstrumentedModule): name = "aiohttp_client" instrument_list = [("aiohttp.client", "ClientSession._request")] async def call(self, module, method, wrapped, instance, args, kwargs): method = kwargs["method"] if "method" in kwargs else args[0] url = kwargs["url"] if "url" in kwargs else args[1] url = str(url) destination = url_to_destination(url) signature = " ".join([method.upper(), get_host_from_url(url)]) url = sanitize_url(url) transaction = execution_context.get_transaction() async with async_capture_span( signature, span_type="external", span_subtype="http", extra={"http": {"url": url}, "destination": destination}, leaf=True, ) as span: leaf_span = span while isinstance(leaf_span, DroppedSpan): leaf_span = leaf_span.parent parent_id = leaf_span.id if leaf_span else transaction.id trace_parent = transaction.trace_parent.copy_from( span_id=parent_id, trace_options=TracingOptions(recorded=True) ) headers = kwargs.get("headers") or {} self._set_disttracing_headers(headers, trace_parent, transaction) kwargs["headers"] = headers return await wrapped(*args, **kwargs) def mutate_unsampled_call_args(self, module, method, wrapped, instance, args, kwargs, transaction): # since we don't have a span, we set the span id to the transaction id trace_parent = transaction.trace_parent.copy_from( span_id=transaction.id, trace_options=TracingOptions(recorded=False) ) headers = kwargs.get("headers") or {} self._set_disttracing_headers(headers, trace_parent, transaction) kwargs["headers"] = headers return args, kwargs def _set_disttracing_headers(self, headers, trace_parent, transaction): trace_parent_str = trace_parent.to_string() headers[constants.TRACEPARENT_HEADER_NAME] = trace_parent_str if transaction.tracer.config.use_elastic_traceparent_header: headers[constants.TRACEPARENT_LEGACY_HEADER_NAME] = trace_parent_str if trace_parent.tracestate: headers[constants.TRACESTATE_HEADER_NAME] = trace_parent.tracestate
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/instrumentation/packages/asyncio/aiohttp_client.py
aiohttp_client.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import hashlib import re import ssl import certifi import urllib3 from urllib3.exceptions import MaxRetryError, TimeoutError from zuqa.transport.base import TransportException from zuqa.transport.http_base import HTTPTransportBase from zuqa.utils import compat, json_encoder, read_pem_file from zuqa.utils.logging import get_logger logger = get_logger("zuqa.transport.http") class Transport(HTTPTransportBase): def __init__(self, url, *args, **kwargs): super(Transport, self).__init__(url, *args, **kwargs) url_parts = compat.urlparse.urlparse(url) pool_kwargs = {"cert_reqs": "CERT_REQUIRED", "ca_certs": certifi.where(), "block": True} if self._server_cert and url_parts.scheme != "http": pool_kwargs.update( {"assert_fingerprint": self.cert_fingerprint, "assert_hostname": False, "cert_reqs": ssl.CERT_NONE} ) del pool_kwargs["ca_certs"] elif not self._verify_server_cert and url_parts.scheme != "http": pool_kwargs["cert_reqs"] = ssl.CERT_NONE pool_kwargs["assert_hostname"] = False proxies = compat.getproxies_environment() proxy_url = proxies.get("https", proxies.get("http", None)) if proxy_url and not compat.proxy_bypass_environment(url_parts.netloc): self.http = urllib3.ProxyManager(proxy_url, **pool_kwargs) else: self.http = urllib3.PoolManager(**pool_kwargs) def send(self, data): response = None headers = self._headers.copy() if self._headers else {} headers.update(self.auth_headers) if compat.PY2 and isinstance(self._url, compat.text_type): url = self._url.encode("utf-8") else: url = self._url try: try: response = self.http.urlopen( "POST", url, body=data, headers=headers, timeout=self._timeout, preload_content=False ) logger.debug("Sent request, url=%s size=%.2fkb status=%s", url, len(data) / 1024.0, response.status) except Exception as e: print_trace = True if isinstance(e, MaxRetryError) and isinstance(e.reason, TimeoutError): message = "Connection to APM Server timed out " "(url: %s, timeout: %s seconds)" % ( self._url, self._timeout, ) print_trace = False else: message = "Unable to reach APM Server: %s (url: %s)" % (e, self._url) raise TransportException(message, data, print_trace=print_trace) body = response.read() if response.status >= 400: if response.status == 429: # rate-limited message = "Temporarily rate limited: " print_trace = False else: message = "HTTP %s: " % response.status print_trace = True message += body.decode("utf8", errors="replace") raise TransportException(message, data, print_trace=print_trace) return response.getheader("Location") finally: if response: response.close() def get_config(self, current_version=None, keys=None): """ Gets configuration from a remote APM Server :param current_version: version of the current configuration :param keys: a JSON-serializable dict to identify this instance, e.g. { "service": { "name": "foo", "environment": "bar" } } :return: a three-tuple of new version, config dictionary and validity in seconds. Any element of the tuple can be None. """ url = self._config_url data = json_encoder.dumps(keys).encode("utf-8") headers = self._headers.copy() headers[b"Content-Type"] = "application/json" headers.pop(b"Content-Encoding", None) # remove gzip content-encoding header headers.update(self.auth_headers) max_age = 300 if current_version: headers["If-None-Match"] = current_version try: response = self.http.urlopen( "POST", url, body=data, headers=headers, timeout=self._timeout, preload_content=False ) except (urllib3.exceptions.RequestError, urllib3.exceptions.HTTPError) as e: logger.debug("HTTP error while fetching remote config: %s", compat.text_type(e)) return current_version, None, max_age body = response.read() if "Cache-Control" in response.headers: try: max_age = int(next(re.finditer(r"max-age=(\d+)", response.headers["Cache-Control"])).groups()[0]) except StopIteration: logger.debug("Could not parse Cache-Control header: %s", response.headers["Cache-Control"]) if response.status == 304: # config is unchanged, return logger.debug("Configuration unchanged") return current_version, None, max_age elif response.status >= 400: return None, None, max_age if not body: logger.debug("APM Server answered with empty body and status code %s", response.status) return current_version, None, max_age return response.headers.get("Etag"), json_encoder.loads(body.decode("utf-8")), max_age @property def cert_fingerprint(self): if self._server_cert: with open(self._server_cert, "rb") as f: cert_data = read_pem_file(f) digest = hashlib.sha256() digest.update(cert_data) return digest.hexdigest() return None @property def auth_headers(self): headers = super(Transport, self).auth_headers return {k.encode("ascii"): v.encode("ascii") for k, v in compat.iteritems(headers)} # left for backwards compatibility AsyncTransport = Transport
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/transport/http.py
http.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from zuqa.conf import constants from zuqa.transport.base import Transport from zuqa.utils import compat class HTTPTransportBase(Transport): def __init__( self, url, client, verify_server_cert=True, compress_level=5, metadata=None, headers=None, timeout=None, server_cert=None, **kwargs ): self._url = url self._verify_server_cert = verify_server_cert self._server_cert = server_cert self._timeout = timeout self._headers = { k.encode("ascii") if isinstance(k, compat.text_type) else k: v.encode("ascii") if isinstance(v, compat.text_type) else v for k, v in (headers if headers is not None else {}).items() } base, sep, tail = self._url.rpartition(constants.EVENTS_API_PATH) self._config_url = "".join((base, constants.AGENT_CONFIG_PATH, tail)) super(HTTPTransportBase, self).__init__(client, metadata=metadata, compress_level=compress_level, **kwargs) def send(self, data): """ Sends a request to a remote APM Server using HTTP POST. Returns the shortcut URL of the recorded error on ZUQA """ raise NotImplementedError() def get_config(self, current_version=None, keys=None): """ Gets configuration from a remote APM Server :param current_version: version of the current configuration :param keys: a JSON-serializable dict to identify this instance, e.g. { "service": { "name": "foo", "environment": "bar" } } :return: a three-tuple of new version, config dictionary and validity in seconds. Any element of the tuple can be None. """ raise NotImplementedError() @property def auth_headers(self): if self.client.config.api_key: return {"Authorization": "ApiKey " + self.client.config.api_key} elif self.client.config.secret_token: return {"Authorization": "Bearer " + self.client.config.secret_token} return {} # left for backwards compatibility AsyncHTTPTransportBase = HTTPTransportBase
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/transport/http_base.py
http_base.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import gzip import os import random import threading import time import timeit from collections import defaultdict from zuqa.utils import compat, json_encoder from zuqa.utils.logging import get_logger from zuqa.utils.threading import ThreadManager logger = get_logger("zuqa.transport") class TransportException(Exception): def __init__(self, message, data=None, print_trace=True): super(TransportException, self).__init__(message) self.data = data self.print_trace = print_trace class Transport(ThreadManager): """ All transport implementations need to subclass this class You must implement a send method.. """ async_mode = False def __init__( self, client, metadata=None, compress_level=5, json_serializer=json_encoder.dumps, queue_chill_count=500, queue_chill_time=1.0, processors=None, **kwargs ): """ Create a new Transport instance :param metadata: Metadata object to prepend to every queue :param compress_level: GZip compress level. If zero, no GZip compression will be used :param json_serializer: serializer to use for JSON encoding :param kwargs: """ self.client = client self.state = TransportState() self._metadata = metadata if metadata is not None else {} self._compress_level = min(9, max(0, compress_level if compress_level is not None else 0)) self._json_serializer = json_serializer self._queued_data = None self._event_queue = self._init_event_queue(chill_until=queue_chill_count, max_chill_time=queue_chill_time) self._is_chilled_queue = isinstance(self._event_queue, ChilledQueue) self._thread = None self._last_flush = timeit.default_timer() self._counts = defaultdict(int) self._flushed = threading.Event() self._closed = False self._processors = processors if processors is not None else [] super(Transport, self).__init__() @property def _max_flush_time(self): return self.client.config.api_request_time / 1000.0 if self.client else None @property def _max_buffer_size(self): return self.client.config.api_request_size if self.client else None def queue(self, event_type, data, flush=False): try: self._flushed.clear() kwargs = {"chill": not (event_type == "close" or flush)} if self._is_chilled_queue else {} self._event_queue.put((event_type, data, flush), block=False, **kwargs) except compat.queue.Full: logger.debug("Event of type %s dropped due to full event queue", event_type) def _process_queue(self): buffer = self._init_buffer() buffer_written = False # add some randomness to timeout to avoid stampedes of several workers that are booted at the same time max_flush_time = self._max_flush_time * random.uniform(0.9, 1.1) if self._max_flush_time else None while True: since_last_flush = timeit.default_timer() - self._last_flush # take max flush time into account to calculate timeout timeout = max(0, max_flush_time - since_last_flush) if max_flush_time else None timed_out = False try: event_type, data, flush = self._event_queue.get(block=True, timeout=timeout) except compat.queue.Empty: event_type, data, flush = None, None, None timed_out = True if event_type == "close": if buffer_written: self._flush(buffer) self._flushed.set() return # time to go home! if data is not None: data = self._process_event(event_type, data) if data is not None: buffer.write((self._json_serializer({event_type: data}) + "\n").encode("utf-8")) buffer_written = True self._counts[event_type] += 1 queue_size = 0 if buffer.fileobj is None else buffer.fileobj.tell() if flush: logger.debug("forced flush") elif timed_out or timeout == 0: # update last flush time, as we might have waited for a non trivial amount of time in # _event_queue.get() since_last_flush = timeit.default_timer() - self._last_flush logger.debug( "flushing due to time since last flush %.3fs > max_flush_time %.3fs", since_last_flush, max_flush_time, ) flush = True elif self._max_buffer_size and queue_size > self._max_buffer_size: logger.debug( "flushing since queue size %d bytes > max_queue_size %d bytes", queue_size, self._max_buffer_size ) flush = True if flush: if buffer_written: self._flush(buffer) self._last_flush = timeit.default_timer() buffer = self._init_buffer() buffer_written = False max_flush_time = self._max_flush_time * random.uniform(0.9, 1.1) if self._max_flush_time else None self._flushed.set() def _process_event(self, event_type, data): # Run the data through processors for processor in self._processors: if not hasattr(processor, "event_types") or event_type in processor.event_types: data = processor(self, data) if not data: logger.debug( "Dropped event of type %s due to processor %s.%s", event_type, getattr(processor, "__module__"), getattr(processor, "__name__"), ) return None return data def _init_buffer(self): buffer = gzip.GzipFile(fileobj=compat.BytesIO(), mode="w", compresslevel=self._compress_level) data = (self._json_serializer({"metadata": self._metadata}) + "\n").encode("utf-8") buffer.write(data) return buffer def _init_event_queue(self, chill_until, max_chill_time): # some libraries like eventlet monkeypatch queue.Queue and switch out the implementation. # In those cases we can't rely on internals of queue.Queue to be there, so we simply use # their queue and forgo the optimizations of ChilledQueue. In the case of eventlet, this # isn't really a loss, because the main reason for ChilledQueue (avoiding context switches # due to the event processor thread being woken up all the time) is not an issue. if all( ( hasattr(compat.queue.Queue, "not_full"), hasattr(compat.queue.Queue, "not_empty"), hasattr(compat.queue.Queue, "unfinished_tasks"), ) ): return ChilledQueue(maxsize=10000, chill_until=chill_until, max_chill_time=max_chill_time) else: return compat.queue.Queue(maxsize=10000) def _flush(self, buffer): """ Flush the queue. This method should only be called from the event processing queue :param sync: if true, flushes the queue synchronously in the current thread :return: None """ if not self.state.should_try(): logger.error("dropping flushed data due to transport failure back-off") else: fileobj = buffer.fileobj # get a reference to the fileobj before closing the gzip file buffer.close() # StringIO on Python 2 does not have getbuffer, so we need to fall back to getvalue data = fileobj.getbuffer() if hasattr(fileobj, "getbuffer") else fileobj.getvalue() try: self.send(data) self.handle_transport_success() except Exception as e: self.handle_transport_fail(e) def start_thread(self, pid=None): super(Transport, self).start_thread(pid=pid) if (not self._thread or self.pid != self._thread.pid) and not self._closed: try: self._thread = threading.Thread(target=self._process_queue, name="eapm event processor thread") self._thread.daemon = True self._thread.pid = self.pid self._thread.start() except RuntimeError: pass def send(self, data): """ You need to override this to do something with the actual data. Usually - this is sending to a server """ raise NotImplementedError def close(self): """ Cleans up resources and closes connection :return: """ if self._closed or (not self._thread or self._thread.pid != os.getpid()): return self._closed = True self.queue("close", None) if not self._flushed.wait(timeout=self._max_flush_time): raise ValueError("close timed out") stop_thread = close def flush(self): """ Trigger a flush of the queue. Note: this method will only return once the queue is empty. This means it can block indefinitely if more events are produced in other threads than can be consumed. """ self.queue(None, None, flush=True) if not self._flushed.wait(timeout=self._max_flush_time): raise ValueError("flush timed out") def handle_transport_success(self, **kwargs): """ Success handler called by the transport on successful send """ self.state.set_success() def handle_transport_fail(self, exception=None, **kwargs): """ Failure handler called by the transport on send failure """ message = str(exception) logger.error("Failed to submit message: %r", message, exc_info=getattr(exception, "print_trace", True)) self.state.set_fail() # left for backwards compatibility AsyncTransport = Transport class TransportState(object): ONLINE = 1 ERROR = 0 def __init__(self): self.status = self.ONLINE self.last_check = None self.retry_number = -1 def should_try(self): if self.status == self.ONLINE: return True interval = min(self.retry_number, 6) ** 2 return timeit.default_timer() - self.last_check > interval def set_fail(self): self.status = self.ERROR self.retry_number += 1 self.last_check = timeit.default_timer() def set_success(self): self.status = self.ONLINE self.last_check = None self.retry_number = -1 def did_fail(self): return self.status == self.ERROR class ChilledQueue(compat.queue.Queue, object): """ A queue subclass that is a bit more chill about how often it notifies the not empty event Note: we inherit from object because queue.Queue is an old-style class in Python 2. This can be removed once we stop support for Python 2 """ def __init__(self, maxsize=0, chill_until=100, max_chill_time=1.0): self._chill_until = chill_until self._max_chill_time = max_chill_time self._last_unchill = time.time() super(ChilledQueue, self).__init__(maxsize=maxsize) def put(self, item, block=True, timeout=None, chill=True): """Put an item into the queue. If optional args 'block' is true and 'timeout' is None (the default), block if necessary until a free slot is available. If 'timeout' is a non-negative number, it blocks at most 'timeout' seconds and raises the Full exception if no free slot was available within that time. Otherwise ('block' is false), put an item on the queue if a free slot is immediately available, else raise the Full exception ('timeout' is ignored in that case). """ with self.not_full: if self.maxsize > 0: if not block: if self._qsize() >= self.maxsize: raise compat.queue.Full elif timeout is None: while self._qsize() >= self.maxsize: self.not_full.wait() elif timeout < 0: raise ValueError("'timeout' must be a non-negative number") else: endtime = time.time() + timeout while self._qsize() >= self.maxsize: remaining = endtime - time.time() if remaining <= 0.0: raise compat.queue.Full self.not_full.wait(remaining) self._put(item) self.unfinished_tasks += 1 if ( not chill or self._qsize() > self._chill_until or (time.time() - self._last_unchill) > self._max_chill_time ): self.not_empty.notify() self._last_unchill = time.time()
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/transport/base.py
base.py
from zuqa.utils import compat try: from urllib import quote except ImportError: from urllib.parse import quote # `get_headers` comes from `werkzeug.datastructures.EnvironHeaders` def get_headers(environ): """ Returns only proper HTTP headers. """ for key, value in compat.iteritems(environ): key = str(key) if key.startswith("HTTP_") and key not in ("HTTP_CONTENT_TYPE", "HTTP_CONTENT_LENGTH"): yield key[5:].replace("_", "-").lower(), value elif key in ("CONTENT_TYPE", "CONTENT_LENGTH"): yield key.replace("_", "-").lower(), value def get_environ(environ): """ Returns our whitelisted environment variables. """ for key in ("REMOTE_ADDR", "SERVER_NAME", "SERVER_PORT"): if key in environ: yield key, environ[key] # `get_host` comes from `werkzeug.wsgi` def get_host(environ): """Return the real host for the given WSGI environment. This takes care of the `X-Forwarded-Host` header. :param environ: the WSGI environment to get the host of. """ scheme = environ.get("wsgi.url_scheme") if "HTTP_X_FORWARDED_HOST" in environ: result = environ["HTTP_X_FORWARDED_HOST"] elif "HTTP_HOST" in environ: result = environ["HTTP_HOST"] else: result = environ["SERVER_NAME"] if (scheme, str(environ["SERVER_PORT"])) not in (("https", "443"), ("http", "80")): result += ":" + environ["SERVER_PORT"] if result.endswith(":80") and scheme == "http": result = result[:-3] elif result.endswith(":443") and scheme == "https": result = result[:-4] return result # `get_current_url` comes from `werkzeug.wsgi` def get_current_url(environ, root_only=False, strip_querystring=False, host_only=False): """A handy helper function that recreates the full URL for the current request or parts of it. Here an example: >>> from werkzeug import create_environ >>> env = create_environ("/?param=foo", "http://localhost/script") >>> get_current_url(env) 'http://localhost/script/?param=foo' >>> get_current_url(env, root_only=True) 'http://localhost/script/' >>> get_current_url(env, host_only=True) 'http://localhost/' >>> get_current_url(env, strip_querystring=True) 'http://localhost/script/' :param environ: the WSGI environment to get the current URL from. :param root_only: set `True` if you only want the root URL. :param strip_querystring: set to `True` if you don't want the querystring. :param host_only: set to `True` if the host URL should be returned. """ tmp = [environ["wsgi.url_scheme"], "://", get_host(environ)] cat = tmp.append if host_only: return "".join(tmp) + "/" cat(quote(environ.get("SCRIPT_NAME", "").rstrip("/"))) if root_only: cat("/") else: cat(quote("/" + environ.get("PATH_INFO", "").lstrip("/"))) if not strip_querystring: qs = environ.get("QUERY_STRING") if qs: cat("?" + qs) return "".join(tmp)
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/utils/wsgi.py
wsgi.py
import fnmatch import inspect import itertools import os import re import sys from zuqa.utils import compat from zuqa.utils.encoding import transform try: from functools import lru_cache except ImportError: from cachetools.func import lru_cache _coding_re = re.compile(r"coding[:=]\s*([-\w.]+)") @lru_cache(512) def get_lines_from_file(filename, lineno, context_lines, loader=None, module_name=None): """ Returns context_lines before and after lineno from file. Returns (pre_context_lineno, pre_context, context_line, post_context). """ lineno = lineno - 1 lower_bound = max(0, lineno - context_lines) upper_bound = lineno + context_lines source = None if loader is not None and hasattr(loader, "get_source"): result = get_source_lines_from_loader(loader, module_name, lineno, lower_bound, upper_bound) if result is not None: return result if source is None: try: with open(filename, "rb") as file_obj: encoding = "utf8" # try to find encoding of source file by "coding" header # if none is found, utf8 is used as a fallback for line in itertools.islice(file_obj, 0, 2): match = _coding_re.search(line.decode("utf8")) if match: encoding = match.group(1) break file_obj.seek(0) lines = [ compat.text_type(line, encoding, "replace") for line in itertools.islice(file_obj, lower_bound, upper_bound + 1) ] offset = lineno - lower_bound return ( [l.strip("\r\n") for l in lines[0:offset]], lines[offset].strip("\r\n"), [l.strip("\r\n") for l in lines[offset + 1 :]] if len(lines) > offset else [], ) except (OSError, IOError, IndexError): pass return None, None, None def get_source_lines_from_loader(loader, module_name, lineno, lower_bound, upper_bound): try: source = loader.get_source(module_name) except ImportError: # ImportError: Loader for module cProfile cannot handle module __main__ return None if source is not None: source = source.splitlines() else: return None, None, None try: pre_context = [line.strip("\r\n") for line in source[lower_bound:lineno]] context_line = source[lineno].strip("\r\n") post_context = [line.strip("\r\n") for line in source[(lineno + 1) : upper_bound + 1]] except IndexError: # the file may have changed since it was loaded into memory return None, None, None return pre_context, context_line, post_context def get_culprit(frames, include_paths=None, exclude_paths=None): # We iterate through each frame looking for a deterministic culprit # When one is found, we mark it as last "best guess" (best_guess) and then # check it against ``exclude_paths``. If it isnt listed, then we # use this option. If nothing is found, we use the "best guess". if include_paths is None: include_paths = [] if exclude_paths is None: exclude_paths = [] best_guess = None culprit = None for frame in frames: try: culprit = ".".join((f or "<unknown>" for f in [frame.get("module"), frame.get("function")])) except KeyError: continue if any((culprit.startswith(k) for k in include_paths)): if not (best_guess and any((culprit.startswith(k) for k in exclude_paths))): best_guess = culprit elif best_guess: break # Return either the best guess or the last frames call return best_guess or culprit def _getitem_from_frame(f_locals, key, default=None): """ f_locals is not guaranteed to have .get(), but it will always support __getitem__. Even if it doesnt, we return ``default``. """ try: return f_locals[key] except Exception: return default def to_dict(dictish): """ Given something that closely resembles a dictionary, we attempt to coerce it into a propery dictionary. """ if hasattr(dictish, "iterkeys"): m = dictish.iterkeys elif hasattr(dictish, "keys"): m = dictish.keys else: raise ValueError(dictish) return dict((k, dictish[k]) for k in m()) def iter_traceback_frames(tb, config=None): """ Given a traceback object, it will iterate over all frames that do not contain the ``__traceback_hide__`` local variable. """ max_frames = config.stack_trace_limit if config else -1 if not max_frames: return frames = [] while tb: # support for __traceback_hide__ which is used by a few libraries # to hide internal frames. frame = tb.tb_frame f_locals = getattr(frame, "f_locals", None) if f_locals is None or not _getitem_from_frame(f_locals, "__traceback_hide__"): frames.append((frame, getattr(tb, "tb_lineno", None))) tb = tb.tb_next if max_frames != -1: frames = frames[-max_frames:] for frame in frames: yield frame def iter_stack_frames(frames=None, start_frame=None, skip=0, skip_top_modules=(), config=None): """ Given an optional list of frames (defaults to current stack), iterates over all frames that do not contain the ``__traceback_hide__`` local variable. Frames can be skipped by either providing a number, or a tuple of module names. If the module of a frame matches one of the names (using `.startswith`, that frame will be skipped. This matching will only be done until the first frame doesn't match. This is useful to filter out frames that are caused by frame collection itself. :param frames: a list of frames, or None :param start_frame: a Frame object or None :param skip: number of frames to skip from the beginning :param skip_top_modules: tuple of strings :param config: agent configuration """ if not frames: frame = start_frame if start_frame is not None else inspect.currentframe().f_back frames = _walk_stack(frame) max_frames = config.stack_trace_limit if config else -1 stop_ignoring = False frames_count = 0 # can't use i, as we don't want to count skipped and ignored frames for i, frame in enumerate(frames): if max_frames != -1 and frames_count == max_frames: break if i < skip: continue f_globals = getattr(frame, "f_globals", {}) if not stop_ignoring and f_globals.get("__name__", "").startswith(skip_top_modules): continue stop_ignoring = True f_locals = getattr(frame, "f_locals", {}) if not _getitem_from_frame(f_locals, "__traceback_hide__"): frames_count += 1 yield frame, frame.f_lineno def get_frame_info( frame, lineno, with_locals=True, library_frame_context_lines=None, in_app_frame_context_lines=None, include_paths_re=None, exclude_paths_re=None, locals_processor_func=None, ): # Support hidden frames f_locals = getattr(frame, "f_locals", {}) if _getitem_from_frame(f_locals, "__traceback_hide__"): return None f_globals = getattr(frame, "f_globals", {}) loader = f_globals.get("__loader__") module_name = f_globals.get("__name__") f_code = getattr(frame, "f_code", None) if f_code: abs_path = frame.f_code.co_filename function = frame.f_code.co_name else: abs_path = None function = None # Try to pull a relative file path # This changes /foo/site-packages/baz/bar.py into baz/bar.py try: base_filename = sys.modules[module_name.split(".", 1)[0]].__file__ filename = abs_path.split(base_filename.rsplit(os.path.sep, 2)[0], 1)[-1].lstrip(os.path.sep) except Exception: filename = abs_path if not filename: filename = abs_path frame_result = { "abs_path": abs_path, "filename": filename, "module": module_name, "function": function, "lineno": lineno, "library_frame": is_library_frame(abs_path, include_paths_re, exclude_paths_re), } context_lines = library_frame_context_lines if frame_result["library_frame"] else in_app_frame_context_lines if context_lines and lineno is not None and abs_path: # context_metadata will be processed by zuqa.processors.add_context_lines_to_frames. # This ensures that blocking operations (reading from source files) happens on the background # processing thread. frame_result["context_metadata"] = (abs_path, lineno, int(context_lines / 2), loader, module_name) if with_locals: if f_locals is not None and not isinstance(f_locals, dict): # XXX: Genshi (and maybe others) have broken implementations of # f_locals that are not actually dictionaries try: f_locals = to_dict(f_locals) except Exception: f_locals = "<invalid local scope>" if locals_processor_func: f_locals = {varname: locals_processor_func(var) for varname, var in compat.iteritems(f_locals)} frame_result["vars"] = transform(f_locals) return frame_result def get_stack_info( frames, with_locals=True, library_frame_context_lines=None, in_app_frame_context_lines=None, include_paths_re=None, exclude_paths_re=None, locals_processor_func=None, ): """ Given a list of frames, returns a list of stack information dictionary objects that are JSON-ready. We have to be careful here as certain implementations of the _Frame class do not contain the necessary data to lookup all of the information we want. :param frames: a list of (Frame, lineno) tuples :param with_locals: boolean to indicate if local variables should be collected :param include_paths_re: a regex to determine if a frame is not a library frame :param exclude_paths_re: a regex to exclude frames from not being library frames :param locals_processor_func: a function to call on all local variables :return: """ results = [] for frame, lineno in frames: result = get_frame_info( frame, lineno, library_frame_context_lines=library_frame_context_lines, in_app_frame_context_lines=in_app_frame_context_lines, with_locals=with_locals, include_paths_re=include_paths_re, exclude_paths_re=exclude_paths_re, locals_processor_func=locals_processor_func, ) if result: results.append(result) return results def _walk_stack(frame): while frame: yield frame frame = frame.f_back @lru_cache(512) def is_library_frame(abs_file_path, include_paths_re, exclude_paths_re): if not abs_file_path: return True if include_paths_re and include_paths_re.match(abs_file_path): # frame is in-app, return False return False elif exclude_paths_re and exclude_paths_re.match(abs_file_path): return True # if neither excluded nor included, assume it's an in-app frame return False def get_path_regex(paths): """ compiles a list of path globs into a single pattern that matches any of the given paths :param paths: a list of strings representing fnmatch path globs :return: a compiled regex """ return re.compile("|".join(map(fnmatch.translate, paths)))
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/utils/stacks.py
stacks.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import atexit import functools import operator import platform import sys import types def noop_decorator(func): @functools.wraps(func) def wrapped(*args, **kwargs): return func(*args, **kwargs) return wrapped def atexit_register(func): """ Uses either uwsgi's atexit mechanism, or atexit from the stdlib. When running under uwsgi, using their atexit handler is more reliable, especially when using gevent :param func: the function to call at exit """ try: import uwsgi orig = getattr(uwsgi, "atexit", None) def uwsgi_atexit(): if callable(orig): orig() func() uwsgi.atexit = uwsgi_atexit except ImportError: atexit.register(func) # Compatibility layer for Python2/Python3, partly inspired by /modified from six, https://github.com/benjaminp/six # Remainder of this file: Copyright Benjamin Peterson, MIT License https://github.com/benjaminp/six/blob/master/LICENSE PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 if PY2: import StringIO import Queue as queue # noqa F401 import urlparse # noqa F401 from urllib2 import HTTPError # noqa F401 from urllib import proxy_bypass_environment, getproxies_environment # noqa F401 StringIO = BytesIO = StringIO.StringIO string_types = (basestring,) # noqa F821 integer_types = (int, long) # noqa F821 class_types = (type, types.ClassType) text_type = unicode # noqa F821 binary_type = str irange = xrange # noqa F821 def b(s): return s get_function_code = operator.attrgetter("func_code") def iterkeys(d, **kwargs): return d.iterkeys(**kwargs) def iteritems(d, **kwargs): return d.iteritems(**kwargs) # for django.utils.datastructures.MultiValueDict def iterlists(d, **kw): return d.iterlists(**kw) else: import io import queue # noqa F401 from urllib import parse as urlparse # noqa F401 from urllib.error import HTTPError # noqa F401 from urllib.request import proxy_bypass_environment, getproxies_environment # noqa F401 StringIO = io.StringIO BytesIO = io.BytesIO string_types = (str,) integer_types = (int,) class_types = (type,) text_type = str binary_type = bytes irange = range def b(s): return s.encode("latin-1") get_function_code = operator.attrgetter("__code__") def iterkeys(d, **kwargs): return iter(d.keys(**kwargs)) def iteritems(d, **kwargs): return iter(d.items(**kwargs)) # for django.utils.datastructures.MultiValueDict def iterlists(d, **kw): return iter(d.lists(**kw)) def get_default_library_patters(): """ Returns library paths depending on the used platform. :return: a list of glob paths """ python_version = platform.python_version_tuple() python_implementation = platform.python_implementation() system = platform.system() if python_implementation == "PyPy": if python_version[0] == "2": return ["*/lib-python/%s.%s/*" % python_version[:2], "*/site-packages/*"] else: return ["*/lib-python/%s/*" % python_version[0], "*/site-packages/*"] else: if system == "Windows": return [r"*\lib\*"] return ["*/lib/python%s.%s/*" % python_version[:2], "*/lib64/python%s.%s/*" % python_version[:2]] def multidict_to_dict(d): """ Turns a werkzeug.MultiDict or django.MultiValueDict into a dict with list values :param d: a MultiDict or MultiValueDict instance :return: a dict instance """ return dict((k, v[0] if len(v) == 1 else v) for k, v in iterlists(d)) try: import uwsgi # check if a master is running before importing postfork if uwsgi.masterpid() != 0: from uwsgidecorators import postfork else: def postfork(f): return f except ImportError: def postfork(f): return f
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/utils/compat.py
compat.py
from __future__ import absolute_import import os import threading from timeit import default_timer class IntervalTimer(threading.Thread): """ A timer that runs a function repeatedly. In contrast to threading.Timer, IntervalTimer runs the given function in perpetuity or until it is cancelled. When run, it will wait `interval` seconds until the first execution. """ def __init__( self, function, interval, name=None, args=(), kwargs=None, daemon=None, evaluate_function_interval=False ): """ :param function: the function to run :param interval: the interval in-between invocations of the function, in milliseconds :param name: name of the thread :param args: arguments to call the function with :param kwargs: keyword arguments to call the function with :param daemon: should the thread run as a daemon :param evaluate_function_interval: if set to True, and the function returns a number, it will be used as the next interval """ super(IntervalTimer, self).__init__(name=name) self.daemon = daemon self._args = args self._kwargs = kwargs if kwargs is not None else {} self._function = function self._interval = interval self._interval_done = threading.Event() self._evaluate_function_interval = evaluate_function_interval def run(self): execution_time = 0 interval_override = None while True: real_interval = (interval_override if interval_override is not None else self._interval) - execution_time interval_completed = True if real_interval: interval_completed = not self._interval_done.wait(real_interval) if not interval_completed: # we've been cancelled, time to go home return start = default_timer() rval = self._function(*self._args, **self._kwargs) if self._evaluate_function_interval and isinstance(rval, (int, float)): interval_override = rval else: interval_override = None execution_time = default_timer() - start def cancel(self): self._interval_done.set() class ThreadManager(object): def __init__(self): self.pid = None def start_thread(self, pid=None): if not pid: pid = os.getpid() self.pid = pid def stop_thread(self): raise NotImplementedError() def is_started(self, current_pid=None): if not current_pid: current_pid = os.getpid() return self.pid == current_pid
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/utils/threading.py
threading.py
import datetime import itertools import uuid from decimal import Decimal from zuqa.conf.constants import KEYWORD_MAX_LENGTH, LABEL_RE, LABEL_TYPES from zuqa.utils import compat PROTECTED_TYPES = compat.integer_types + (type(None), float, Decimal, datetime.datetime, datetime.date, datetime.time) def is_protected_type(obj): """Determine if the object instance is of a protected type. Objects of protected types are preserved as-is when passed to force_text(strings_only=True). """ return isinstance(obj, PROTECTED_TYPES) def force_text(s, encoding="utf-8", strings_only=False, errors="strict"): """ Similar to smart_text, except that lazy instances are resolved to strings, rather than kept as lazy objects. If strings_only is True, don't convert (some) non-string-like objects. """ # Handle the common case first, saves 30-40% when s is an instance of # compat.text_type. This function gets called often in that setting. # # Adapted from Django if isinstance(s, compat.text_type): return s if strings_only and is_protected_type(s): return s try: if not isinstance(s, compat.string_types): if hasattr(s, "__unicode__"): s = s.__unicode__() else: if compat.PY3: if isinstance(s, bytes): s = compat.text_type(s, encoding, errors) else: s = compat.text_type(s) else: s = compat.text_type(bytes(s), encoding, errors) else: # Note: We use .decode() here, instead of compat.text_type(s, encoding, # errors), so that if s is a SafeBytes, it ends up being a # SafeText at the end. s = s.decode(encoding, errors) except UnicodeDecodeError as e: if not isinstance(s, Exception): raise UnicodeDecodeError(*e.args) else: # If we get to here, the caller has passed in an Exception # subclass populated with non-ASCII bytestring data without a # working unicode method. Try to handle this without raising a # further exception by individually forcing the exception args # to unicode. s = " ".join([force_text(arg, encoding, strings_only, errors) for arg in s]) return s def _has_zuqa_metadata(value): try: return callable(value.__getattribute__("__zuqa__")) except Exception: return False def transform(value, stack=None, context=None): # TODO: make this extendable if context is None: context = {} if stack is None: stack = [] objid = id(value) if objid in context: return "<...>" context[objid] = 1 transform_rec = lambda o: transform(o, stack + [value], context) if any(value is s for s in stack): ret = "cycle" elif isinstance(value, (tuple, list, set, frozenset)): try: ret = type(value)(transform_rec(o) for o in value) except Exception: # We may be dealing with a namedtuple class value_type(list): __name__ = type(value).__name__ ret = value_type(transform_rec(o) for o in value) elif isinstance(value, uuid.UUID): ret = repr(value) elif isinstance(value, dict): ret = dict((to_unicode(k), transform_rec(v)) for k, v in compat.iteritems(value)) elif isinstance(value, compat.text_type): ret = to_unicode(value) elif isinstance(value, compat.binary_type): ret = to_string(value) elif not isinstance(value, compat.class_types) and _has_zuqa_metadata(value): ret = transform_rec(value.__zuqa__()) elif isinstance(value, bool): ret = bool(value) elif isinstance(value, float): ret = float(value) elif isinstance(value, int): ret = int(value) elif compat.PY2 and isinstance(value, long): # noqa F821 ret = long(value) # noqa F821 elif value is not None: try: ret = transform(repr(value)) except Exception: # It's common case that a model's __unicode__ definition may try to query the database # which if it was not cleaned up correctly, would hit a transaction aborted exception ret = u"<BadRepr: %s>" % type(value) else: ret = None del context[objid] return ret def to_unicode(value): try: value = compat.text_type(force_text(value)) except (UnicodeEncodeError, UnicodeDecodeError): value = "(Error decoding value)" except Exception: # in some cases we get a different exception try: value = compat.binary_type(repr(type(value))) except Exception: value = "(Error decoding value)" return value def to_string(value): try: return compat.binary_type(value.decode("utf-8").encode("utf-8")) except Exception: return to_unicode(value).encode("utf-8") def shorten(var, list_length=50, string_length=200, dict_length=50): """ Shorten a given variable based on configurable maximum lengths, leaving breadcrumbs in the object to show that it was shortened. For strings, truncate the string to the max length, and append "..." so the user knows data was lost. For lists, truncate the list to the max length, and append two new strings to the list: "..." and "(<x> more elements)" where <x> is the number of elements removed. For dicts, truncate the dict to the max length (based on number of key/value pairs) and add a new (key, value) pair to the dict: ("...", "(<x> more elements)") where <x> is the number of key/value pairs removed. :param var: Variable to be shortened :param list_length: Max length (in items) of lists :param string_length: Max length (in characters) of strings :param dict_length: Max length (in key/value pairs) of dicts :return: Shortened variable """ var = transform(var) if isinstance(var, compat.string_types) and len(var) > string_length: var = var[: string_length - 3] + "..." elif isinstance(var, (list, tuple, set, frozenset)) and len(var) > list_length: # TODO: we should write a real API for storing some metadata with vars when # we get around to doing ref storage var = list(var)[:list_length] + ["...", "(%d more elements)" % (len(var) - list_length,)] elif isinstance(var, dict) and len(var) > dict_length: trimmed_tuples = [(k, v) for (k, v) in itertools.islice(compat.iteritems(var), dict_length)] if "<truncated>" not in var: trimmed_tuples += [("<truncated>", "(%d more elements)" % (len(var) - dict_length))] var = dict(trimmed_tuples) return var def keyword_field(string): if not isinstance(string, compat.string_types) or len(string) <= KEYWORD_MAX_LENGTH: return string return string[: KEYWORD_MAX_LENGTH - 1] + u"…" def enforce_label_format(labels): """ Enforces label format: * dots, double quotes or stars in keys are replaced by underscores * string values are limited to a length of 1024 characters * values can only be of a limited set of types :param labels: a dictionary of labels :return: a new dictionary with sanitized keys/values """ new = {} for key, value in compat.iteritems(labels): if not isinstance(value, LABEL_TYPES): value = keyword_field(compat.text_type(value)) new[LABEL_RE.sub("_", compat.text_type(key))] = value return new
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/utils/encoding.py
encoding.py
import ctypes from zuqa.conf import constants from zuqa.utils.logging import get_logger logger = get_logger("zuqa.utils") class TraceParent(object): __slots__ = ("version", "trace_id", "span_id", "trace_options", "tracestate", "is_legacy") def __init__(self, version, trace_id, span_id, trace_options, tracestate=None, is_legacy=False): self.version = version self.trace_id = trace_id self.span_id = span_id self.trace_options = trace_options self.is_legacy = is_legacy self.tracestate = tracestate def copy_from(self, version=None, trace_id=None, span_id=None, trace_options=None, tracestate=None): return TraceParent( version or self.version, trace_id or self.trace_id, span_id or self.span_id, trace_options or self.trace_options, tracestate or self.tracestate, ) def to_string(self): return "{:02x}-{}-{}-{:02x}".format(self.version, self.trace_id, self.span_id, self.trace_options.asByte) def to_ascii(self): return self.to_string().encode("ascii") @classmethod def from_string(cls, traceparent_string, tracestate_string=None, is_legacy=False): try: parts = traceparent_string.split("-") version, trace_id, span_id, trace_flags = parts[:4] except ValueError: logger.debug("Invalid traceparent header format, value %s", traceparent_string) return try: version = int(version, 16) if version == 255: raise ValueError() except ValueError: logger.debug("Invalid version field, value %s", version) return try: tracing_options = TracingOptions() tracing_options.asByte = int(trace_flags, 16) except ValueError: logger.debug("Invalid trace-options field, value %s", trace_flags) return return TraceParent(version, trace_id, span_id, tracing_options, tracestate_string, is_legacy) @classmethod def from_headers( cls, headers, header_name=constants.TRACEPARENT_HEADER_NAME, legacy_header_name=constants.TRACEPARENT_LEGACY_HEADER_NAME, tracestate_header_name=constants.TRACESTATE_HEADER_NAME, ): tracestate = cls.merge_duplicate_headers(headers, tracestate_header_name) if header_name in headers: return TraceParent.from_string(headers[header_name], tracestate, is_legacy=False) elif legacy_header_name in headers: return TraceParent.from_string(headers[legacy_header_name], tracestate, is_legacy=False) else: return None @classmethod def merge_duplicate_headers(cls, headers, key): """ HTTP allows multiple values for the same header name. Most WSGI implementations merge these values using a comma as separator (this has been confirmed for wsgiref, werkzeug, gunicorn and uwsgi). Other implementations may use containers like multidict to store headers and have APIs to iterate over all values for a given key. This method is provided as a hook for framework integrations to provide their own TraceParent implementation. The implementation should return a single string. Multiple values for the same key should be merged using a comma as separator. :param headers: a dict-like header object :param key: header name :return: a single string value or None """ # this works for all known WSGI implementations return headers.get(key) class TracingOptions_bits(ctypes.LittleEndianStructure): _fields_ = [("recorded", ctypes.c_uint8, 1)] class TracingOptions(ctypes.Union): _anonymous_ = ("bit",) _fields_ = [("bit", TracingOptions_bits), ("asByte", ctypes.c_uint8)] def __init__(self, **kwargs): super(TracingOptions, self).__init__() for k, v in kwargs.items(): setattr(self, k, v) def trace_parent_from_string(traceparent_string, tracestate_string=None, is_legacy=False): """ This is a wrapper function so we can add traceparent generation to the public API. """ return TraceParent.from_string(traceparent_string, tracestate_string=tracestate_string, is_legacy=is_legacy) def trace_parent_from_headers(headers): """ This is a wrapper function so we can add traceparent generation to the public API. """ return TraceParent.from_headers(headers)
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/utils/disttracing.py
disttracing.py
import os import re CGROUP_PATH = "/proc/self/cgroup" SYSTEMD_SCOPE_SUFFIX = ".scope" kubepods_regexp = re.compile( r"(?:^/kubepods/[^/]+/pod([^/]+)$)|(?:^/kubepods\.slice/kubepods-[^/]+\.slice/kubepods-[^/]+-pod([^/]+)\.slice$)" ) container_id_regexp = re.compile( "^(?:[0-9a-f]{64}|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4,})$", re.IGNORECASE ) def get_cgroup_container_metadata(): """ Reads docker/kubernetes metadata (container id, pod id) from /proc/self/cgroup The result is a nested dictionary with the detected IDs, e.g. { "container": {"id": "2227daf62df6694645fee5df53c1f91271546a9560e8600a525690ae252b7f63"}, "pod": {"uid": "90d81341_92de_11e7_8cf2_507b9d4141fa"} } :return: a dictionary with the detected ids or {} """ if not os.path.exists(CGROUP_PATH): return {} with open(CGROUP_PATH) as f: return parse_cgroups(f) or {} def parse_cgroups(filehandle): """ Reads lines from a file handle and tries to parse docker container IDs and kubernetes Pod IDs. See tests.utils.docker_tests.test_cgroup_parsing for a set of test cases :param filehandle: :return: nested dictionary or None """ for line in filehandle: parts = line.strip().split(":") if len(parts) != 3: continue cgroup_path = parts[2] # Depending on the filesystem driver used for cgroup # management, the paths in /proc/pid/cgroup will have # one of the following formats in a Docker container: # # systemd: /system.slice/docker-<container-ID>.scope # cgroupfs: /docker/<container-ID> # # In a Kubernetes pod, the cgroup path will look like: # # systemd:/kubepods.slice/kubepods-<QoS-class>.slice/kubepods-<QoS-class>-pod<pod-UID>.slice/<container-iD>.scope # cgroupfs:/kubepods/<QoS-class>/pod<pod-UID>/<container-iD> directory, container_id = os.path.split(cgroup_path) if container_id.endswith(SYSTEMD_SCOPE_SUFFIX): container_id = container_id[: -len(SYSTEMD_SCOPE_SUFFIX)] if "-" in container_id: container_id = container_id.split("-", 1)[1] kubepods_match = kubepods_regexp.match(directory) if kubepods_match: pod_id = kubepods_match.group(1) if not pod_id: pod_id = kubepods_match.group(2) if pod_id: pod_id = pod_id.replace("_", "-") return {"container": {"id": container_id}, "kubernetes": {"pod": {"uid": pod_id}}} elif container_id_regexp.match(container_id): return {"container": {"id": container_id}}
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/utils/cgroup.py
cgroup.py
import base64 import os import re from functools import partial from zuqa.conf import constants from zuqa.utils import compat, encoding try: from functools import partialmethod partial_types = (partial, partialmethod) except ImportError: # Python 2 partial_types = (partial,) default_ports = {"https": 443, "http": 80, "postgresql": 5432, "mysql": 3306, "mssql": 1433} def varmap(func, var, context=None, name=None): """ Executes ``func(key_name, value)`` on all values, recursively discovering dict and list scoped values. """ if context is None: context = set() objid = id(var) if objid in context: return func(name, "<...>") context.add(objid) if isinstance(var, dict): ret = func(name, dict((k, varmap(func, v, context, k)) for k, v in compat.iteritems(var))) elif isinstance(var, (list, tuple)): ret = func(name, [varmap(func, f, context, name) for f in var]) else: ret = func(name, var) context.remove(objid) return ret def get_name_from_func(func): # partials don't have `__module__` or `__name__`, so we use the values from the "inner" function if isinstance(func, partial_types): return "partial({})".format(get_name_from_func(func.func)) elif hasattr(func, "_partialmethod") and hasattr(func._partialmethod, "func"): return "partial({})".format(get_name_from_func(func._partialmethod.func)) module = func.__module__ if hasattr(func, "__name__"): view_name = func.__name__ else: # Fall back if there's no __name__ view_name = func.__class__.__name__ return "{0}.{1}".format(module, view_name) def build_name_with_http_method_prefix(name, request): return " ".join((request.method, name)) if name else name def is_master_process(): # currently only recognizes uwsgi master process try: import uwsgi return os.getpid() == uwsgi.masterpid() except ImportError: return False def get_url_dict(url): parse_result = compat.urlparse.urlparse(url) url_dict = { "full": encoding.keyword_field(url), "protocol": parse_result.scheme + ":", "hostname": encoding.keyword_field(parse_result.hostname), "pathname": encoding.keyword_field(parse_result.path), } port = None if parse_result.port is None else str(parse_result.port) if port: url_dict["port"] = port if parse_result.query: url_dict["search"] = encoding.keyword_field("?" + parse_result.query) return url_dict def sanitize_url(url): if "@" not in url: return url parts = compat.urlparse.urlparse(url) return url.replace("%s:%s" % (parts.username, parts.password), "%s:%s" % (parts.username, constants.MASK)) def get_host_from_url(url): parsed_url = compat.urlparse.urlparse(url) host = parsed_url.hostname or " " if parsed_url.port and default_ports.get(parsed_url.scheme) != parsed_url.port: host += ":" + str(parsed_url.port) return host def url_to_destination(url, service_type="external"): parts = compat.urlparse.urlsplit(url) hostname = parts.hostname # preserve brackets for IPv6 URLs if "://[" in url: hostname = "[%s]" % hostname try: port = parts.port except ValueError: # Malformed port, just use None rather than raising an exception port = None default_port = default_ports.get(parts.scheme, None) name = "%s://%s" % (parts.scheme, hostname) resource = hostname if not port and parts.scheme in default_ports: port = default_ports[parts.scheme] if port: if port != default_port: name += ":%d" % port resource += ":%d" % port return {"service": {"name": name, "resource": resource, "type": service_type}} def read_pem_file(file_obj): cert = b"" for line in file_obj: if line.startswith(b"-----BEGIN CERTIFICATE-----"): break # scan until we find the first END CERTIFICATE marker for line in file_obj: if line.startswith(b"-----END CERTIFICATE-----"): break cert += line.strip() return base64.b64decode(cert) def starmatch_to_regex(pattern): i, n = 0, len(pattern) res = [] while i < n: c = pattern[i] i = i + 1 if c == "*": res.append(".*") else: res.append(re.escape(c)) return re.compile(r"(?:%s)\Z" % "".join(res), re.IGNORECASE | re.DOTALL)
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/utils/__init__.py
__init__.py
import sys PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 if PY3: string_types = str, import builtins exec_ = getattr(builtins, "exec") del builtins else: string_types = basestring, def exec_(_code_, _globs_=None, _locs_=None): """Execute code in a namespace.""" if _globs_ is None: frame = sys._getframe(1) _globs_ = frame.f_globals if _locs_ is None: _locs_ = frame.f_locals del frame elif _locs_ is None: _locs_ = _globs_ exec("""exec _code_ in _globs_, _locs_""") from functools import partial from inspect import ismethod, isclass, formatargspec from collections import namedtuple from threading import Lock, RLock try: from inspect import signature except ImportError: pass from .wrappers import (FunctionWrapper, BoundFunctionWrapper, ObjectProxy, CallableObjectProxy) # Adapter wrapper for the wrapped function which will overlay certain # properties from the adapter function onto the wrapped function so that # functions such as inspect.getargspec(), inspect.getfullargspec(), # inspect.signature() and inspect.getsource() return the correct results # one would expect. class _AdapterFunctionCode(CallableObjectProxy): def __init__(self, wrapped_code, adapter_code): super(_AdapterFunctionCode, self).__init__(wrapped_code) self._self_adapter_code = adapter_code @property def co_argcount(self): return self._self_adapter_code.co_argcount @property def co_code(self): return self._self_adapter_code.co_code @property def co_flags(self): return self._self_adapter_code.co_flags @property def co_kwonlyargcount(self): return self._self_adapter_code.co_kwonlyargcount @property def co_varnames(self): return self._self_adapter_code.co_varnames class _AdapterFunctionSurrogate(CallableObjectProxy): def __init__(self, wrapped, adapter): super(_AdapterFunctionSurrogate, self).__init__(wrapped) self._self_adapter = adapter @property def __code__(self): return _AdapterFunctionCode(self.__wrapped__.__code__, self._self_adapter.__code__) @property def __defaults__(self): return self._self_adapter.__defaults__ @property def __kwdefaults__(self): return self._self_adapter.__kwdefaults__ @property def __signature__(self): if 'signature' not in globals(): return self._self_adapter.__signature__ else: # Can't allow this to fail on Python 3 else it falls # through to using __wrapped__, but that will be the # wrong function we want to derive the signature # from. Thus generate the signature ourselves. return signature(self._self_adapter) if PY2: func_code = __code__ func_defaults = __defaults__ class _BoundAdapterWrapper(BoundFunctionWrapper): @property def __func__(self): return _AdapterFunctionSurrogate(self.__wrapped__.__func__, self._self_parent._self_adapter) if PY2: im_func = __func__ class AdapterWrapper(FunctionWrapper): __bound_function_wrapper__ = _BoundAdapterWrapper def __init__(self, *args, **kwargs): adapter = kwargs.pop('adapter') super(AdapterWrapper, self).__init__(*args, **kwargs) self._self_surrogate = _AdapterFunctionSurrogate( self.__wrapped__, adapter) self._self_adapter = adapter @property def __code__(self): return self._self_surrogate.__code__ @property def __defaults__(self): return self._self_surrogate.__defaults__ @property def __kwdefaults__(self): return self._self_surrogate.__kwdefaults__ if PY2: func_code = __code__ func_defaults = __defaults__ @property def __signature__(self): return self._self_surrogate.__signature__ class AdapterFactory(object): def __call__(self, wrapped): raise NotImplementedError() class DelegatedAdapterFactory(AdapterFactory): def __init__(self, factory): super(DelegatedAdapterFactory, self).__init__() self.factory = factory def __call__(self, wrapped): return self.factory(wrapped) adapter_factory = DelegatedAdapterFactory # Decorator for creating other decorators. This decorator and the # wrappers which they use are designed to properly preserve any name # attributes, function signatures etc, in addition to the wrappers # themselves acting like a transparent proxy for the original wrapped # function so the wrapper is effectively indistinguishable from the # original wrapped function. def decorator(wrapper=None, enabled=None, adapter=None): # The decorator should be supplied with a single positional argument # which is the wrapper function to be used to implement the # decorator. This may be preceded by a step whereby the keyword # arguments are supplied to customise the behaviour of the # decorator. The 'adapter' argument is used to optionally denote a # separate function which is notionally used by an adapter # decorator. In that case parts of the function '__code__' and # '__defaults__' attributes are used from the adapter function # rather than those of the wrapped function. This allows for the # argument specification from inspect.getargspec() and similar # functions to be overridden with a prototype for a different # function than what was wrapped. The 'enabled' argument provides a # way to enable/disable the use of the decorator. If the type of # 'enabled' is a boolean, then it is evaluated immediately and the # wrapper not even applied if it is False. If not a boolean, it will # be evaluated when the wrapper is called for an unbound wrapper, # and when binding occurs for a bound wrapper. When being evaluated, # if 'enabled' is callable it will be called to obtain the value to # be checked. If False, the wrapper will not be called and instead # the original wrapped function will be called directly instead. if wrapper is not None: # Helper function for creating wrapper of the appropriate # time when we need it down below. def _build(wrapped, wrapper, enabled=None, adapter=None): if adapter: if isinstance(adapter, AdapterFactory): adapter = adapter(wrapped) if not callable(adapter): ns = {} if not isinstance(adapter, string_types): adapter = formatargspec(*adapter) exec_('def adapter{0}: pass'.format(adapter), ns, ns) adapter = ns['adapter'] return AdapterWrapper(wrapped=wrapped, wrapper=wrapper, enabled=enabled, adapter=adapter) return FunctionWrapper(wrapped=wrapped, wrapper=wrapper, enabled=enabled) # The wrapper has been provided so return the final decorator. # The decorator is itself one of our function wrappers so we # can determine when it is applied to functions, instance methods # or class methods. This allows us to bind the instance or class # method so the appropriate self or cls attribute is supplied # when it is finally called. def _wrapper(wrapped, instance, args, kwargs): # We first check for the case where the decorator was applied # to a class type. # # @decorator # class mydecoratorclass(object): # def __init__(self, arg=None): # self.arg = arg # def __call__(self, wrapped, instance, args, kwargs): # return wrapped(*args, **kwargs) # # @mydecoratorclass(arg=1) # def function(): # pass # # In this case an instance of the class is to be used as the # decorator wrapper function. If args was empty at this point, # then it means that there were optional keyword arguments # supplied to be used when creating an instance of the class # to be used as the wrapper function. if instance is None and isclass(wrapped) and not args: # We still need to be passed the target function to be # wrapped as yet, so we need to return a further function # to be able to capture it. def _capture(target_wrapped): # Now have the target function to be wrapped and need # to create an instance of the class which is to act # as the decorator wrapper function. Before we do that, # we need to first check that use of the decorator # hadn't been disabled by a simple boolean. If it was, # the target function to be wrapped is returned instead. _enabled = enabled if type(_enabled) is bool: if not _enabled: return target_wrapped _enabled = None # Now create an instance of the class which is to act # as the decorator wrapper function. Any arguments had # to be supplied as keyword only arguments so that is # all we pass when creating it. target_wrapper = wrapped(**kwargs) # Finally build the wrapper itself and return it. return _build(target_wrapped, target_wrapper, _enabled, adapter) return _capture # We should always have the target function to be wrapped at # this point as the first (and only) value in args. target_wrapped = args[0] # Need to now check that use of the decorator hadn't been # disabled by a simple boolean. If it was, then target # function to be wrapped is returned instead. _enabled = enabled if type(_enabled) is bool: if not _enabled: return target_wrapped _enabled = None # We now need to build the wrapper, but there are a couple of # different cases we need to consider. if instance is None: if isclass(wrapped): # In this case the decorator was applied to a class # type but optional keyword arguments were not supplied # for initialising an instance of the class to be used # as the decorator wrapper function. # # @decorator # class mydecoratorclass(object): # def __init__(self, arg=None): # self.arg = arg # def __call__(self, wrapped, instance, # args, kwargs): # return wrapped(*args, **kwargs) # # @mydecoratorclass # def function(): # pass # # We still need to create an instance of the class to # be used as the decorator wrapper function, but no # arguments are pass. target_wrapper = wrapped() else: # In this case the decorator was applied to a normal # function, or possibly a static method of a class. # # @decorator # def mydecoratorfuntion(wrapped, instance, # args, kwargs): # return wrapped(*args, **kwargs) # # @mydecoratorfunction # def function(): # pass # # That normal function becomes the decorator wrapper # function. target_wrapper = wrapper else: if isclass(instance): # In this case the decorator was applied to a class # method. # # class myclass(object): # @decorator # @classmethod # def decoratorclassmethod(cls, wrapped, # instance, args, kwargs): # return wrapped(*args, **kwargs) # # instance = myclass() # # @instance.decoratorclassmethod # def function(): # pass # # This one is a bit strange because binding was actually # performed on the wrapper created by our decorator # factory. We need to apply that binding to the decorator # wrapper function which which the decorator factory # was applied to. target_wrapper = wrapper.__get__(None, instance) else: # In this case the decorator was applied to an instance # method. # # class myclass(object): # @decorator # def decoratorclassmethod(self, wrapped, # instance, args, kwargs): # return wrapped(*args, **kwargs) # # instance = myclass() # # @instance.decoratorclassmethod # def function(): # pass # # This one is a bit strange because binding was actually # performed on the wrapper created by our decorator # factory. We need to apply that binding to the decorator # wrapper function which which the decorator factory # was applied to. target_wrapper = wrapper.__get__(instance, type(instance)) # Finally build the wrapper itself and return it. return _build(target_wrapped, target_wrapper, _enabled, adapter) # We first return our magic function wrapper here so we can # determine in what context the decorator factory was used. In # other words, it is itself a universal decorator. return _build(wrapper, _wrapper) else: # The wrapper still has not been provided, so we are just # collecting the optional keyword arguments. Return the # decorator again wrapped in a partial using the collected # arguments. return partial(decorator, enabled=enabled, adapter=adapter) # Decorator for implementing thread synchronization. It can be used as a # decorator, in which case the synchronization context is determined by # what type of function is wrapped, or it can also be used as a context # manager, where the user needs to supply the correct synchronization # context. It is also possible to supply an object which appears to be a # synchronization primitive of some sort, by virtue of having release() # and acquire() methods. In that case that will be used directly as the # synchronization primitive without creating a separate lock against the # derived or supplied context. def synchronized(wrapped): # Determine if being passed an object which is a synchronization # primitive. We can't check by type for Lock, RLock, Semaphore etc, # as the means of creating them isn't the type. Therefore use the # existence of acquire() and release() methods. This is more # extensible anyway as it allows custom synchronization mechanisms. if hasattr(wrapped, 'acquire') and hasattr(wrapped, 'release'): # We remember what the original lock is and then return a new # decorator which accesses and locks it. When returning the new # decorator we wrap it with an object proxy so we can override # the context manager methods in case it is being used to wrap # synchronized statements with a 'with' statement. lock = wrapped @decorator def _synchronized(wrapped, instance, args, kwargs): # Execute the wrapped function while the original supplied # lock is held. with lock: return wrapped(*args, **kwargs) class _PartialDecorator(CallableObjectProxy): def __enter__(self): lock.acquire() return lock def __exit__(self, *args): lock.release() return _PartialDecorator(wrapped=_synchronized) # Following only apply when the lock is being created automatically # based on the context of what was supplied. In this case we supply # a final decorator, but need to use FunctionWrapper directly as we # want to derive from it to add context manager methods in case it is # being used to wrap synchronized statements with a 'with' statement. def _synchronized_lock(context): # Attempt to retrieve the lock for the specific context. lock = vars(context).get('_synchronized_lock', None) if lock is None: # There is no existing lock defined for the context we # are dealing with so we need to create one. This needs # to be done in a way to guarantee there is only one # created, even if multiple threads try and create it at # the same time. We can't always use the setdefault() # method on the __dict__ for the context. This is the # case where the context is a class, as __dict__ is # actually a dictproxy. What we therefore do is use a # meta lock on this wrapper itself, to control the # creation and assignment of the lock attribute against # the context. meta_lock = vars(synchronized).setdefault( '_synchronized_meta_lock', Lock()) with meta_lock: # We need to check again for whether the lock we want # exists in case two threads were trying to create it # at the same time and were competing to create the # meta lock. lock = vars(context).get('_synchronized_lock', None) if lock is None: lock = RLock() setattr(context, '_synchronized_lock', lock) return lock def _synchronized_wrapper(wrapped, instance, args, kwargs): # Execute the wrapped function while the lock for the # desired context is held. If instance is None then the # wrapped function is used as the context. with _synchronized_lock(instance or wrapped): return wrapped(*args, **kwargs) class _FinalDecorator(FunctionWrapper): def __enter__(self): self._self_lock = _synchronized_lock(self.__wrapped__) self._self_lock.acquire() return self._self_lock def __exit__(self, *args): self._self_lock.release() return _FinalDecorator(wrapped=wrapped, wrapper=_synchronized_wrapper)
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/utils/wrapt/decorators.py
decorators.py
import sys import threading PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 if PY3: import importlib string_types = str, else: string_types = basestring, from .decorators import synchronized # The dictionary registering any post import hooks to be triggered once # the target module has been imported. Once a module has been imported # and the hooks fired, the list of hooks recorded against the target # module will be truncacted but the list left in the dictionary. This # acts as a flag to indicate that the module had already been imported. _post_import_hooks = {} _post_import_hooks_init = False _post_import_hooks_lock = threading.RLock() # Register a new post import hook for the target module name. This # differs from the PEP-369 implementation in that it also allows the # hook function to be specified as a string consisting of the name of # the callback in the form 'module:function'. This will result in a # proxy callback being registered which will defer loading of the # specified module containing the callback function until required. def _create_import_hook_from_string(name): def import_hook(module): module_name, function = name.split(':') attrs = function.split('.') __import__(module_name) callback = sys.modules[module_name] for attr in attrs: callback = getattr(callback, attr) return callback(module) return import_hook @synchronized(_post_import_hooks_lock) def register_post_import_hook(hook, name): # Create a deferred import hook if hook is a string name rather than # a callable function. if isinstance(hook, string_types): hook = _create_import_hook_from_string(hook) # Automatically install the import hook finder if it has not already # been installed. global _post_import_hooks_init if not _post_import_hooks_init: _post_import_hooks_init = True sys.meta_path.insert(0, ImportHookFinder()) # Determine if any prior registration of a post import hook for # the target modules has occurred and act appropriately. hooks = _post_import_hooks.get(name, None) if hooks is None: # No prior registration of post import hooks for the target # module. We need to check whether the module has already been # imported. If it has we fire the hook immediately and add an # empty list to the registry to indicate that the module has # already been imported and hooks have fired. Otherwise add # the post import hook to the registry. module = sys.modules.get(name, None) if module is not None: _post_import_hooks[name] = [] hook(module) else: _post_import_hooks[name] = [hook] elif hooks == []: # A prior registration of port import hooks for the target # module was done and the hooks already fired. Fire the hook # immediately. module = sys.modules[name] hook(module) else: # A prior registration of port import hooks for the target # module was done but the module has not yet been imported. _post_import_hooks[name].append(hook) # Register post import hooks defined as package entry points. def _create_import_hook_from_entrypoint(entrypoint): def import_hook(module): __import__(entrypoint.module_name) callback = sys.modules[entrypoint.module_name] for attr in entrypoint.attrs: callback = getattr(callback, attr) return callback(module) return import_hook def discover_post_import_hooks(group): try: import pkg_resources except ImportError: return for entrypoint in pkg_resources.iter_entry_points(group=group): callback = _create_import_hook_from_entrypoint(entrypoint) register_post_import_hook(callback, entrypoint.name) # Indicate that a module has been loaded. Any post import hooks which # were registered against the target module will be invoked. If an # exception is raised in any of the post import hooks, that will cause # the import of the target module to fail. @synchronized(_post_import_hooks_lock) def notify_module_loaded(module): name = getattr(module, '__name__', None) hooks = _post_import_hooks.get(name, None) if hooks: _post_import_hooks[name] = [] for hook in hooks: hook(module) # A custom module import finder. This intercepts attempts to import # modules and watches out for attempts to import target modules of # interest. When a module of interest is imported, then any post import # hooks which are registered will be invoked. class _ImportHookLoader: def load_module(self, fullname): module = sys.modules[fullname] notify_module_loaded(module) return module class _ImportHookChainedLoader: def __init__(self, loader): self.loader = loader def load_module(self, fullname): module = self.loader.load_module(fullname) notify_module_loaded(module) return module class ImportHookFinder: def __init__(self): self.in_progress = {} @synchronized(_post_import_hooks_lock) def find_module(self, fullname, path=None): # If the module being imported is not one we have registered # post import hooks for, we can return immediately. We will # take no further part in the importing of this module. if not fullname in _post_import_hooks: return None # When we are interested in a specific module, we will call back # into the import system a second time to defer to the import # finder that is supposed to handle the importing of the module. # We set an in progress flag for the target module so that on # the second time through we don't trigger another call back # into the import system and cause a infinite loop. if fullname in self.in_progress: return None self.in_progress[fullname] = True # Now call back into the import system again. try: if PY3: # For Python 3 we need to use find_loader() from # the importlib module. It doesn't actually # import the target module and only finds the # loader. If a loader is found, we need to return # our own loader which will then in turn call the # real loader to import the module and invoke the # post import hooks. loader = importlib.find_loader(fullname, path) if loader: return _ImportHookChainedLoader(loader) else: # For Python 2 we don't have much choice but to # call back in to __import__(). This will # actually cause the module to be imported. If no # module could be found then ImportError will be # raised. Otherwise we return a loader which # returns the already loaded module and invokes # the post import hooks. __import__(fullname) return _ImportHookLoader() finally: del self.in_progress[fullname] # Decorator for marking that a function should be called as a post # import hook when the target module is imported. def when_imported(name): def register(hook): register_post_import_hook(hook, name) return hook return register
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/utils/wrapt/importer.py
importer.py
from inspect import getargspec, ismethod import sys def getcallargs(func, *positional, **named): """Get the mapping of arguments to values. A dict is returned, with keys the function argument names (including the names of the * and ** arguments, if any), and values the respective bound values from 'positional' and 'named'.""" args, varargs, varkw, defaults = getargspec(func) f_name = func.__name__ arg2value = {} # The following closures are basically because of tuple parameter unpacking. assigned_tuple_params = [] def assign(arg, value): if isinstance(arg, str): arg2value[arg] = value else: assigned_tuple_params.append(arg) value = iter(value) for i, subarg in enumerate(arg): try: subvalue = next(value) except StopIteration: raise ValueError('need more than %d %s to unpack' % (i, 'values' if i > 1 else 'value')) assign(subarg, subvalue) try: next(value) except StopIteration: pass else: raise ValueError('too many values to unpack') def is_assigned(arg): if isinstance(arg, str): return arg in arg2value return arg in assigned_tuple_params if ismethod(func) and func.im_self is not None: # implicit 'self' (or 'cls' for classmethods) argument positional = (func.im_self,) + positional num_pos = len(positional) num_total = num_pos + len(named) num_args = len(args) num_defaults = len(defaults) if defaults else 0 for arg, value in zip(args, positional): assign(arg, value) if varargs: if num_pos > num_args: assign(varargs, positional[-(num_pos-num_args):]) else: assign(varargs, ()) elif 0 < num_args < num_pos: raise TypeError('%s() takes %s %d %s (%d given)' % ( f_name, 'at most' if defaults else 'exactly', num_args, 'arguments' if num_args > 1 else 'argument', num_total)) elif num_args == 0 and num_total: if varkw: if num_pos: # XXX: We should use num_pos, but Python also uses num_total: raise TypeError('%s() takes exactly 0 arguments ' '(%d given)' % (f_name, num_total)) else: raise TypeError('%s() takes no arguments (%d given)' % (f_name, num_total)) for arg in args: if isinstance(arg, str) and arg in named: if is_assigned(arg): raise TypeError("%s() got multiple values for keyword " "argument '%s'" % (f_name, arg)) else: assign(arg, named.pop(arg)) if defaults: # fill in any missing values with the defaults for arg, value in zip(args[-num_defaults:], defaults): if not is_assigned(arg): assign(arg, value) if varkw: assign(varkw, named) elif named: unexpected = next(iter(named)) if isinstance(unexpected, unicode): unexpected = unexpected.encode(sys.getdefaultencoding(), 'replace') raise TypeError("%s() got an unexpected keyword argument '%s'" % (f_name, unexpected)) unassigned = num_args - len([arg for arg in args if is_assigned(arg)]) if unassigned: num_required = num_args - num_defaults raise TypeError('%s() takes %s %d %s (%d given)' % ( f_name, 'at least' if defaults else 'exactly', num_required, 'arguments' if num_required > 1 else 'argument', num_total)) return arg2value
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/utils/wrapt/arguments.py
arguments.py