Skip to content

url_fetcher

Parallel URL fetching.

This module provides UrlFetcher, a multi-threaded URL fetcher which downloads files in parallel - one worker thread per concurrent fetch - storing the results in a working folder, so that they can be retrieved either one by one (wait) or streamed (iter_results).

The URLs are fetched via the filesystem abstraction layer (see gfs), so any supported URL protocol - local files, http(s), GCS, etc. - can be used transparently.

Example
import os
import tempfile

import py_misc_utils.url_fetcher as uf

tdir = tempfile.mkdtemp()
fpath = os.path.join(tdir, 'a.txt')
with open(fpath, 'wb') as f:
  f.write(b'alpha')

with uf.UrlFetcher() as fetcher:
  fetcher.enqueue(fpath)
  data = fetcher.wait(fpath)

assert data == b'alpha'

UrlFetcher

A multi-threaded parallel URL fetcher.

URLs submitted via enqueue() are fetched concurrently by a pool of worker threads, each of them resolving the URLs through the filesystem abstraction layer.

A UrlFetcher is a context manager: entering it starts the workers, exiting it shuts them down.

Example
import os
import tempfile

from py_misc_utils import url_fetcher as uf

tdir = tempfile.mkdtemp()
fpath = os.path.join(tdir, 'a.txt')
with open(fpath, 'wb') as f:
  f.write(b'alpha')

with uf.UrlFetcher() as fetcher:
  wmap = fetcher.enqueue(fpath, None)
  # Falsy URLs are skipped - None was not enqueued.
  assert set(wmap) == {fpath}

  data = fetcher.wait(fpath)
  assert data == b'alpha'
Source code in py_misc_utils/url_fetcher.py
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
class UrlFetcher:
  """A multi-threaded parallel URL fetcher.

  URLs submitted via enqueue() are fetched concurrently by a pool of
  worker threads, each of them resolving the URLs through the filesystem
  abstraction layer.

  A UrlFetcher is a context manager: entering it starts the workers,
  exiting it shuts them down.

  Example:
    import os
    import tempfile

    from py_misc_utils import url_fetcher as uf

    tdir = tempfile.mkdtemp()
    fpath = os.path.join(tdir, 'a.txt')
    with open(fpath, 'wb') as f:
      f.write(b'alpha')

    with uf.UrlFetcher() as fetcher:
      wmap = fetcher.enqueue(fpath, None)
      # Falsy URLs are skipped - None was not enqueued.
      assert set(wmap) == {fpath}

      data = fetcher.wait(fpath)
      assert data == b'alpha'
  """

  def __init__(self, path=None, num_workers=None, fs_kwargs=None):
    """Creates an URL fetcher.

    Args:
      path: An optional working folder path where the fetched files are
        stored. If None, a fast filesystem folder - automatically cleaned
        up upon shutdown - is used.
      num_workers: The number of fetcher worker threads. If None, a
        default value - based on the CPU count - is used.
      fs_kwargs: Optional keyword arguments passed to the filesystem
        resolver - like the fetch timeout.
    """
    fs_kwargs = fs_kwargs or dict()
    fs_kwargs = ut.dict_setmissing(
        fs_kwargs,
        timeout=ut.getenv('FETCHER_TIMEO', dtype=float, defval=10.0),
    )

    self._ctor_path = path
    self._path = None
    self._num_workers = num_workers or max(os.cpu_count() * 4, 128)
    self._fs_kwargs = fs_kwargs
    self._uqueue = self._rqueue = None
    self._workers = []
    self._pending = set()

  def start(self):
    """Starts the fetcher workers."""
    if self._ctor_path is None:
      self._path = tmpd.fastfs_dir()
    else:
      self._path = self._ctor_path

    self._uqueue = queue.Queue()
    self._rqueue = queue.Queue()
    for i in range(self._num_workers):
      worker = threading.Thread(
          target=fetcher,
          args=(self._path, self._fs_kwargs, self._uqueue, self._rqueue),
          daemon=True,
      )
      worker.start()
      self._workers.append(worker)

  def shutdown(self):
    """Shuts down the fetcher workers.

    Waits for all the worker threads to complete their pending fetches,
    and removes the working folder if it has been created by the fetcher
    itself.
    """
    alog.verbose('Sending shutdowns down the queue')
    for _ in range(len(self._workers)):
      self._uqueue.put('')

    alog.verbose('Joining fetcher workers')
    for worker in self._workers:
      worker.join()

    self._uqueue = self._rqueue = None
    self._workers = []

    if self._path != self._ctor_path:
      gfs.rmtree(self._path, ignore_errors=True)

    self._path = None
    self._pending = set()

  def enqueue(self, *urls):
    """Enqueues URLs to be fetched.

    Args:
      *urls: The URLs to enqueue. Empty (falsy) URLs are skipped.

    Returns:
      A dict mapping each enqueued URL to its work-result hash - as
      expected by the work-results API.

    Example:
      import os
      import tempfile

      from py_misc_utils import url_fetcher as uf

      fpath = os.path.join(tempfile.mkdtemp(), 'a.txt')
      with open(fpath, 'wb') as f:
        f.write(b'alpha')

      with uf.UrlFetcher() as fetcher:
        wmap = fetcher.enqueue(fpath, None)
        # Falsy URLs are skipped - only fpath got enqueued.
        assert set(wmap) == {fpath}
    """
    wmap = dict()
    for url in urls:
      if url:
        self._uqueue.put(url)
        self._pending.add(url)
        wmap[url] = wres.work_hash(url)

    return wmap

  def wait(self, url):
    """Waits for the fetch of an URL to be completed - or to have failed.

    Blocks until the given URL fetch completes, consuming the completion
    notifications of the URLs completed in the meantime.

    Args:
      url: The URL to wait for - it must have been enqueued.

    Returns:
      The fetched content.

    Raises:
      Exception: The error which made the fetch fail - if it failed.
      AssertionError: If the URL has already been waited for - i.e. it is
        not pending anymore - and its work result is not found.

    Example:
      import os
      import tempfile

      from py_misc_utils import url_fetcher as uf

      tdir = tempfile.mkdtemp()
      fpath = os.path.join(tdir, 'a.txt')
      with open(fpath, 'wb') as f:
        f.write(b'alpha')

      with uf.UrlFetcher() as fetcher:
        fetcher.enqueue(fpath)
        assert fetcher.wait(fpath) == b'alpha'

        # Waiting for a failed fetch raises the original error.
        missing = os.path.join(tdir, 'missing.txt')
        fetcher.enqueue(missing)
        try:
          fetcher.wait(missing)
        except FileNotFoundError:
          pass
    """
    wpath = wres.work_path(self._path, url)
    if not os.path.isfile(wpath):
      tas.check(url in self._pending, msg=f'URL already retired: {url}')

      while self._pending:
        rurl = self._rqueue.get()
        self._pending.discard(rurl)
        if rurl == url:
          break

    try:
      return wres.get_work(wpath)
    finally:
      os.remove(wpath)

  def iter_results(self, max_results=None, block=True, timeout=None):
    """Iterates over the results of the completed fetches.

    Args:
      max_results: An optional maximum number of results to yield.
      block: Whether to block waiting for the next result.
      timeout: An optional maximum number of seconds to block.

    Yields:
      (url, data) tuples - one per completed fetch - where data holds the
      fetched content, or a WorkException carrying the error if the fetch
      failed.

    Example:
      import os
      import tempfile

      from py_misc_utils import work_results as wres

      from py_misc_utils import url_fetcher as uf

      tdir = tempfile.mkdtemp()
      fpath = os.path.join(tdir, 'a.txt')
      with open(fpath, 'wb') as f:
        f.write(b'alpha')

      with uf.UrlFetcher() as fetcher:
        fetcher.enqueue(fpath)

        for url, data in fetcher.iter_results():
          if isinstance(data, wres.WorkException):
            print(f'Fetch of "{url}" failed: {data}')
          else:
            assert data == b'alpha'
    """
    count = 0
    while self._pending:
      try:
        rurl = self._rqueue.get(block=block, timeout=timeout)

        self._pending.discard(rurl)
        wpath = wres.work_path(self._path, rurl)

        wdata = wres.load_work(wpath)

        os.remove(wpath)

        yield rurl, wdata
      except queue.Empty:
        break

      count += 1
      if max_results is not None and count >= max_results:
        break

  def __enter__(self):
    """Starts the fetcher workers."""

    self.start()

    return self

  def __exit__(self, *exc):
    """Shuts down the fetcher workers."""

    self.shutdown()

    return False

start()

Starts the fetcher workers.

Source code in py_misc_utils/url_fetcher.py
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
def start(self):
  """Starts the fetcher workers."""
  if self._ctor_path is None:
    self._path = tmpd.fastfs_dir()
  else:
    self._path = self._ctor_path

  self._uqueue = queue.Queue()
  self._rqueue = queue.Queue()
  for i in range(self._num_workers):
    worker = threading.Thread(
        target=fetcher,
        args=(self._path, self._fs_kwargs, self._uqueue, self._rqueue),
        daemon=True,
    )
    worker.start()
    self._workers.append(worker)

shutdown()

Shuts down the fetcher workers.

Waits for all the worker threads to complete their pending fetches, and removes the working folder if it has been created by the fetcher itself.

Source code in py_misc_utils/url_fetcher.py
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
def shutdown(self):
  """Shuts down the fetcher workers.

  Waits for all the worker threads to complete their pending fetches,
  and removes the working folder if it has been created by the fetcher
  itself.
  """
  alog.verbose('Sending shutdowns down the queue')
  for _ in range(len(self._workers)):
    self._uqueue.put('')

  alog.verbose('Joining fetcher workers')
  for worker in self._workers:
    worker.join()

  self._uqueue = self._rqueue = None
  self._workers = []

  if self._path != self._ctor_path:
    gfs.rmtree(self._path, ignore_errors=True)

  self._path = None
  self._pending = set()

enqueue(*urls)

Enqueues URLs to be fetched.

Parameters:

Name Type Description Default
*urls

The URLs to enqueue. Empty (falsy) URLs are skipped.

()

Returns:

Type Description

A dict mapping each enqueued URL to its work-result hash - as

expected by the work-results API.

Example
import os
import tempfile

from py_misc_utils import url_fetcher as uf

fpath = os.path.join(tempfile.mkdtemp(), 'a.txt')
with open(fpath, 'wb') as f:
  f.write(b'alpha')

with uf.UrlFetcher() as fetcher:
  wmap = fetcher.enqueue(fpath, None)
  # Falsy URLs are skipped - only fpath got enqueued.
  assert set(wmap) == {fpath}
Source code in py_misc_utils/url_fetcher.py
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
def enqueue(self, *urls):
  """Enqueues URLs to be fetched.

  Args:
    *urls: The URLs to enqueue. Empty (falsy) URLs are skipped.

  Returns:
    A dict mapping each enqueued URL to its work-result hash - as
    expected by the work-results API.

  Example:
    import os
    import tempfile

    from py_misc_utils import url_fetcher as uf

    fpath = os.path.join(tempfile.mkdtemp(), 'a.txt')
    with open(fpath, 'wb') as f:
      f.write(b'alpha')

    with uf.UrlFetcher() as fetcher:
      wmap = fetcher.enqueue(fpath, None)
      # Falsy URLs are skipped - only fpath got enqueued.
      assert set(wmap) == {fpath}
  """
  wmap = dict()
  for url in urls:
    if url:
      self._uqueue.put(url)
      self._pending.add(url)
      wmap[url] = wres.work_hash(url)

  return wmap

wait(url)

Waits for the fetch of an URL to be completed - or to have failed.

Blocks until the given URL fetch completes, consuming the completion notifications of the URLs completed in the meantime.

Parameters:

Name Type Description Default
url

The URL to wait for - it must have been enqueued.

required

Returns:

Type Description

The fetched content.

Raises:

Type Description
Exception

The error which made the fetch fail - if it failed.

AssertionError

If the URL has already been waited for - i.e. it is not pending anymore - and its work result is not found.

Example
import os
import tempfile

from py_misc_utils import url_fetcher as uf

tdir = tempfile.mkdtemp()
fpath = os.path.join(tdir, 'a.txt')
with open(fpath, 'wb') as f:
  f.write(b'alpha')

with uf.UrlFetcher() as fetcher:
  fetcher.enqueue(fpath)
  assert fetcher.wait(fpath) == b'alpha'

  # Waiting for a failed fetch raises the original error.
  missing = os.path.join(tdir, 'missing.txt')
  fetcher.enqueue(missing)
  try:
    fetcher.wait(missing)
  except FileNotFoundError:
    pass
Source code in py_misc_utils/url_fetcher.py
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
def wait(self, url):
  """Waits for the fetch of an URL to be completed - or to have failed.

  Blocks until the given URL fetch completes, consuming the completion
  notifications of the URLs completed in the meantime.

  Args:
    url: The URL to wait for - it must have been enqueued.

  Returns:
    The fetched content.

  Raises:
    Exception: The error which made the fetch fail - if it failed.
    AssertionError: If the URL has already been waited for - i.e. it is
      not pending anymore - and its work result is not found.

  Example:
    import os
    import tempfile

    from py_misc_utils import url_fetcher as uf

    tdir = tempfile.mkdtemp()
    fpath = os.path.join(tdir, 'a.txt')
    with open(fpath, 'wb') as f:
      f.write(b'alpha')

    with uf.UrlFetcher() as fetcher:
      fetcher.enqueue(fpath)
      assert fetcher.wait(fpath) == b'alpha'

      # Waiting for a failed fetch raises the original error.
      missing = os.path.join(tdir, 'missing.txt')
      fetcher.enqueue(missing)
      try:
        fetcher.wait(missing)
      except FileNotFoundError:
        pass
  """
  wpath = wres.work_path(self._path, url)
  if not os.path.isfile(wpath):
    tas.check(url in self._pending, msg=f'URL already retired: {url}')

    while self._pending:
      rurl = self._rqueue.get()
      self._pending.discard(rurl)
      if rurl == url:
        break

  try:
    return wres.get_work(wpath)
  finally:
    os.remove(wpath)

iter_results(max_results=None, block=True, timeout=None)

Iterates over the results of the completed fetches.

Parameters:

Name Type Description Default
max_results

An optional maximum number of results to yield.

None
block

Whether to block waiting for the next result.

True
timeout

An optional maximum number of seconds to block.

None

Yields:

Type Description

(url, data) tuples - one per completed fetch - where data holds the

fetched content, or a WorkException carrying the error if the fetch

failed.

Example
import os
import tempfile

from py_misc_utils import work_results as wres

from py_misc_utils import url_fetcher as uf

tdir = tempfile.mkdtemp()
fpath = os.path.join(tdir, 'a.txt')
with open(fpath, 'wb') as f:
  f.write(b'alpha')

with uf.UrlFetcher() as fetcher:
  fetcher.enqueue(fpath)

  for url, data in fetcher.iter_results():
    if isinstance(data, wres.WorkException):
      print(f'Fetch of "{url}" failed: {data}')
    else:
      assert data == b'alpha'
Source code in py_misc_utils/url_fetcher.py
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
def iter_results(self, max_results=None, block=True, timeout=None):
  """Iterates over the results of the completed fetches.

  Args:
    max_results: An optional maximum number of results to yield.
    block: Whether to block waiting for the next result.
    timeout: An optional maximum number of seconds to block.

  Yields:
    (url, data) tuples - one per completed fetch - where data holds the
    fetched content, or a WorkException carrying the error if the fetch
    failed.

  Example:
    import os
    import tempfile

    from py_misc_utils import work_results as wres

    from py_misc_utils import url_fetcher as uf

    tdir = tempfile.mkdtemp()
    fpath = os.path.join(tdir, 'a.txt')
    with open(fpath, 'wb') as f:
      f.write(b'alpha')

    with uf.UrlFetcher() as fetcher:
      fetcher.enqueue(fpath)

      for url, data in fetcher.iter_results():
        if isinstance(data, wres.WorkException):
          print(f'Fetch of "{url}" failed: {data}')
        else:
          assert data == b'alpha'
  """
  count = 0
  while self._pending:
    try:
      rurl = self._rqueue.get(block=block, timeout=timeout)

      self._pending.discard(rurl)
      wpath = wres.work_path(self._path, rurl)

      wdata = wres.load_work(wpath)

      os.remove(wpath)

      yield rurl, wdata
    except queue.Empty:
      break

    count += 1
    if max_results is not None and count >= max_results:
      break

resolve_url(fss, url, fs_kwargs)

Resolves an URL into its filesystem object and normalized path.

Parameters:

Name Type Description Default
fss

A dict of already-resolved filesystem objects, keyed by their protocol ids - updated in place upon a successful resolution.

required
url

The URL to resolve.

required
fs_kwargs

Optional keyword arguments passed to the filesystem resolver.

required

Returns:

Type Description

A (fs, fpath) tuple, where fs is the filesystem object handling the

URL and fpath the URL path normalized with respect to it.

Example
import os

from py_misc_utils import url_fetcher as uf

fs, fpath = uf.resolve_url({}, '/etc/hosts', {})
assert fpath == '/etc/hosts'
Source code in py_misc_utils/url_fetcher.py
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
def resolve_url(fss, url, fs_kwargs):
  """Resolves an URL into its filesystem object and normalized path.

  Args:
    fss: A dict of already-resolved filesystem objects, keyed by their
      protocol ids - updated in place upon a successful resolution.
    url: The URL to resolve.
    fs_kwargs: Optional keyword arguments passed to the filesystem
      resolver.

  Returns:
    A (fs, fpath) tuple, where fs is the filesystem object handling the
    URL and fpath the URL path normalized with respect to it.

  Example:
    import os

    from py_misc_utils import url_fetcher as uf

    fs, fpath = uf.resolve_url({}, '/etc/hosts', {})
    assert fpath == '/etc/hosts'
  """
  proto = gfs.get_proto(url)
  fs = fss.get(proto)
  if fs is None:
    fs, fpath = gfs.resolve_fs(url, **fs_kwargs)
    for fsid in fs.IDS:
      fss[fsid] = fs
  else:
    fpath = fs.norm_url(url)

  return fs, fpath

fetcher(path, fs_kwargs, uqueue, rqueue)

The URL fetcher worker function.

Fetches the URLs received from a work queue - one at a time - storing their content in the working folder, until a shutdown message is received.

Parameters:

Name Type Description Default
path

The working folder path where the fetched files are stored.

required
fs_kwargs

Optional keyword arguments passed to the filesystem resolver.

required
uqueue

The queue holding the URLs to be fetched - and the shutdown messages ('').

required
rqueue

The queue onto which the URLs of the completed - or failed - fetches are posted.

required
Example
import os
import queue
import tempfile
import threading

from py_misc_utils import url_fetcher as uf

work = tempfile.mkdtemp()
fpath = os.path.join(work, 'a.txt')
with open(fpath, 'wb') as f:
  f.write(b'alpha')

uqueue = queue.Queue()
rqueue = queue.Queue()
worker = threading.Thread(target=uf.fetcher,
                          args=(work, {}, uqueue, rqueue),
                          daemon=True)
worker.start()

uqueue.put(fpath)
assert rqueue.get(timeout=30) == fpath

uqueue.put('')
worker.join(timeout=30)
Source code in py_misc_utils/url_fetcher.py
 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
def fetcher(path, fs_kwargs, uqueue, rqueue):
  """The URL fetcher worker function.

  Fetches the URLs received from a work queue - one at a time - storing
  their content in the working folder, until a shutdown message is
  received.

  Args:
    path: The working folder path where the fetched files are stored.
    fs_kwargs: Optional keyword arguments passed to the filesystem
      resolver.
    uqueue: The queue holding the URLs to be fetched - and the shutdown
      messages ('').
    rqueue: The queue onto which the URLs of the completed - or failed -
      fetches are posted.

  Example:
    import os
    import queue
    import tempfile
    import threading

    from py_misc_utils import url_fetcher as uf

    work = tempfile.mkdtemp()
    fpath = os.path.join(work, 'a.txt')
    with open(fpath, 'wb') as f:
      f.write(b'alpha')

    uqueue = queue.Queue()
    rqueue = queue.Queue()
    worker = threading.Thread(target=uf.fetcher,
                              args=(work, {}, uqueue, rqueue),
                              daemon=True)
    worker.start()

    uqueue.put(fpath)
    assert rqueue.get(timeout=30) == fpath

    uqueue.put('')
    worker.join(timeout=30)
  """
  fss = dict()
  while True:
    url = uqueue.get()
    if not url:
      break

    wpath = wres.work_path(path, url)

    alog.verbose(f'Fetching "{url}"')
    try:
      fs, fpath = resolve_url(fss, url, fs_kwargs)

      with wres.write_result(wpath) as fd:
        for data in fs.get_file(fpath):
          fd.write(data)
    except Exception as ex:  # noqa: BLE001 -- worker boundary: any fetch failure is recorded via write_error, never propagated
      wres.write_error(wpath, ex, workid=url)
    finally:
      rqueue.put(url)