openrvdas.logger.utils.base_module

The biggest thing that this abstract parent class does is help with (optional) type checking of the child class' inputs and outputs. In the past an explicit, but very awkward, form of type checking was used, with child classes passing the Transform class a list of input_format and output_format specifications.

That is now deprecated in favor of using Python's type hints. Type hints should be specified for the child class' read(), transform() or write() method. Then the method can call self.can_process_record(record) to see whether it's one of the input types it can handle, and/or check_result to see if the output is as expected. If not, it can "return self.digest_record(record) to have the parent class try to deal with it:

E.g.: def transform(self, record: Union[int, str, float]): if not self.can_process_record(record): # inherited from BaseModule() return self.digest_record(record) # inherited from BaseModule() return str(record) + '+'

If no type hints are specified, can_process_record() will return True for all records except those of type "None" or "list". The logic is that digest_record() will return a None when given a None, and when given a list, will iteratively apply the transform to every element of the list and return the resulting list.

Note that the child class can explicitly call super().__init__(quiet=True) or such to initialize the type checking and set its debugging level. If it is not explicitly initialized, it will be done implicitly the first time can_process_record() or digest_record() are called, but with the default of quiet=False.

  1#!/usr/bin/env python3
  2"""
  3The biggest thing that this abstract parent class does is help with (optional)
  4type checking of the child class' inputs and outputs. In the past an explicit,
  5but very awkward, form of type checking was used, with child classes passing the
  6Transform class a list of input_format and output_format specifications.
  7
  8That is now deprecated in favor of using Python's type hints. Type hints should be
  9specified for the child class' read(), transform() or write() method. Then the method can
 10call self.can_process_record(record) to see whether it's one of the input types it
 11can handle, and/or check_result to see if the output is as expected. If not, it can
 12"return self.digest_record(record) to have the parent class try to deal with it:
 13
 14E.g.:
 15     def transform(self, record: Union[int, str, float]):
 16        if not self.can_process_record(record):  # inherited from BaseModule()
 17            return self.digest_record(record)  # inherited from BaseModule()
 18         return str(record) + '+'
 19
 20If no type hints are specified, can_process_record() will return True for all
 21records *except* those of type "None" or "list". The logic is that digest_record()
 22will return a None when given a None, and when given a list, will iteratively
 23apply the transform to every element of the list and return the resulting list.
 24
 25Note that the child class can explicitly call super().__init__(quiet=True) or such
 26to initialize the type checking and set its debugging level. If it is not explicitly
 27initialized, it will be done implicitly the first time can_process_record() or
 28digest_record() are called, but with the default of quiet=False.
 29"""
 30import inspect
 31import logging
 32import threading
 33import queue
 34from typing import get_args
 35
 36from logger.utils.das_record import DASRecord  # noqa E402
 37
 38
 39########################################
 40def get_method_type_hints(method):
 41    """
 42    When passed a method via something like
 43
 44        get_method_type_hints(self.__class__.transform)
 45
 46    return a dict of the method's type hints for the arguments
 47    and return value. E.g., if transform() is defined as:
 48
 49        def transform(self, record: int|float) -> str:
 50
 51    will return
 52
 53        {'return': (<class 'str'>),
 54         'record': (<class 'int'>, <class 'float'>)}
 55
 56    The point of this routine is to allow Transform and Writer to sanity
 57    check their inputs.
 58    """
 59    method_args = inspect.getfullargspec(method).annotations
 60    method_types = {k: tuple([value])
 61                    if isinstance(value, type)
 62                    else tuple(get_args(value))
 63                    for k, value in method_args.items()
 64                    }
 65    return method_types
 66
 67
 68################################################################################
 69class BaseModule:
 70    """
 71    Base class for OpenRVDAS Readers, Transforms and Writers.
 72
 73    Implements method for checking whether a received record is in a format
 74    that the derived class can process, and also a method for splitting a
 75    list of records into its elements and calling subclass transform() on them.
 76
 77    Starting with v0.6, BaseModule also implements "mirroring" functionality.
 78    If the optional 'mirror_to' argument is passed to the constructor (and
 79    the subclass is valid for mirroring, i.e. not a Writer), BaseModule
 80    will spin up a thread and a queue to asynchronously write a copy of
 81    every record it processes to the specified Writer.
 82
 83    The intent is to mirror the records that are handed downstream, and
 84    nothing else. Mirroring is done by wrapping the public read() or
 85    transform() method, so every call to that method mirrors what it
 86    returns. A module should therefore never call its own read() or
 87    transform() for internal work, such as processing the elements of a
 88    list or skipping ahead in a file. Put that work in a private helper
 89    method (or use digest_record()) and have the public method call it.
 90    """
 91    ############################
 92    def __init__(self, quiet=False, encoding='utf-8', encoding_errors='ignore',
 93                 mirror_to=None, *args, **kwargs):
 94        """
 95        ```
 96        quiet - if type checking should log type errors or operate silently.
 97
 98        Two additional arguments govern how records will be encoded/decoded
 99        from bytes, if desired by the Writer subclass when it calls
100        _encode_str() or _decode_bytes:
101
102        encoding - 'utf-8' by default. If empty or None, do not attempt any
103                decoding and return raw bytes. Other possible encodings are
104                listed in online documentation here:
105                https://docs.python.org/3/library/codecs.html#standard-encodings
106
107        encoding_errors - 'ignore' by default. Other error strategies are
108                'strict', 'replace', and 'backslashreplace', described here:
109                https://docs.python.org/3/howto/unicode.html#encodings
110
111        mirror_to - Optional Writer to which all records read or transformed
112                by this module (if it is a Reader or Transform) will be
113                "mirrored" (copied). Mirroring happens asynchronously via
114                a queue and background thread to minimize impact on the
115                primary data flow. Only records handed downstream should
116                be mirrored (see class docstring). Writers cannot be mirrored.
117        ```
118        """
119        if kwargs.get('input_format'):
120            logging.warning(f'Code warning: {self.__class__.__name__} use of "input_format"'
121                            'is deprecated in favor of type hints. Please see documentation'
122                            'in logger/utils/base_module.py.')
123        if kwargs.get('output_format'):
124            logging.warning(f'Code warning: {self.__class__.__name__} use of "output_format"'
125                            'is deprecated in favor of type hints. Please see documentation'
126                            'in logger/utils/base_module.py.')
127        self.quiet = quiet
128
129        # Make sure '' behaves the same as None, which is what all the
130        # docstrings say, and would be logical... but then certain things treat
131        # them differently (e.g., file.open(mode='ab', encoding='') throws
132        # ValueError: binary mode doesn't take an encoding argument)
133        if encoding == '':
134            encoding = None
135        self.encoding = encoding
136        self.encoding_errors = encoding_errors
137
138        # Handle mirroring
139        self.mirror_to = mirror_to
140        if self.mirror_to:
141            from logger.writers.writer import Writer
142            if isinstance(self, Writer):
143                logging.warning(f'Writer {self.__class__.__name__} passed "mirror_to" argument. '
144                                'Writers cannot be mirrored.')
145                self.mirror_to = None
146            elif not isinstance(self.mirror_to, Writer):
147                raise TypeError(f'mirror_to must be a Writer, not {type(self.mirror_to)}')
148            else:
149                self.mirror_queue = queue.Queue()
150                self.mirror_thread = threading.Thread(target=self._mirror_output_thread,
151                                                      daemon=True)
152                self.mirror_thread.start()
153
154                # Dynamically wrap the read() or transform() method
155                if hasattr(self, 'read'):
156                    self._original_read = self.read
157                    self.read = self._wrapped_read
158                elif hasattr(self, 'transform'):
159                    self._original_transform = self.transform
160                    self.transform = self._wrapped_transform
161
162    def _mirror_output_thread(self):
163        """Thread to pull records from the queue and write them to the
164        mirror_to writer."""
165        while True:
166            record = self.mirror_queue.get()
167            try:
168                self.mirror_to.write(record)
169            except Exception as e:
170                logging.warning(f'Error writing to mirror_to: {e}')
171
172    def _wrapped_read(self, *args, **kwargs):
173        """Wrapped version of read() that intercepts records and sends
174        them to the mirror_to writer."""
175        record = self._original_read(*args, **kwargs)
176        if record is not None:
177            self.mirror_queue.put(record)
178        return record
179
180    def _wrapped_transform(self, record, *args, **kwargs):
181        """Wrapped version of transform() that intercepts records and sends
182        them to the mirror_to writer."""
183        result = self._original_transform(record, *args, **kwargs)
184        if result is not None:
185            self.mirror_queue.put(result)
186        return result
187
188    ############################
189    def _initialize_type_hints(self, module_type, module_method):
190        """We should only get called from the _initialize_type_hints method of
191        Reader/Transform/Writer subclasses, which should fill in all parameters.
192
193        Retrieve any type hints for child read()/transform()/write() method so we
194        can check whether the type of record we've received can be parsed
195        natively or not."""
196        self.module_type = module_type
197        self.module_method = module_method
198
199        # We make stupid assumption that the input variable is called 'record'
200        method_type_hints = get_method_type_hints(self.module_method)
201        self.input_types = method_type_hints.get('record')
202        self.return_types = method_type_hints.get('return')
203
204        # logging.warning(f'input_types: {self.input_types}')
205        # logging.warning(f'return_types: {self.return_types}')
206
207        # Other things we'd want to make sure are defined.
208        self.class_name = self.__class__.__name__
209        self.initialized = True
210
211    ############################
212    def can_process_record(self, record):
213        """ Is this record in a format that the transform or writer can handle?
214
215        - If there are type hints: True if type of record is in type hints.
216        - If there are no type hints: False if None or list, otherwise True.
217
218        The logic is that if there are no type hints and we see False or
219        a list, we expect digest_record() to be called to deal with it."""
220
221        try:  # if we've not been initialized with type hints, initialize now
222            self.initialized or True
223        except AttributeError:
224            # This will call the subclass initialization, e.g.
225            # Transform._initialize_type_hints(), which will in turn call
226            # OpenRVDASModule._initialize_type_hints()
227            self._initialize_type_hints()
228
229        # Special case: we want to turn empty str records into None. By saying
230        # no, record should get punted to digest_record(), which will do the
231        # right thing.
232        if isinstance(record, str) and not len(record):
233            return False
234
235        if self.input_types:
236            return isinstance(record, self.input_types)
237
238        # If not type hints, make some judgment calls. Say "no" to None
239        # and to lists, because we'll expect that answer to trigger a
240        # call to digest_record(), which will handle them.
241        if record is None or isinstance(record, list):
242            return False
243        return True
244
245    ############################
246    def digest_record(self, record):
247        """ Try to digest record down into a format that the method can
248        handle. Typically that will mean that we've been handed a list of
249        records that we need to break into individual records."""
250
251        try:  # if we've not been initialized with type hints, initialize now
252            self.initialized or True
253        except AttributeError:
254            self._initialize_type_hints()
255
256        # Go through our litany of things that reduce to None
257        if record is None:
258            return None
259
260        if isinstance(record, str) and not len(record):
261            return None
262
263        # If it's a type the method can handle directly (though, if so,
264        # why were we called?!?
265        if self.can_process_record(record) and not self.quiet:
266            logging.warning(f'{self.class_name}: digest_record() called unnecessarily.')
267            logging.warning(f'Can process {self.input_types}; received {type(record)}: {record}')
268            return self.module_method(record)
269
270        # We know how to deal with it if it's a list: Apply to components,
271        # stripping out any None's
272        if isinstance(record, list):
273            result = [self.module_method(self, r) for r in record if r is not None]
274            return [r for r in result if r is not None]  # remove Nones
275
276        # Is record a number we can convert to a string?
277        if str in self.input_types and isinstance(record, (int, float)):
278            return str(record)
279
280        # If it's a DASRecord, serialize it as JSON
281        if str in self.input_types and isinstance(record, DASRecord):
282            return record.as_json()
283
284        # If we don't know how to deal with it
285        if not self.quiet:
286            logging.warning(f'Unable to convert record to format "{self.class_name}" can process')
287            logging.warning(f'Must be instance or list of {self.input_types}')
288            logging.warning(f'Received {type(record)}: {record}')
289        return None
290
291    ############################
292    def _unescape_str(self, the_str):
293        """Unescape a string by encoding it to bytes, then unescaping when we
294        decode it. Ugly.
295        """
296        if not self.encoding:
297            return the_str
298
299        encoded = the_str.encode(encoding=self.encoding, errors=self.encoding_errors)
300        return encoded.decode('unicode_escape')
301
302    ############################
303    def _encode_str(self, the_str, unescape=False):
304        """Encode a string to bytes, optionally unescaping things like \n and \r.
305        Unescaping requires ugly convolutions of encoding, then decoding while we
306        escape things, then encoding a second time.
307        """
308        if not self.encoding:
309            return the_str
310        if unescape:
311            the_str = self._unescape_str(the_str)
312        return the_str.encode(encoding=self.encoding, errors=self.encoding_errors)
313
314    ############################
315    def _decode_bytes(self, record, allow_empty: bool = False):
316        """Decode a record from bytes to str, if we have an encoding specified."""
317        if record is None:
318            return None
319
320        if not record and not allow_empty:  # if it's an empty record but not None
321            return None
322
323        if not self.encoding:
324            return record
325
326        if self.encoding == 'hex':
327            try:
328                r = record.hex()
329                return r
330            except Exception as e:
331                logging.warning('Error decoding string "%s" from encoding "%s": %s',
332                                record, self.encoding, str(e))
333                return None
334
335        try:
336            return record.decode(encoding=self.encoding,
337                                 errors=self.encoding_errors)
338        except UnicodeDecodeError as e:
339            logging.warning('Error decoding string "%s" from encoding "%s": %s',
340                            record, self.encoding, str(e))
341            return None
def get_method_type_hints(method):
41def get_method_type_hints(method):
42    """
43    When passed a method via something like
44
45        get_method_type_hints(self.__class__.transform)
46
47    return a dict of the method's type hints for the arguments
48    and return value. E.g., if transform() is defined as:
49
50        def transform(self, record: int|float) -> str:
51
52    will return
53
54        {'return': (<class 'str'>),
55         'record': (<class 'int'>, <class 'float'>)}
56
57    The point of this routine is to allow Transform and Writer to sanity
58    check their inputs.
59    """
60    method_args = inspect.getfullargspec(method).annotations
61    method_types = {k: tuple([value])
62                    if isinstance(value, type)
63                    else tuple(get_args(value))
64                    for k, value in method_args.items()
65                    }
66    return method_types

When passed a method via something like

get_method_type_hints(self.__class__.transform)

return a dict of the method's type hints for the arguments and return value. E.g., if transform() is defined as:

def transform(self, record: int|float) -> str:

will return

{'return': (<class 'str'>),
 'record': (<class 'int'>, <class 'float'>)}

The point of this routine is to allow Transform and Writer to sanity check their inputs.

class BaseModule:
 70class BaseModule:
 71    """
 72    Base class for OpenRVDAS Readers, Transforms and Writers.
 73
 74    Implements method for checking whether a received record is in a format
 75    that the derived class can process, and also a method for splitting a
 76    list of records into its elements and calling subclass transform() on them.
 77
 78    Starting with v0.6, BaseModule also implements "mirroring" functionality.
 79    If the optional 'mirror_to' argument is passed to the constructor (and
 80    the subclass is valid for mirroring, i.e. not a Writer), BaseModule
 81    will spin up a thread and a queue to asynchronously write a copy of
 82    every record it processes to the specified Writer.
 83
 84    The intent is to mirror the records that are handed downstream, and
 85    nothing else. Mirroring is done by wrapping the public read() or
 86    transform() method, so every call to that method mirrors what it
 87    returns. A module should therefore never call its own read() or
 88    transform() for internal work, such as processing the elements of a
 89    list or skipping ahead in a file. Put that work in a private helper
 90    method (or use digest_record()) and have the public method call it.
 91    """
 92    ############################
 93    def __init__(self, quiet=False, encoding='utf-8', encoding_errors='ignore',
 94                 mirror_to=None, *args, **kwargs):
 95        """
 96        ```
 97        quiet - if type checking should log type errors or operate silently.
 98
 99        Two additional arguments govern how records will be encoded/decoded
100        from bytes, if desired by the Writer subclass when it calls
101        _encode_str() or _decode_bytes:
102
103        encoding - 'utf-8' by default. If empty or None, do not attempt any
104                decoding and return raw bytes. Other possible encodings are
105                listed in online documentation here:
106                https://docs.python.org/3/library/codecs.html#standard-encodings
107
108        encoding_errors - 'ignore' by default. Other error strategies are
109                'strict', 'replace', and 'backslashreplace', described here:
110                https://docs.python.org/3/howto/unicode.html#encodings
111
112        mirror_to - Optional Writer to which all records read or transformed
113                by this module (if it is a Reader or Transform) will be
114                "mirrored" (copied). Mirroring happens asynchronously via
115                a queue and background thread to minimize impact on the
116                primary data flow. Only records handed downstream should
117                be mirrored (see class docstring). Writers cannot be mirrored.
118        ```
119        """
120        if kwargs.get('input_format'):
121            logging.warning(f'Code warning: {self.__class__.__name__} use of "input_format"'
122                            'is deprecated in favor of type hints. Please see documentation'
123                            'in logger/utils/base_module.py.')
124        if kwargs.get('output_format'):
125            logging.warning(f'Code warning: {self.__class__.__name__} use of "output_format"'
126                            'is deprecated in favor of type hints. Please see documentation'
127                            'in logger/utils/base_module.py.')
128        self.quiet = quiet
129
130        # Make sure '' behaves the same as None, which is what all the
131        # docstrings say, and would be logical... but then certain things treat
132        # them differently (e.g., file.open(mode='ab', encoding='') throws
133        # ValueError: binary mode doesn't take an encoding argument)
134        if encoding == '':
135            encoding = None
136        self.encoding = encoding
137        self.encoding_errors = encoding_errors
138
139        # Handle mirroring
140        self.mirror_to = mirror_to
141        if self.mirror_to:
142            from logger.writers.writer import Writer
143            if isinstance(self, Writer):
144                logging.warning(f'Writer {self.__class__.__name__} passed "mirror_to" argument. '
145                                'Writers cannot be mirrored.')
146                self.mirror_to = None
147            elif not isinstance(self.mirror_to, Writer):
148                raise TypeError(f'mirror_to must be a Writer, not {type(self.mirror_to)}')
149            else:
150                self.mirror_queue = queue.Queue()
151                self.mirror_thread = threading.Thread(target=self._mirror_output_thread,
152                                                      daemon=True)
153                self.mirror_thread.start()
154
155                # Dynamically wrap the read() or transform() method
156                if hasattr(self, 'read'):
157                    self._original_read = self.read
158                    self.read = self._wrapped_read
159                elif hasattr(self, 'transform'):
160                    self._original_transform = self.transform
161                    self.transform = self._wrapped_transform
162
163    def _mirror_output_thread(self):
164        """Thread to pull records from the queue and write them to the
165        mirror_to writer."""
166        while True:
167            record = self.mirror_queue.get()
168            try:
169                self.mirror_to.write(record)
170            except Exception as e:
171                logging.warning(f'Error writing to mirror_to: {e}')
172
173    def _wrapped_read(self, *args, **kwargs):
174        """Wrapped version of read() that intercepts records and sends
175        them to the mirror_to writer."""
176        record = self._original_read(*args, **kwargs)
177        if record is not None:
178            self.mirror_queue.put(record)
179        return record
180
181    def _wrapped_transform(self, record, *args, **kwargs):
182        """Wrapped version of transform() that intercepts records and sends
183        them to the mirror_to writer."""
184        result = self._original_transform(record, *args, **kwargs)
185        if result is not None:
186            self.mirror_queue.put(result)
187        return result
188
189    ############################
190    def _initialize_type_hints(self, module_type, module_method):
191        """We should only get called from the _initialize_type_hints method of
192        Reader/Transform/Writer subclasses, which should fill in all parameters.
193
194        Retrieve any type hints for child read()/transform()/write() method so we
195        can check whether the type of record we've received can be parsed
196        natively or not."""
197        self.module_type = module_type
198        self.module_method = module_method
199
200        # We make stupid assumption that the input variable is called 'record'
201        method_type_hints = get_method_type_hints(self.module_method)
202        self.input_types = method_type_hints.get('record')
203        self.return_types = method_type_hints.get('return')
204
205        # logging.warning(f'input_types: {self.input_types}')
206        # logging.warning(f'return_types: {self.return_types}')
207
208        # Other things we'd want to make sure are defined.
209        self.class_name = self.__class__.__name__
210        self.initialized = True
211
212    ############################
213    def can_process_record(self, record):
214        """ Is this record in a format that the transform or writer can handle?
215
216        - If there are type hints: True if type of record is in type hints.
217        - If there are no type hints: False if None or list, otherwise True.
218
219        The logic is that if there are no type hints and we see False or
220        a list, we expect digest_record() to be called to deal with it."""
221
222        try:  # if we've not been initialized with type hints, initialize now
223            self.initialized or True
224        except AttributeError:
225            # This will call the subclass initialization, e.g.
226            # Transform._initialize_type_hints(), which will in turn call
227            # OpenRVDASModule._initialize_type_hints()
228            self._initialize_type_hints()
229
230        # Special case: we want to turn empty str records into None. By saying
231        # no, record should get punted to digest_record(), which will do the
232        # right thing.
233        if isinstance(record, str) and not len(record):
234            return False
235
236        if self.input_types:
237            return isinstance(record, self.input_types)
238
239        # If not type hints, make some judgment calls. Say "no" to None
240        # and to lists, because we'll expect that answer to trigger a
241        # call to digest_record(), which will handle them.
242        if record is None or isinstance(record, list):
243            return False
244        return True
245
246    ############################
247    def digest_record(self, record):
248        """ Try to digest record down into a format that the method can
249        handle. Typically that will mean that we've been handed a list of
250        records that we need to break into individual records."""
251
252        try:  # if we've not been initialized with type hints, initialize now
253            self.initialized or True
254        except AttributeError:
255            self._initialize_type_hints()
256
257        # Go through our litany of things that reduce to None
258        if record is None:
259            return None
260
261        if isinstance(record, str) and not len(record):
262            return None
263
264        # If it's a type the method can handle directly (though, if so,
265        # why were we called?!?
266        if self.can_process_record(record) and not self.quiet:
267            logging.warning(f'{self.class_name}: digest_record() called unnecessarily.')
268            logging.warning(f'Can process {self.input_types}; received {type(record)}: {record}')
269            return self.module_method(record)
270
271        # We know how to deal with it if it's a list: Apply to components,
272        # stripping out any None's
273        if isinstance(record, list):
274            result = [self.module_method(self, r) for r in record if r is not None]
275            return [r for r in result if r is not None]  # remove Nones
276
277        # Is record a number we can convert to a string?
278        if str in self.input_types and isinstance(record, (int, float)):
279            return str(record)
280
281        # If it's a DASRecord, serialize it as JSON
282        if str in self.input_types and isinstance(record, DASRecord):
283            return record.as_json()
284
285        # If we don't know how to deal with it
286        if not self.quiet:
287            logging.warning(f'Unable to convert record to format "{self.class_name}" can process')
288            logging.warning(f'Must be instance or list of {self.input_types}')
289            logging.warning(f'Received {type(record)}: {record}')
290        return None
291
292    ############################
293    def _unescape_str(self, the_str):
294        """Unescape a string by encoding it to bytes, then unescaping when we
295        decode it. Ugly.
296        """
297        if not self.encoding:
298            return the_str
299
300        encoded = the_str.encode(encoding=self.encoding, errors=self.encoding_errors)
301        return encoded.decode('unicode_escape')
302
303    ############################
304    def _encode_str(self, the_str, unescape=False):
305        """Encode a string to bytes, optionally unescaping things like \n and \r.
306        Unescaping requires ugly convolutions of encoding, then decoding while we
307        escape things, then encoding a second time.
308        """
309        if not self.encoding:
310            return the_str
311        if unescape:
312            the_str = self._unescape_str(the_str)
313        return the_str.encode(encoding=self.encoding, errors=self.encoding_errors)
314
315    ############################
316    def _decode_bytes(self, record, allow_empty: bool = False):
317        """Decode a record from bytes to str, if we have an encoding specified."""
318        if record is None:
319            return None
320
321        if not record and not allow_empty:  # if it's an empty record but not None
322            return None
323
324        if not self.encoding:
325            return record
326
327        if self.encoding == 'hex':
328            try:
329                r = record.hex()
330                return r
331            except Exception as e:
332                logging.warning('Error decoding string "%s" from encoding "%s": %s',
333                                record, self.encoding, str(e))
334                return None
335
336        try:
337            return record.decode(encoding=self.encoding,
338                                 errors=self.encoding_errors)
339        except UnicodeDecodeError as e:
340            logging.warning('Error decoding string "%s" from encoding "%s": %s',
341                            record, self.encoding, str(e))
342            return None

Base class for OpenRVDAS Readers, Transforms and Writers.

Implements method for checking whether a received record is in a format that the derived class can process, and also a method for splitting a list of records into its elements and calling subclass transform() on them.

Starting with v0.6, BaseModule also implements "mirroring" functionality. If the optional 'mirror_to' argument is passed to the constructor (and the subclass is valid for mirroring, i.e. not a Writer), BaseModule will spin up a thread and a queue to asynchronously write a copy of every record it processes to the specified Writer.

The intent is to mirror the records that are handed downstream, and nothing else. Mirroring is done by wrapping the public read() or transform() method, so every call to that method mirrors what it returns. A module should therefore never call its own read() or transform() for internal work, such as processing the elements of a list or skipping ahead in a file. Put that work in a private helper method (or use digest_record()) and have the public method call it.

BaseModule( quiet=False, encoding='utf-8', encoding_errors='ignore', mirror_to=None, *args, **kwargs)
 93    def __init__(self, quiet=False, encoding='utf-8', encoding_errors='ignore',
 94                 mirror_to=None, *args, **kwargs):
 95        """
 96        ```
 97        quiet - if type checking should log type errors or operate silently.
 98
 99        Two additional arguments govern how records will be encoded/decoded
100        from bytes, if desired by the Writer subclass when it calls
101        _encode_str() or _decode_bytes:
102
103        encoding - 'utf-8' by default. If empty or None, do not attempt any
104                decoding and return raw bytes. Other possible encodings are
105                listed in online documentation here:
106                https://docs.python.org/3/library/codecs.html#standard-encodings
107
108        encoding_errors - 'ignore' by default. Other error strategies are
109                'strict', 'replace', and 'backslashreplace', described here:
110                https://docs.python.org/3/howto/unicode.html#encodings
111
112        mirror_to - Optional Writer to which all records read or transformed
113                by this module (if it is a Reader or Transform) will be
114                "mirrored" (copied). Mirroring happens asynchronously via
115                a queue and background thread to minimize impact on the
116                primary data flow. Only records handed downstream should
117                be mirrored (see class docstring). Writers cannot be mirrored.
118        ```
119        """
120        if kwargs.get('input_format'):
121            logging.warning(f'Code warning: {self.__class__.__name__} use of "input_format"'
122                            'is deprecated in favor of type hints. Please see documentation'
123                            'in logger/utils/base_module.py.')
124        if kwargs.get('output_format'):
125            logging.warning(f'Code warning: {self.__class__.__name__} use of "output_format"'
126                            'is deprecated in favor of type hints. Please see documentation'
127                            'in logger/utils/base_module.py.')
128        self.quiet = quiet
129
130        # Make sure '' behaves the same as None, which is what all the
131        # docstrings say, and would be logical... but then certain things treat
132        # them differently (e.g., file.open(mode='ab', encoding='') throws
133        # ValueError: binary mode doesn't take an encoding argument)
134        if encoding == '':
135            encoding = None
136        self.encoding = encoding
137        self.encoding_errors = encoding_errors
138
139        # Handle mirroring
140        self.mirror_to = mirror_to
141        if self.mirror_to:
142            from logger.writers.writer import Writer
143            if isinstance(self, Writer):
144                logging.warning(f'Writer {self.__class__.__name__} passed "mirror_to" argument. '
145                                'Writers cannot be mirrored.')
146                self.mirror_to = None
147            elif not isinstance(self.mirror_to, Writer):
148                raise TypeError(f'mirror_to must be a Writer, not {type(self.mirror_to)}')
149            else:
150                self.mirror_queue = queue.Queue()
151                self.mirror_thread = threading.Thread(target=self._mirror_output_thread,
152                                                      daemon=True)
153                self.mirror_thread.start()
154
155                # Dynamically wrap the read() or transform() method
156                if hasattr(self, 'read'):
157                    self._original_read = self.read
158                    self.read = self._wrapped_read
159                elif hasattr(self, 'transform'):
160                    self._original_transform = self.transform
161                    self.transform = self._wrapped_transform
quiet - if type checking should log type errors or operate silently.

Two additional arguments govern how records will be encoded/decoded
from bytes, if desired by the Writer subclass when it calls
_encode_str() or _decode_bytes:

encoding - 'utf-8' by default. If empty or None, do not attempt any
        decoding and return raw bytes. Other possible encodings are
        listed in online documentation here:
        https://docs.python.org/3/library/codecs.html#standard-encodings

encoding_errors - 'ignore' by default. Other error strategies are
        'strict', 'replace', and 'backslashreplace', described here:
        https://docs.python.org/3/howto/unicode.html#encodings

mirror_to - Optional Writer to which all records read or transformed
        by this module (if it is a Reader or Transform) will be
        "mirrored" (copied). Mirroring happens asynchronously via
        a queue and background thread to minimize impact on the
        primary data flow. Only records handed downstream should
        be mirrored (see class docstring). Writers cannot be mirrored.
quiet
encoding
encoding_errors
mirror_to
def can_process_record(self, record):
213    def can_process_record(self, record):
214        """ Is this record in a format that the transform or writer can handle?
215
216        - If there are type hints: True if type of record is in type hints.
217        - If there are no type hints: False if None or list, otherwise True.
218
219        The logic is that if there are no type hints and we see False or
220        a list, we expect digest_record() to be called to deal with it."""
221
222        try:  # if we've not been initialized with type hints, initialize now
223            self.initialized or True
224        except AttributeError:
225            # This will call the subclass initialization, e.g.
226            # Transform._initialize_type_hints(), which will in turn call
227            # OpenRVDASModule._initialize_type_hints()
228            self._initialize_type_hints()
229
230        # Special case: we want to turn empty str records into None. By saying
231        # no, record should get punted to digest_record(), which will do the
232        # right thing.
233        if isinstance(record, str) and not len(record):
234            return False
235
236        if self.input_types:
237            return isinstance(record, self.input_types)
238
239        # If not type hints, make some judgment calls. Say "no" to None
240        # and to lists, because we'll expect that answer to trigger a
241        # call to digest_record(), which will handle them.
242        if record is None or isinstance(record, list):
243            return False
244        return True

Is this record in a format that the transform or writer can handle?

  • If there are type hints: True if type of record is in type hints.
  • If there are no type hints: False if None or list, otherwise True.

The logic is that if there are no type hints and we see False or a list, we expect digest_record() to be called to deal with it.

def digest_record(self, record):
247    def digest_record(self, record):
248        """ Try to digest record down into a format that the method can
249        handle. Typically that will mean that we've been handed a list of
250        records that we need to break into individual records."""
251
252        try:  # if we've not been initialized with type hints, initialize now
253            self.initialized or True
254        except AttributeError:
255            self._initialize_type_hints()
256
257        # Go through our litany of things that reduce to None
258        if record is None:
259            return None
260
261        if isinstance(record, str) and not len(record):
262            return None
263
264        # If it's a type the method can handle directly (though, if so,
265        # why were we called?!?
266        if self.can_process_record(record) and not self.quiet:
267            logging.warning(f'{self.class_name}: digest_record() called unnecessarily.')
268            logging.warning(f'Can process {self.input_types}; received {type(record)}: {record}')
269            return self.module_method(record)
270
271        # We know how to deal with it if it's a list: Apply to components,
272        # stripping out any None's
273        if isinstance(record, list):
274            result = [self.module_method(self, r) for r in record if r is not None]
275            return [r for r in result if r is not None]  # remove Nones
276
277        # Is record a number we can convert to a string?
278        if str in self.input_types and isinstance(record, (int, float)):
279            return str(record)
280
281        # If it's a DASRecord, serialize it as JSON
282        if str in self.input_types and isinstance(record, DASRecord):
283            return record.as_json()
284
285        # If we don't know how to deal with it
286        if not self.quiet:
287            logging.warning(f'Unable to convert record to format "{self.class_name}" can process')
288            logging.warning(f'Must be instance or list of {self.input_types}')
289            logging.warning(f'Received {type(record)}: {record}')
290        return None

Try to digest record down into a format that the method can handle. Typically that will mean that we've been handed a list of records that we need to break into individual records.