Debian Codegraph @

README.md

raw
1 # AIOFile
2
3 [![Github Actions](https://github.com/mosquito/aiofile/workflows/ci/badge.svg)](https://github.com/mosquito/aiofile/actions?query=workflow%3Aci) [![Latest Version](https://img.shields.io/pypi/v/aiofile.svg)](https://pypi.python.org/pypi/aiofile/) [![Python Versions](https://img.shields.io/pypi/pyversions/aiofile.svg)](https://pypi.python.org/pypi/aiofile/) [![License](https://img.shields.io/pypi/l/aiofile.svg)](https://pypi.python.org/pypi/aiofile/) [![Coverage Status](https://coveralls.io/repos/github/mosquito/aiofile/badge.svg?branch=master)](https://coveralls.io/github/mosquito/aiofile?branch=master)
4
5 Real asynchronous file operations with asyncio support.
6
7 ## Features
8
9 * Since version 2.0.0, uses [caio](https://pypi.org/project/caio), which provides multiple
10 async I/O backends:
11 * **Linux io_uring** — the modern, high-performance Linux kernel AIO interface.
12 * **Linux libaio** — the classic kernel AIO mechanism via [libaio](https://pagure.io/libaio).
13 * **Thread-based (C)** — a [threadpool](https://github.com/mbrossard/threadpool/)-backed
14 implementation for POSIX systems (macOS, Linux).
15 * **Pure Python** — a thread-based fallback for any platform.
16 * The best available backend is chosen automatically based on system compatibility.
17 * `AIOFile` has no internal file pointer. Pass `offset` and `chunk_size` to each operation,
18 or use the `Reader`/`Writer` helpers. For a file-like interface, use `async_open`.
19
20 ## Limitations
21
22 * The Linux native AIO and io_uring backends cannot open special files.
23 Asynchronous operations against special filesystems such as `/proc/` or `/sys/` are not
24 supported by the kernel — this is neither an aiofile nor a caio issue.
25 In such cases, switch to a thread-based implementation
26 (see the [Troubleshooting](#troubleshooting) section).
27
28 ## Code examples
29
30 All code examples require Python 3.11+.
31
32 ### High-level API
33
34 #### `async_open` helper
35
36 This helper mimics Python's file-like objects, returning an object with
37 equivalent asynchronous methods.
38
39 Supported methods:
40
41 * `async def read(length=-1)` — reads a chunk from the file; `-1` reads to the end.
42 * `async def write(data)` — writes a chunk to the file.
43 * `def seek(offset)` — sets the file pointer position.
44 * `def tell()` — returns the current file pointer position.
45 * `async def readline(size=-1, newline="\n")` — reads until a newline or EOF.
46 Since version 3.7.0, `__aiter__` returns a `LineReader`.
47 This method is suboptimal for small lines because it does not reuse the read buffer —
48 prefer `LineReader` when reading line by line.
49 * `def __aiter__() -> LineReader` — iterator over lines.
50 * `def iter_chunked(chunk_size: int = 32768) -> Reader` — iterator over chunks.
51 * `.file` — the underlying `AIOFile` object.
52
53 Basic example:
54
55 <!-- name: test_basic -->
56 ```python
57 import asyncio
58 from pathlib import Path
59 from tempfile import gettempdir
60
61 from aiofile import async_open
62
63 tmp_filename = Path(gettempdir()) / "hello.txt"
64
65 async def main():
66 async with async_open(tmp_filename, 'w+') as afp:
67 await afp.write("Hello ")
68 await afp.write("world")
69 afp.seek(0)
70
71 print(await afp.read())
72
73 await afp.write("Hello from\nasync world")
74 print(await afp.readline())
75 print(await afp.readline())
76
77 asyncio.run(main())
78 ```
79
80 Example without context manager:
81
82 <!-- name: test_basic_without_context_manager -->
83 ```python
84 import asyncio
85 import atexit
86 import os
87 from tempfile import mktemp
88
89 from aiofile import async_open
90
91
92 TMP_NAME = mktemp()
93 atexit.register(os.unlink, TMP_NAME)
94
95
96 async def main():
97 afp = await async_open(TMP_NAME, "w")
98 await afp.write("Hello")
99 await afp.close()
100
101
102 asyncio.run(main())
103 assert open(TMP_NAME, "r").read() == "Hello"
104 ```
105
106 Concatenate example program (`cat`):
107
108 ```python
109 import asyncio
110 import sys
111 from argparse import ArgumentParser
112 from pathlib import Path
113
114 from aiofile import async_open
115
116 parser = ArgumentParser(
117 description="Read files line by line using asynchronous io API"
118 )
119 parser.add_argument("file_name", nargs="+", type=Path)
120
121 async def main(arguments):
122 for src in arguments.file_name:
123 async with async_open(src, "r") as afp:
124 async for line in afp:
125 sys.stdout.write(line)
126
127
128 asyncio.run(main(parser.parse_args()))
129 ```
130
131 Copy file example program (`cp`):
132
133 ```python
134 import asyncio
135 from argparse import ArgumentParser
136 from pathlib import Path
137
138 from aiofile import async_open
139
140 parser = ArgumentParser(
141 description="Copying files using asynchronous io API"
142 )
143 parser.add_argument("source", type=Path)
144 parser.add_argument("dest", type=Path)
145 parser.add_argument("--chunk-size", type=int, default=65535)
146
147
148 async def main(arguments):
149 async with async_open(arguments.source, "rb") as src, \
150 async_open(arguments.dest, "wb") as dest:
151 async for chunk in src.iter_chunked(arguments.chunk_size):
152 await dest.write(chunk)
153
154
155 asyncio.run(main(parser.parse_args()))
156 ```
157
158 Example with opening an already-open file pointer:
159
160 ```python
161 import asyncio
162 from typing import IO, Any
163 from aiofile import async_open
164
165
166 async def main(fp: IO[Any]):
167 async with async_open(fp) as afp:
168 await afp.write("Hello from\nasync world")
169 print(await afp.readline())
170
171
172 with open("test.txt", "w+") as fp:
173 asyncio.run(main(fp))
174 ```
175
176 Linux native AIO and io_uring do not support reading or writing special files
177 (procfs, sysfs, Unix pipes, etc.), so operations on these files require
178 a compatible context object.
179
180 ```python
181 import asyncio
182 from aiofile import async_open
183 from caio import thread_aio_asyncio
184 from contextlib import AsyncExitStack
185
186
187 async def main():
188 async with AsyncExitStack() as stack:
189
190 # Custom context should be reused
191 ctx = await stack.enter_async_context(
192 thread_aio_asyncio.AsyncioContext()
193 )
194
195 # Open special file with custom context
196 src = await stack.enter_async_context(
197 async_open("/proc/cpuinfo", "r", context=ctx)
198 )
199
200 # Open regular file with default context
201 dest = await stack.enter_async_context(
202 async_open("/tmp/cpuinfo", "w")
203 )
204
205 # Copying file content line by line
206 async for line in src:
207 await dest.write(line)
208
209
210 asyncio.run(main())
211 ```
212
213 ### `clone` helper
214
215 An asynchronous context supports a limited number of concurrent operations at the low level,
216 regardless of how many file descriptors are open. `clone` lets you create a second file-like
217 object with its own independent offset from a single descriptor, without opening the file
218 multiple times.
219
220 ```python
221 """
222 This example counts multiple hash functions from the file passed as the first
223 argument. The hash functions are counted competitively, and the results are
224 printed in the order of hashing completion.
225 """
226 import asyncio
227 import hashlib
228 import sys
229
230 import aiofile
231
232
233 async def hasher(name, hash_func, afp):
234 loop = asyncio.get_running_loop()
235 async for chunk in afp.iter_chunked(2 ** 20):
236 await loop.run_in_executor(None, hash_func.update, chunk)
237 print(name, hash_func.hexdigest())
238
239
240 async def main():
241 async with aiofile.async_open(sys.argv[1], "rb") as source:
242 hashers = [
243 ("MD5", hashlib.md5()),
244 ("SHA1", hashlib.sha1()),
245 ("SHA256", hashlib.sha256()),
246 ("SHA512", hashlib.sha512()),
247 ]
248
249 await asyncio.gather(*[
250 hasher(name, hash_func, await aiofile.clone(source))
251 for name, hash_func in hashers
252 ])
253
254
255 asyncio.run(main())
256 ```
257
258 > **Note:** This will likely perform poorly on Windows, so if that is
259 > your target platform, this optimization may not be worth it.
260
261 ### Low-level API
262
263 The `AIOFile` class is a low-level interface for asynchronous file operations. Its `read` and
264 `write` methods accept an `offset=0` (in bytes) at which the operation is performed.
265
266 This allows many independent I/O operations on a single open file without an internal pointer.
267 For sequential reading and writing, use `Writer`, `Reader`, and `LineReader`. Note that
268 `async_open` is not the same as `AIOFile`: it wraps it to provide a file-like interface
269 similar to the built-in `open`.
270
271 ```python
272 import asyncio
273 from aiofile import AIOFile
274
275
276 async def main():
277 async with AIOFile("hello.txt", 'w+') as afp:
278 payload = "Hello world\n"
279
280 await asyncio.gather(
281 *[afp.write(payload, offset=i * len(payload)) for i in range(10)]
282 )
283
284 await afp.fsync()
285
286 assert await afp.read(len(payload) * 10) == payload * 10
287
288 asyncio.run(main())
289 ```
290
291 The low-level API is essentially a lightly sugared `caio` API.
292
293 ```python
294 import asyncio
295 from aiofile import AIOFile
296
297
298 async def main():
299 async with AIOFile("/tmp/hello.txt", 'w+') as afp:
300 await afp.write("Hello ")
301 await afp.write("world", offset=7)
302 await afp.fsync()
303
304 print(await afp.read())
305
306
307 asyncio.run(main())
308 ```
309
310 #### `Reader` and `Writer`
311
312 To read or write a file linearly, the following example may be helpful.
313
314 ```python
315 import asyncio
316 from aiofile import AIOFile, Reader, Writer
317
318
319 async def main():
320 async with AIOFile("/tmp/hello.txt", 'w+') as afp:
321 writer = Writer(afp)
322 reader = Reader(afp, chunk_size=8)
323
324 await writer("Hello")
325 await writer(" ")
326 await writer("World")
327 await afp.fsync()
328
329 async for chunk in reader:
330 print(chunk)
331
332
333 asyncio.run(main())
334 ```
335
336 #### `LineReader` - read file line by line
337
338 `LineReader` is a helper for reading a file linearly, line by line. It maintains a buffer
339 and reads file fragments chunk by chunk, searching for line boundaries. The default chunk
340 size is 4KB.
341
342 ```python
343 import asyncio
344 from aiofile import AIOFile, LineReader, Writer
345
346
347 async def main():
348 async with AIOFile("/tmp/hello.txt", 'w+') as afp:
349 writer = Writer(afp)
350
351 await writer("Hello")
352 await writer(" ")
353 await writer("World")
354 await writer("\n")
355 await writer("\n")
356 await writer("From async world")
357 await afp.fsync()
358
359 async for line in LineReader(afp):
360 print(line)
361
362
363 asyncio.run(main())
364 ```
365
366 To read a file line by line, prefer `LineReader` over `async_open`.
367
368 ## More examples
369
370 ### Async CSV Dict Reader
371
372 ```python
373 import asyncio
374 import io
375 from csv import DictReader
376
377 from aiofile import AIOFile, LineReader
378
379
380 class AsyncDictReader:
381 def __init__(self, afp, **kwargs):
382 self.buffer = io.BytesIO()
383 self.file_reader = LineReader(
384 afp, line_sep=kwargs.pop('line_sep', '\n'),
385 chunk_size=kwargs.pop('chunk_size', 4096),
386 offset=kwargs.pop('offset', 0),
387 )
388 self.reader = DictReader(
389 io.TextIOWrapper(
390 self.buffer,
391 encoding=kwargs.pop('encoding', 'utf-8'),
392 errors=kwargs.pop('errors', 'replace'),
393 ), **kwargs,
394 )
395 self.line_num = 0
396
397 def __aiter__(self):
398 return self
399
400 async def __anext__(self):
401 if self.line_num == 0:
402 header = await self.file_reader.readline()
403 self.buffer.write(header)
404
405 line = await self.file_reader.readline()
406
407 if not line:
408 raise StopAsyncIteration
409
410 self.buffer.write(line)
411 self.buffer.seek(0)
412
413 try:
414 result = next(self.reader)
415 except StopIteration as e:
416 raise StopAsyncIteration from e
417
418 self.buffer.seek(0)
419 self.buffer.truncate(0)
420 self.line_num = self.reader.line_num
421
422 return result
423
424
425 async def main():
426 async with AIOFile('sample.csv', 'rb') as afp:
427 async for item in AsyncDictReader(afp):
428 print(item)
429
430
431 asyncio.run(main())
432 ```
433
434 ## Troubleshooting
435
436 The caio Linux backends (io_uring and libaio) work well on modern kernels and filesystems.
437 Problems are usually environment-specific and are not bugs. There are several ways to resolve them:
438
439 1. Upgrade the kernel.
440 2. Use a compatible filesystem.
441 3. Switch to a thread-based or pure-Python backend.
442
443 Since version 0.7.0, caio offers several ways to select the backend:
444
445 1. Set the `CAIO_IMPL` environment variable at runtime:
446
447 * `uring` — Linux io_uring (requires kernel ≥ 5.1)
448 * `linux` — Linux libaio
449 * `thread` — C-based thread pool implementation
450 * `python` — pure-Python thread-based fallback
451
452 2. The `default_implementation` file located next to `__init__.py` in the caio installation
453 directory. Useful for distribution package maintainers. The file may contain comments
454 (lines starting with `#`); the first non-comment line should be one of the values above.
455
456 3. Manage contexts manually:
457
458 ```python
459 import asyncio
460
461 from aiofile import async_open
462 from caio import linux_aio_asyncio, thread_aio_asyncio
463
464
465 async def main():
466 linux_ctx = linux_aio_asyncio.AsyncioContext()
467 threads_ctx = thread_aio_asyncio.AsyncioContext()
468
469 async with async_open("/tmp/test.txt", "w", context=linux_ctx) as afp:
470 await afp.write("Hello")
471
472 async with async_open("/tmp/test.txt", "r", context=threads_ctx) as afp:
473 print(await afp.read())
474
475
476 asyncio.run(main())
477 ```
478
479 ## Benchmark
480
481 stdlib, `aiofile` (once per `caio` backend, each in its own subprocess), `aiofiles`,
482 `aiomisc.io` — linear/random block order, read/write, buffered/`O_DIRECT`,
483 sequential/concurrent, fixed op count per cell (never a partial/cancelled
484 measurement). Tool, methodology and raw data: [`benchmark/`](benchmark/); a
485 third report at 4096B lives in `benchmark/results/`.
486
487 ![aiofile benchmark, 65536B blocks](https://media.githubusercontent.com/media/mosquito/aiofile/master/benchmark/results/aiofile-bench-report-bs65536.png)
488
489 Linear write, one Linux/ext4 run, 65536B blocks, 2000 ops/cell, per-op
490 latency in ms (p50 / p95, ±stdev):
491
492 | participant | x1 | x8 |
493 |-----------------------|------------------------|------------------------|
494 | stdlib (buffered) | 0.081 / 0.128 (±0.030) | 0.167 / 0.298 (±0.157) |
495 | stdlib (O_DIRECT) | 0.148 / 0.398 (±0.097) | 0.266 / 0.650 (±0.192) |
496 | aiofile (linux_uring) | 0.050 / 0.108 (±0.022) | 0.040 / 0.248 (±0.293) |
497 | aiofile (linux_aio) | 0.009 / 0.024 (±0.020) | 0.040 / 0.089 (±0.020) |
498 | aiofile (thread_aio) | 0.150 / 0.461 (±0.128) | 0.664 / 2.930 (±0.943) |
499 | aiofile (python_aio) | 0.109 / 0.173 (±0.042) | 0.189 / 0.314 (±0.072) |
500 | aiofiles | 0.155 / 0.257 (±0.175) | 1.166 / 2.238 (±0.570) |
501 | aiomisc | 0.156 / 0.256 (±0.051) | 1.118 / 1.607 (±1.750) |
502
503 `linux_aio` posts the lowest, tightest per-op latency at both concurrency
504 levels here -- `io_submit()` is a lean, purpose-built syscall, while
505 `linux_uring`'s ring/SQPOLL machinery is built to amortize *over batched
506 submissions*, not to minimize one op's latency, so it only pulls ahead
507 once there's a batch to amortize over. `aiofiles`/`aiomisc` latency
508 *grows* at x8 (one seek cursor, serialized by a lock) instead of
509 shrinking like the positional-I/O libraries.
510
511 ![aiofile benchmark, 256B blocks](https://media.githubusercontent.com/media/mosquito/aiofile/master/benchmark/results/aiofile-bench-report-bs256.png)
512
513 Linear write, 256B blocks, 2000 ops/cell, per-op latency in ms (p50 / p95, ±stdev):
514
515 | participant | x1 | x8 |
516 |-----------------------|-------------------------------|------------------------|
517 | stdlib (buffered) | 0.066 / 0.104 (±0.017) | 0.152 / 0.299 (±0.125) |
518 | stdlib (O_DIRECT) | n/a (256B isn't 4096-aligned) | n/a |
519 | aiofile (linux_uring) | 0.086 / 0.159 (±0.043) | 0.043 / 0.070 (±0.021) |
520 | aiofile (linux_aio) | 0.005 / 0.008 (±0.004) | 0.017 / 0.027 (±0.008) |
521 | aiofile (thread_aio) | 0.128 / 0.290 (±0.090) | 0.464 / 1.503 (±0.470) |
522 | aiofile (python_aio) | 0.113 / 0.201 (±0.037) | 0.179 / 0.354 (±0.124) |
523 | aiofiles | 0.136 / 0.169 (±0.030) | 1.002 / 1.516 (±0.372) |
524 | aiomisc | 0.144 / 0.223 (±0.040) | 1.046 / 1.999 (±0.415) |
525
526 Same shape at a tiny block size: `linux_aio` still has the lowest latency
527 by a wide margin (sub-10μs median at x1), `linux_uring` still needs
528 concurrency to close the gap (and still doesn't fully close it), and the
529 lock-serialized libraries still get *worse*, not better, under
530 concurrency.