work_results¶
Work-result storage and exchange.
This module provides helpers to store and retrieve the results of asynchronous work - via unique work ids - along with the handling of the work failures: failed work results are marked with an error tag, holding a pickled WorkException, so that the consumers can detect the failure and re-raise it as if the work was executed locally.
Example
import os
import pickle
import tempfile
import py_misc_utils.work_results as pwr
tdir = tempfile.mkdtemp()
path = pwr.work_path(tdir, 'sum-job')
with pwr.write_result(path) as fd:
fd.write(pickle.dumps({'sum': 42}))
assert pickle.loads(pwr.get_work(wpath=path)) == {'sum': 42}
WorkException
¶
A serializable holder of an exception raised by a worker.
Some exceptions cannot be pickled, so the held exception is verified to survive a pickle round-trip: if not, a generic Exception holding its string representation is stored instead.
The type of the held exception is tracked as an importable (module, qualname) reference, so that the holder itself stays picklable even when the exception class is local or dynamically created. In that case the reported type degrades to Exception - the most precise claim which can be transported - and is_instance() stays consistent with the exception actually re-raised by do_raise().
Arbitrary attributes - set from the kwargs - can be attached to the exception holder, to be transported along the exception.
Example
import pickle
import py_misc_utils.work_results as pwr
wex = pwr.WorkException(ValueError('bad input'), worker='W1')
assert wex.is_instance(ValueError)
assert isinstance(wex.exception(), ValueError)
assert repr(wex) == "ValueError('bad input'): {'worker': 'W1'}"
# The holder is picklable, and keeps the kwargs after the roundtrip.
wex2 = pickle.loads(pickle.dumps(wex))
assert wex2.is_instance(ValueError) and wex2.worker == 'W1'
Source code in py_misc_utils/work_results.py
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 | |
do_raise()
¶
Raises the held exception.
Source code in py_misc_utils/work_results.py
109 110 111 112 | |
is_instance(*types)
¶
Checks the type of the held exception.
The check uses the resolved (module, qualname) reference, so it stays consistent with the exception type actually re-raised by do_raise(): locally-defined exception classes degrade to a generic Exception.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*types
|
The exception types to check against. |
()
|
Returns:
| Type | Description |
|---|---|
|
True if the held exception type is one of the given types. |
Example
import py_misc_utils.work_results as pwr
# Exception classes which cannot be referenced by (module, qualname)
# - like locally-defined ones - degrade to a generic Exception.
class LocalEx(Exception):
pass
wex = pwr.WorkException(LocalEx('local only'))
assert wex.is_instance(Exception)
assert not wex.is_instance(LocalEx)
assert str(wex.exception()) == 'LocalEx: local only'
Source code in py_misc_utils/work_results.py
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 | |
exception()
¶
Returns the held exception.
Returns:
| Type | Description |
|---|---|
|
The deserialized held exception - or its generic fallback. |
Source code in py_misc_utils/work_results.py
165 166 167 168 169 170 171 | |
work_hash(workid)
¶
Returns the hash of a work id.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
workid
|
The work id - typically a string holding an URL or another unique work identifier. |
required |
Returns:
| Type | Description |
|---|---|
|
The SHA-1 hash of the work id. |
Example
import py_misc_utils.work_results as pwr
assert len(pwr.work_hash('job-1')) == 40 # SHA-1 hex digest.
Source code in py_misc_utils/work_results.py
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 | |
work_path(path, workid)
¶
Returns the work-result file path of a work id.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
The folder holding the work results. |
required | |
workid
|
The work id. |
required |
Returns:
| Type | Description |
|---|---|
|
The work-result file path. |
Example
import os
import py_misc_utils.work_results as pwr
path = pwr.work_path('/results', 'job-1')
assert os.path.dirname(path) == '/results'
assert os.path.basename(path) == pwr.work_hash('job-1')
Source code in py_misc_utils/work_results.py
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 | |
enum_ready(path)
¶
Enumerates the work results stored in a folder.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
The folder holding the work results. |
required |
Yields:
| Type | Description |
|---|---|
|
(name, path) tuples - one per stored work result. |
Example
import pickle
import tempfile
import py_misc_utils.work_results as pwr
tdir = tempfile.mkdtemp()
for workid in ('a', 'b'):
with pwr.write_result(pwr.work_path(tdir, workid)) as fd:
fd.write(pickle.dumps(workid))
names = sorted(name for name, path in pwr.enum_ready(tdir))
assert len(names) == 2, names
Source code in py_misc_utils/work_results.py
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 | |
make_error(msg)
¶
Tags a message as an error payload.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
msg
|
The error payload - e.g. a pickled WorkException. |
required |
Returns:
| Type | Description |
|---|---|
|
The tagged error payload. |
Example
import pickle
import py_misc_utils.work_results as pwr
tagged = pwr.make_error(pickle.dumps(pwr.WorkException(RuntimeError('boom'))))
assert tagged.startswith(b'#@$ERROR$@#')
Source code in py_misc_utils/work_results.py
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 | |
write_result(path)
¶
Returns a context manager writing a work result atomically.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
The work-result file path. |
required |
Returns:
| Type | Description |
|---|---|
|
A context manager yielding the open file object of the work-result |
|
|
file. |
Example
import pickle
import tempfile
import py_misc_utils.work_results as pwr
tdir = tempfile.mkdtemp()
path = pwr.work_path(tdir, 'sum-job')
with pwr.write_result(path) as fd:
fd.write(pickle.dumps({'sum': 42}))
assert pickle.loads(pwr.load_work(wpath=path)) == {'sum': 42}
Source code in py_misc_utils/work_results.py
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 | |
write_error(path, exception, **kwargs)
¶
Writes an error-tagged work result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
The work-result file path. |
required | |
exception
|
The exception to record. |
required | |
**kwargs
|
Optional attributes attached to the WorkException holder. |
{}
|
Example
import tempfile
import py_misc_utils.work_results as pwr
tdir = tempfile.mkdtemp()
pwr.write_error(pwr.work_path(tdir, 'bad-job'), ValueError('failed'),
worker='W2')
wex = pwr.load_work(wpath=pwr.work_path(tdir, 'bad-job'))
assert wex.is_instance(ValueError) and wex.worker == 'W2'
Source code in py_misc_utils/work_results.py
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 | |
get_error(data)
¶
Extracts the WorkException held by an error-tagged payload.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
The work-result data to check. |
required |
Returns:
| Type | Description |
|---|---|
|
The deserialized WorkException, or None if the data is not |
|
|
error-tagged. |
Example
import pickle
import py_misc_utils.work_results as pwr
assert pwr.get_error(pickle.dumps({'ok': 1})) is None
Source code in py_misc_utils/work_results.py
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 | |
raise_if_error(data)
¶
Raises the error held by a work result - if any.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
The work-result data. |
required |
Returns:
| Type | Description |
|---|---|
|
The work-result data, if it does not hold an error. |
Raises:
| Type | Description |
|---|---|
Exception
|
The exception held by the work result, if any. |
Example
import pickle
import py_misc_utils.work_results as pwr
tagged = pwr.make_error(pickle.dumps(pwr.WorkException(RuntimeError('boom'))))
wex = pwr.get_error(tagged)
try:
pwr.raise_if_error(wex)
except RuntimeError as e:
assert str(e) == 'boom'
Source code in py_misc_utils/work_results.py
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 | |
load_work(wpath=None, path=None, workid=None)
¶
Loads a work result - without raising its error, if any.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
wpath
|
An optional work-result file path - taking precedence over the path/workid pair. |
None
|
|
path
|
The folder holding the work results - used if wpath is None. |
None
|
|
workid
|
The work id - used if wpath is None. |
None
|
Returns:
| Type | Description |
|---|---|
|
The work-result data: either the payload, or the WorkException |
|
|
deserialized from an error-tagged payload. |
Example
import pickle
import tempfile
import py_misc_utils.work_results as pwr
tdir = tempfile.mkdtemp()
path = pwr.work_path(tdir, 'sum-job')
with pwr.write_result(path) as fd:
fd.write(pickle.dumps({'sum': 42}))
assert pickle.loads(pwr.load_work(wpath=path)) == {'sum': 42}
pwr.write_error(pwr.work_path(tdir, 'bad-job'), ValueError('failed'))
wex = pwr.load_work(wpath=pwr.work_path(tdir, 'bad-job'))
assert wex.is_instance(ValueError)
Source code in py_misc_utils/work_results.py
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 | |
get_work(wpath, path=None, workid=None)
¶
Loads a work result, raising its error - if any.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
wpath
|
An optional work-result file path - taking precedence over the path/workid pair. |
required | |
path
|
The folder holding the work results - used if wpath is None. |
None
|
|
workid
|
The work id - used if wpath is None. |
None
|
Returns:
| Type | Description |
|---|---|
|
The work-result payload. |
Raises:
| Type | Description |
|---|---|
Exception
|
The exception held by the work result, if any. |
Example
import pickle
import tempfile
import py_misc_utils.work_results as pwr
tdir = tempfile.mkdtemp()
path = pwr.work_path(tdir, 'sum-job')
with pwr.write_result(path) as fd:
fd.write(pickle.dumps({'sum': 42}))
assert pickle.loads(pwr.get_work(wpath=path)) == {'sum': 42}
pwr.write_error(pwr.work_path(tdir, 'bad-job'), ValueError('failed'))
try:
pwr.get_work(wpath=pwr.work_path(tdir, 'bad-job'))
except ValueError as e:
assert str(e) == 'failed'
Source code in py_misc_utils/work_results.py
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 | |