File: utils.py

package info (click to toggle)
python-rq 2.6-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,580 kB
  • sloc: python: 13,878; makefile: 22; sh: 19
file content (557 lines) | stat: -rw-r--r-- 17,591 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
"""
Miscellaneous helper functions.

The formatter for ANSI colored console output is heavily based on Pygments
terminal colorizing code, originally by Georg Brandl.
"""

import calendar
import datetime
import importlib
import inspect
import logging
import numbers
import os
import warnings
from collections.abc import Generator, Iterable, Sequence

# TODO: Change import path to "collections.abc" after we stop supporting Python 3.8
from typing import (
    TYPE_CHECKING,
    Any,
    Callable,
    Optional,
    TypeVar,
    Union,
    overload,
)

from redis.exceptions import ResponseError

from .exceptions import TimeoutFormatError

if TYPE_CHECKING:
    from redis import Redis

    from .job import Job
    from .queue import Queue
    from .worker import Worker


_T = TypeVar('_T')
_O = TypeVar('_O', bound=object)
ObjOrStr = Union[_O, str]


logger = logging.getLogger(__name__)


def resolve_function_reference(func) -> tuple[Any, str]:
    """Resolve a function reference into instance and function name components.

    Args:
        func: The function reference to resolve - can be a method, function,
             builtin, string path, or callable class instance.

    Returns:
        A tuple of (instance, func_name) where:
        - instance: The object instance (for methods/callable instances) or None
        - func_name: The string representation of the function name/path

    Raises:
        TypeError: If func is not a valid callable or string reference.
    """
    if inspect.ismethod(func):
        return func.__self__, func.__name__
    elif inspect.isfunction(func) or inspect.isbuiltin(func):
        return None, f'{func.__module__}.{func.__qualname__}'
    elif isinstance(func, str):
        return None, as_text(func)
    elif not inspect.isclass(func) and hasattr(func, '__call__'):  # a callable class instance
        return func, '__call__'
    else:
        raise TypeError(f'Expected a callable or a string, but got: {func}')


def compact(lst: Iterable[Optional[_T]]) -> list[_T]:
    """Excludes `None` values from a list-like object.

    Args:
        lst (list): A list (or list-like) object

    Returns:
        object (list): The list without None values
    """
    return [item for item in lst if item is not None]


def as_text(v: Union[bytes, str]) -> str:
    """Converts a bytes value to a string using `utf-8`.

    Args:
        v (Union[bytes, str]): The value (bytes or string)

    Raises:
        ValueError: If the value is not bytes or string

    Returns:
        value (str): The decoded string
    """
    if isinstance(v, bytes):
        return v.decode('utf-8')
    elif isinstance(v, str):
        return v
    else:
        raise ValueError('Unknown type %r' % type(v))


def decode_redis_hash(h: dict[Union[bytes, str], Any], *, decode_values: bool = False) -> dict[str, Any]:
    """Decodes the Redis hash, ensuring that keys are strings
    Most importantly, decodes bytes strings, ensuring the dict has str keys.

    Args:
        h (Dict[Any, Any]): The Redis hash
        decode_values (bool): If True, also decode values to strings using as_text(). Defaults to False.

    Returns:
        Dict[str, Any]: The decoded Redis data (Dictionary)
        When decode_values=True, returns Dict[str, str]
    """
    if decode_values:
        return dict((as_text(k), as_text(v)) for k, v in h.items())
    return dict((as_text(k), v) for k, v in h.items())


def import_attribute(name: str) -> Callable[..., Any]:
    """Returns an attribute from a dotted path name. Example: `path.to.func`.

    When the attribute we look for is a staticmethod, module name in its
    dotted path is not the last-before-end word

    E.g.: package_a.package_b.module_a.ClassA.my_static_method

    Thus we remove the bits from the end of the name until we can import it

    Args:
        name (str): The name (reference) to the path.

    Raises:
        ValueError: If no module is found or invalid attribute name.

    Returns:
        Any: An attribute (normally a Callable)
    """
    name_bits = name.split('.')
    module_name_bits, attribute_bits = name_bits[:-1], [name_bits[-1]]
    module = None
    while len(module_name_bits):
        try:
            module_name = '.'.join(module_name_bits)
            module = importlib.import_module(module_name)
            break
        except ImportError:
            attribute_bits.insert(0, module_name_bits.pop())

    if module is None:
        # maybe it's a builtin
        try:
            return __builtins__[name]  # type: ignore[index]
        except KeyError:
            raise ValueError(f'Invalid attribute name: {name}')

    attribute_name = '.'.join(attribute_bits)
    if hasattr(module, attribute_name):
        return getattr(module, attribute_name)
    # staticmethods
    attribute_name = attribute_bits.pop()
    attribute_owner_name = '.'.join(attribute_bits)
    try:
        attribute_owner = getattr(module, attribute_owner_name)
    except:  # noqa
        raise ValueError('Invalid attribute name: %s' % attribute_name)

    if not hasattr(attribute_owner, attribute_name):
        raise ValueError('Invalid attribute name: %s' % name)
    return getattr(attribute_owner, attribute_name)


def import_worker_class(name: str) -> type['Worker']:
    """Import a worker class from a dotted path name."""
    cls = import_attribute(name)

    if not isinstance(cls, type):
        raise ValueError(f'Invalid worker class: {name}')

    from .worker import Worker

    if not issubclass(cls, Worker):
        raise ValueError(f'Invalid worker class: {name}')

    return cls


def import_job_class(name: str) -> type['Job']:
    """Import a job class from a dotted path name."""
    cls = import_attribute(name)

    if not isinstance(cls, type):
        raise ValueError(f'Invalid job class: {name}')

    from .job import Job

    if not issubclass(cls, Job):
        raise ValueError(f'Invalid job class: {name}')

    return cls


def import_queue_class(name: str) -> type['Queue']:
    """Import a queue class from a dotted path name."""
    cls = import_attribute(name)

    if not isinstance(cls, type):
        raise ValueError(f'Invalid queue class: {name}')

    from .queue import Queue

    if not issubclass(cls, Queue):
        raise ValueError(f'Invalid queue class: {name}')

    return cls


def normalize_config_path(config_path: str) -> str:
    """Normalize configuration path to dotted module path format.

    Converts file paths like 'directory/config_file.py' or 'directory.config_file'
    to dotted module paths like 'directory.config_file' for use with importlib.import_module().

    Args:
        config_path: Either a file path (e.g., 'app/cron_config.py', 'app/cron_config')
                    or a dotted module path (e.g., 'app.cron_config')

    Returns:
        A dotted module path suitable for importlib.import_module()

    Examples:
        normalize_config_path('app/cron_config.py') -> 'app.cron_config'
        normalize_config_path('app/cron_config') -> 'app.cron_config'
        normalize_config_path('app.cron_config') -> 'app.cron_config'
        normalize_config_path('/abs/path/to/config.py') -> 'abs.path.to.config'
    """
    # Check if it's already a dotted path (no path separators and no .py extension)
    is_file_path = os.path.sep in config_path or config_path.endswith('.py')

    if not is_file_path:
        # Already a dotted module path, return as-is
        return config_path

    # Convert file path to dotted module path
    normalized = config_path

    # Remove .py extension if present
    if normalized.endswith('.py'):
        normalized = normalized[:-3]

    # Handle absolute paths by removing leading separator
    if normalized.startswith(os.path.sep):
        normalized = normalized[1:]

    # Replace path separators with dots
    normalized = normalized.replace(os.path.sep, '.')

    return normalized


def validate_absolute_path(file_path: str) -> str:
    """Validate that an absolute file path exists and points to a file.

    Args:
        file_path: The absolute file path to validate

    Returns:
        The same file path if validation passes (for chaining)

    Raises:
        FileNotFoundError: If the file does not exist
        IsADirectoryError: If the path points to a directory instead of a file

    Examples:
        validate_absolute_path('/path/to/config.py')  # Returns '/path/to/config.py'
        validate_absolute_path('/path/to/missing.py')  # Raises FileNotFoundError
        validate_absolute_path('/path/to/directory')   # Raises IsADirectoryError
    """
    if not os.path.exists(file_path):
        raise FileNotFoundError(f"Configuration file not found at '{file_path}'")

    if not os.path.isfile(file_path):
        raise IsADirectoryError(f"Configuration path points to a directory, not a file: '{file_path}'")

    return file_path


def now() -> datetime.datetime:
    """Return now in UTC"""
    return datetime.datetime.now(datetime.timezone.utc)


_TIMESTAMP_FORMAT = '%Y-%m-%dT%H:%M:%S.%fZ'


def utcformat(dt: datetime.datetime) -> str:
    return dt.strftime(as_text(_TIMESTAMP_FORMAT))


def utcparse(string: str) -> datetime.datetime:
    try:
        parsed = datetime.datetime.strptime(string, _TIMESTAMP_FORMAT)
    except ValueError:
        # This catches any jobs remain with old datetime format
        parsed = datetime.datetime.strptime(string, '%Y-%m-%dT%H:%M:%SZ')
    return parsed.replace(tzinfo=datetime.timezone.utc)


def is_nonstring_iterable(obj: Any) -> bool:
    """Returns whether the obj is an iterable, but not a string

    Args:
        obj (Any): _description_

    Returns:
        bool: _description_
    """
    return isinstance(obj, Iterable) and not isinstance(obj, str)


@overload
def ensure_job_list(obj: str) -> list[str]: ...
@overload
def ensure_job_list(obj: 'Job') -> list['Job']: ...
@overload
def ensure_job_list(obj: Union['Job', str, Sequence[Union['Job', str]]]) -> list[Union['Job', str]]: ...
@overload
def ensure_job_list(obj: Iterable[_O]) -> list[_O]: ...
@overload
def ensure_job_list(obj: _O) -> list[_O]: ...


def ensure_job_list(obj):
    """When passed an iterable of objects, convert to list, otherwise, it returns
    a list with just that object in it.

    Args:
        obj (Any): _description_

    returns:
        List: _description_
    """
    # Note: To reuse is_nonstring_iterable, we need TypeGuard of Python 3.10+,
    # but we are dragged by Python 3.8.
    return list(obj) if isinstance(obj, Iterable) and not isinstance(obj, str) else [obj]


def current_timestamp() -> int:
    """Returns current UTC timestamp

    Returns:
        int: _description_
    """
    return calendar.timegm(now().utctimetuple())


def backend_class(holder, default_name, override=None) -> type:
    """Get a backend class using its default attribute name or an override

    Args:
        holder (_type_): _description_
        default_name (_type_): _description_
        override (_type_, optional): _description_. Defaults to None.

    Returns:
        _type_: _description_
    """
    if override is None:
        return getattr(holder, default_name)
    elif isinstance(override, str):
        return import_attribute(override)  # type: ignore[return-value]
    else:
        return override


def str_to_date(date_str: Union[bytes, str]) -> datetime.datetime:
    if not date_str:
        raise ValueError('Empty string or bytestring provided')
    else:
        if isinstance(date_str, bytes):
            return utcparse(date_str.decode())
        else:
            return utcparse(date_str)


def parse_timeout(timeout: Optional[Union[int, float, str]]) -> Optional[int]:
    """Transfer all kinds of timeout format to an integer representing seconds"""
    if not isinstance(timeout, numbers.Integral) and timeout is not None:
        try:
            timeout = int(timeout)
            return timeout
        except ValueError:
            assert isinstance(timeout, str)
            digit, unit = timeout[:-1], (timeout[-1:]).lower()
            unit_second = {'d': 86400, 'h': 3600, 'm': 60, 's': 1}
            try:
                timeout = int(digit) * unit_second[unit]
            except (ValueError, KeyError):
                raise TimeoutFormatError(
                    'Timeout must be an integer or a string representing an integer, or '
                    'a string with format: digits + unit, unit can be "d", "h", "m", "s", '
                    'such as "1h", "23m".'
                )

    return int(timeout) if timeout is not None else None


def get_version(connection: 'Redis') -> tuple[int, int, int]:
    """
    Returns tuple of Redis server version.
    This function also correctly handles 4 digit redis server versions.

    Args:
        connection (Redis): The Redis connection.

    Returns:
        version (Tuple[int, int, int]): A tuple representing the semantic versioning format (eg. (5, 0, 9))
    """
    try:
        # Getting the connection info for each job tanks performance, we can cache it on the connection object
        if not getattr(connection, '__rq_redis_server_version', None):
            # Cast the version string to a tuple of integers. Some Redis implementations may return a float.
            version_str = str(connection.info('server')['redis_version'])
            version_parts = [int(i) for i in version_str.split('.')[:3]]
            # Ensure the version tuple has exactly three elements
            while len(version_parts) < 3:
                version_parts.append(0)
            setattr(
                connection,
                '__rq_redis_server_version',
                tuple(version_parts),
            )
        return getattr(connection, '__rq_redis_server_version')
    except ResponseError:  # fakeredis doesn't implement Redis' INFO command
        return (5, 0, 9)


def ceildiv(a, b):
    """Ceiling division. Returns the ceiling of the quotient of a division operation

    Args:
        a (_type_): _description_
        b (_type_): _description_

    Returns:
        _type_: _description_
    """
    return -(-a // b)


def split_list(a_list: Sequence[_T], segment_size: int) -> Generator[Sequence[_T], None, None]:
    """Splits a list into multiple smaller lists having size `segment_size`

    Args:
        a_list (Sequence[Any]): A sequence to split
        segment_size (int): The segment size to split into

    Yields:
        list: The splitted listed
    """
    for i in range(0, len(a_list), segment_size):
        yield a_list[i : i + segment_size]


def truncate_long_string(data: str, max_length: Optional[int] = None) -> str:
    """Truncate arguments with representation longer than max_length

    Args:
        data (str): The data to truncate
        max_length (Optional[int], optional): The max length. Defaults to None.

    Returns:
        truncated (str): The truncated string
    """
    if max_length is None:
        return data
    return (data[:max_length] + '...') if len(data) > max_length else data


def get_call_string(
    func_name: Optional[str], args: Any, kwargs: dict[Any, Any], max_length: Optional[int] = None
) -> Optional[str]:
    """
    Returns a string representation of the call, formatted as a regular
    Python function invocation statement. If max_length is not None, truncate
    arguments with representation longer than max_length.

    Args:
        func_name (str): The function name
        args (Any): The function arguments
        kwargs (Dict[Any, Any]): The function kwargs
        max_length (int, optional): The max length. Defaults to None.

    Returns:
        str: A string representation of the function call.
    """
    if func_name is None:
        return None

    arg_list = [as_text(truncate_long_string(repr(arg), max_length)) for arg in args]

    list_kwargs = [f'{k}={as_text(truncate_long_string(repr(v), max_length))}' for k, v in kwargs.items()]
    arg_list += sorted(list_kwargs)
    args = ', '.join(arg_list)

    return f'{func_name}({args})'


def parse_names(queues_or_names: Iterable[Union[str, 'Queue']]) -> list[str]:
    """Given a iterable  of strings or queues, returns queue names"""
    from .queue import Queue

    names = []
    for queue_or_name in queues_or_names:
        if isinstance(queue_or_name, Queue):
            names.append(queue_or_name.name)
        else:
            names.append(str(queue_or_name))
    return names


def get_connection_from_queues(queues_or_names: Iterable[Union[str, 'Queue']]) -> Optional['Redis']:
    """Given a list of strings or queues, returns a connection"""
    from .queue import Queue

    for queue_or_name in queues_or_names:
        if isinstance(queue_or_name, Queue):
            return queue_or_name.connection
    return None


def parse_composite_key(composite_key: str) -> tuple[str, str]:
    """Method returns a parsed composite key.

    Args:
        composite_key (str): the composite key to parse

    Returns:
        tuple[str, str]: tuple of job id and the execution id
    """
    result = composite_key.split(':')
    if len(result) == 1:
        # StartedJobRegistry contains a composite key under the sorted set
        # a single job_id should've never ended up in the set, but
        # just in case there's a regression (tests don't show any)
        warnings.warn(
            f'Composite key must contain job_id:execution_id, got {composite_key}',
            DeprecationWarning,
        )
        return (result[0], '')
    job_id, execution_id = result
    return (job_id, execution_id)