openas 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
openas-0.1.0/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
openas-0.1.0/NOTICE ADDED
@@ -0,0 +1,13 @@
1
+ openas
2
+ Copyright 2007-2026 Gabriele Fariello
3
+
4
+ This product includes software developed by Gabriele Fariello
5
+ (https://github.com/fariello/openas).
6
+
7
+ Citation and Credit
8
+ -------------------
9
+ If you use openas in academic work, technical reports, or other publications,
10
+ please cite and credit this software as described in CITATION.cff:
11
+
12
+ Fariello, G. (2026). openas (Version 0.1.0) [Computer software].
13
+ https://github.com/fariello/openas
openas-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,228 @@
1
+ Metadata-Version: 2.4
2
+ Name: openas
3
+ Version: 0.1.0
4
+ Summary: Line-by-line and chunked streaming I/O for plain and compressed files (.gz, .bz2, .xz, .zst) in text or binary mode across local paths, HTTP/HTTPS, FTP, and SSH/SFTP.
5
+ Author: Gabriele Fariello
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/fariello/openas
8
+ Project-URL: Repository, https://github.com/fariello/openas
9
+ Project-URL: Issues, https://github.com/fariello/openas/issues
10
+ Project-URL: Documentation, https://github.com/fariello/openas/blob/main/docs/API.md
11
+ Project-URL: Changelog, https://github.com/fariello/openas/blob/main/CHANGELOG.md
12
+ Keywords: streaming,compression,gzip,bzip2,lzma,zstd,sftp,ftp,http,io,cli
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
16
+ Classifier: Topic :: System :: Archiving :: Compression
17
+ Classifier: Topic :: Utilities
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3.9
20
+ Classifier: Programming Language :: Python :: 3.10
21
+ Classifier: Programming Language :: Python :: 3.11
22
+ Classifier: Programming Language :: Python :: 3.12
23
+ Classifier: Programming Language :: Python :: 3.13
24
+ Classifier: Programming Language :: Python :: 3.14
25
+ Classifier: Operating System :: OS Independent
26
+ Requires-Python: >=3.9
27
+ Description-Content-Type: text/markdown
28
+ License-File: LICENSE
29
+ License-File: NOTICE
30
+ Requires-Dist: paramiko>=2.1
31
+ Requires-Dist: zstandard>=0.14.0
32
+ Requires-Dist: requests>=2.20
33
+ Requires-Dist: tqdm>=4.0
34
+ Requires-Dist: ftputil>=5.0
35
+ Provides-Extra: dev
36
+ Requires-Dist: pytest>=7.0; extra == "dev"
37
+ Dynamic: license-file
38
+
39
+ # openas
40
+
41
+ A lightweight Python library and CLI for streaming plain and compressed files (`.gz`, `.bz2`, `.xz`, `.zst`) line-by-line or in chunks across local paths and remote protocols (`http://`, `https://`, `ftp://`, `ssh://`, `sftp://`), in both text (`str`, UTF-8 by default) and binary (`bytes`) modes.
42
+
43
+ ## Background and Philosophy
44
+
45
+ `openas` started around 2007 as an internal utility to read and write compressed files (such as logs, CSVs, and JSONL) line-by-line without decompressing full files into memory or writing separate boilerplate for each codec and transport. It has now been extracted into a standalone Apache-2.0 package.
46
+
47
+ **How `openas` compares to `smart_open` and `fsspec`:**
48
+ `smart_open` and `fsspec` also support streaming compressed files line-by-line and excel at cloud object stores (`s3://`, `gs://`, Azure) or full virtual filesystem APIs. `openas` focuses on a smaller, self-contained scope:
49
+
50
+ - **Unified line-by-line compressed streaming across local and POSIX/network transports:** Reads and writes plain, `.gz`, `.bz2`, `.xz`, and multi-frame `.zst` streams line-by-line in both text (`str`, UTF-8 by default) and raw binary (`bytes`) modes, without requiring manual `io.TextIOWrapper` or `io.BufferedReader` glue (including for `zstandard`, whose raw `stream_reader` does not support `readline()` directly).
51
+ - **No cloud SDKs and fast startup:** Explicitly excludes cloud object stores (`s3://`, `gs://`, `az://`, `hdfs://`) so it never pulls in cloud SDKs (`boto3`, GCS, Azure). Optional standard-library codecs (`gzip`, `bz2`, `lzma`, `ftplib`, `argparse`, `urllib.parse`) and runtime transport libraries (`paramiko`, `ftputil`, `requests`, `zstandard`, `tqdm`) are imported lazily on first use, while all five runtime dependencies install by default so every documented protocol and codec works immediately.
52
+ - **Built-in transfer tuning, progress, and overwrite safety:** Includes bounded 4 MiB sliding-window SFTP read streaming and write pipelining, thread-local cookie-free HTTP session reuse, raw-byte `tqdm` progress bars (`show_progress=True`), optional sequential `.NNN.bu` backups on overwrite, and a single-pass 64 KiB binary-chunk multi-destination CLI (`--read` / `--write`).
53
+
54
+ See [GUIDING_PRINCIPLES.md](https://github.com/fariello/openas/blob/main/GUIDING_PRINCIPLES.md) and [DECISIONS.md](https://github.com/fariello/openas/blob/main/DECISIONS.md) for design boundaries and architectural trade-offs.
55
+
56
+ ## Features
57
+
58
+ - **Line-by-Line Streaming and Transparent Compression:** Streams plain, `.gz`, `.bz2`, `.xz`, and multi-frame `.zst` files on the fly in text (`'r'`/`'rt'`, `'w'`/`'wt'`, `'a'`/`'at'`, UTF-8 by default with `builtins.open()`-compatible `encoding`, `errors`, and `newline` options) or raw binary (`'rb'`, `'wb'`, `'ab'`) mode. Accepts optional `compresslevel: Optional[int] = None` (defaulting to each library's own setting: `zstd` level 3, `lzma` preset 6, `bz2` level 9, `gzip` level 9).
59
+ - **Local and Remote Protocols:** Reads and writes over local files (`file://` or plain paths), `ssh://`/`sftp://` (read, write, and append, with optional `key_filename`), and `ftp://` (read and write), and streams read-only `http://`/`https://` responses via thread-local, cookie-free `requests.Session` reuse with optional per-request `headers`. Supports an optional `timeout` parameter across all network transports.
60
+ - **SFTP Pipelining, Progress Bars, and Clean Shutdown:** Uses bounded 4 MiB sliding-window SFTP `readv()` streaming (`max_concurrent_prefetch_requests=64`, O(1) memory on multi-GB files), SFTP write pipelining (`set_pipelined(True)`), optional `tqdm` progress bars tracking exact raw bytes read or written (`show_progress=True` on both `OpenAsReader` and `OpenAsWriter`), and deterministic, idempotent handle closure across all transports.
61
+ - **Standard File-Like Interface:** Supports `with` context management, `read()`, binary `read1()`, `readline()`, `readlines()`, line iteration (`for line in f:`), `write()`, `writelines()`, `flush()`, `closed`, `readable()`, `writable()`, `seekable()`, `encoding` (effective encoding string in text mode, `None` in binary mode), and direct `io.TextIOWrapper(openas(path, "rb"))` composition.
62
+ - **Optional Sequential `.bu` Overwrite Backups:** When overwriting an existing file (`backup=True`, default for write modes; pass `backup=False` to disable), moves the existing file to `<path>.001.bu` (checking `.001.bu` first in O(1), then scanning once up to `.999.bu` with a nanosecond timestamp fallback). Local backups use atomic `os.link`/`os.unlink` and reject directories (`IsADirectoryError`).
63
+
64
+ ## Installation
65
+
66
+ Requires Python 3.9 or newer:
67
+
68
+ ```bash
69
+ pip install openas
70
+ ```
71
+
72
+ *Runtime dependencies installed automatically:* `paramiko`, `zstandard`, `requests`, `tqdm`, and `ftputil` (imported lazily on first use).
73
+
74
+ ## Quick Start
75
+
76
+ Use the unified `openas()` function for local or remote compressed streams in text (`str`) or binary (`bytes`) mode.
77
+
78
+ ### Basic Usage
79
+
80
+ ```python
81
+ from openas import openas
82
+
83
+ # 1. Write a compressed text file (optional compresslevel tunes speed vs ratio)
84
+ with openas("events.jsonl.zst", "w", compresslevel=3) as f:
85
+ f.write('{"event": "start"}\n')
86
+
87
+ # 2. Append to the compressed file without creating a .bu backup
88
+ with openas("events.jsonl.zst", "a") as f:
89
+ f.writelines(['{"event": "tick"}\n', '{"event": "stop"}\n'])
90
+
91
+ # 3. Stream the compressed text file back line-by-line
92
+ with openas("events.jsonl.zst", "r") as f:
93
+ for line in f:
94
+ print(line.strip())
95
+
96
+ # 4. Write and stream back a raw binary compressed file (including non-UTF-8 bytes)
97
+ with openas("payload.bin.gz", "wb", backup=False) as f:
98
+ f.write(b"\x00\xffrecord1\nrecord2\n")
99
+
100
+ with openas("payload.bin.gz", "rb") as f:
101
+ for raw_line in f:
102
+ print(raw_line)
103
+ ```
104
+
105
+ ## Capabilities and Support Matrix
106
+
107
+ `openas` handles single-file plain and compressed streams and rejects multi-file container archives to prevent corruption.
108
+
109
+ ### Supported Stream Formats and Protocols
110
+
111
+ | Format / Protocol | Read | Write | Append | Notes |
112
+ | :--- | :---: | :---: | :---: | :--- |
113
+ | Plain Files (`.txt`, `.jsonl`, `.bin`, etc.) | Yes | Yes | Yes | UTF-8 text (`str`) or binary (`bytes`) streams |
114
+ | Zstandard (`.zst`) | Yes | Yes | Yes | Multi-frame line streaming; default write level 3 (tunable via `compresslevel`) |
115
+ | GZIP (`.gz`) | Yes | Yes | Yes | Standard Python `gzip`; default write level 9 (tunable via `compresslevel`) |
116
+ | BZIP2 (`.bz2`) | Yes | Yes | Yes | Standard Python `bz2`; default write level 9 (tunable via `compresslevel`) |
117
+ | LZMA (`.xz`) | Yes | Yes | Yes | Standard Python `lzma`; default write preset 6 (tunable via `compresslevel`) |
118
+ | Local File (`file://` or implicit) | Yes | Yes | Yes | Atomic `os.link`/`os.unlink` sequential `.bu` backups with `.001.bu` fast-path |
119
+ | SSH / SFTP (`ssh://`, `sftp://`) | Yes | Yes | Yes | System host-key verification, bounded 4 MiB SFTP `readv()` streaming, write pipelining, sequential `.bu` backups |
120
+ | FTP (`ftp://`) | Yes | Yes | No | Read and write with sequential `.bu` backups; append raises `UnsupportedProtocolError` |
121
+ | HTTP / HTTPS (`http://`, `https://`) | Yes | No | No | Thread-local cookie-free session reuse; write/append raises `ReadOnlyProtocolError` |
122
+
123
+ ### Unsupported Archive Formats
124
+
125
+ Container archives embed directory tables and multi-file headers rather than a single data stream. Passing any of these extensions raises `UnsupportedArchiveError`:
126
+
127
+ | Container Extensions | Supported | Reason | Alternative |
128
+ | :--- | :---: | :--- | :--- |
129
+ | `.zip` | No | Stream writes overwrite the Central Directory table | Python `zipfile` |
130
+ | `.tar`, `.tar.gz`, `.tgz`, `.tar.bz2`, `.tbz`, `.tbz2`, `.tar.xz`, `.txz`, `.tar.zst`, `.tzst`, `.tar.lzma`, `.tlz`, `.gz.tar`, `.bz2.tar`, `.xz.tar`, `.zst.tar` | No | Contains POSIX tar archive headers | Python `tarfile` |
131
+ | `.rar`, `.7z` | No | Multi-file container formats, not single streams | Dedicated archive libraries |
132
+
133
+ ### Remote Streaming Examples
134
+
135
+ Pass remote URLs directly; `openas` detects `.gz`, `.bz2`, `.xz`, and `.zst` from the URL path (ignoring query strings):
136
+
137
+ ```python
138
+ from openas import openas
139
+
140
+ # Write over SSH/SFTP using an explicit deploy key or SSH agent / ~/.ssh keys
141
+ with openas(
142
+ "sftp://user@hostname/path/to/data.csv.zst",
143
+ "w",
144
+ backup=True,
145
+ timeout=30,
146
+ newline="\n",
147
+ key_filename="/path/to/id_ed25519",
148
+ ) as f:
149
+ f.write("id,name\n1,alice\n")
150
+
151
+ # Stream a remote compressed HTTP file line-by-line with custom request headers
152
+ with openas(
153
+ "https://example.com/data.jsonl.gz",
154
+ "r",
155
+ timeout=30,
156
+ headers={"Authorization": "Bearer <token>", "User-Agent": "my-app/1.0"},
157
+ ) as f:
158
+ for line in f:
159
+ print(line.strip())
160
+ ```
161
+
162
+ > **Credential safety:** Prefer SSH agent, `~/.ssh` keys, or explicit `key_filename` authentication (`sftp://user@host/path/to/file`) over inline passwords (`user:pass@host`). Avoid putting plaintext passwords on command lines where they can appear in shell history or process listings. `openas` redacts URL passwords and query strings in CLI output, `__repr__()`, and archive error messages, and never exposes HTTP `headers` or SSH `key_filename` in `__repr__()`. On cross-host HTTP redirects, `requests` strips `Authorization` automatically while forwarding other custom headers (such as `X-API-Key`).
163
+
164
+ > **Remote URL paths, authentication, and environment variables:** `sftp://` and `ssh://` URLs pass the URL path verbatim as an absolute remote path (for example `/path/to/data.csv.zst`) with no `~/` expansion and do not parse `~/.ssh/config`. Omitting the SSH username defaults to the local OS user authenticating via the SSH agent, `~/.ssh/id_*` keys, or `key_filename`; omitting FTP credentials logs in anonymously. `openas` defines no custom environment variables, while HTTP/HTTPS inherits `requests.Session` `trust_env=True` defaults (`HTTP_PROXY`, `HTTPS_PROXY`, `NO_PROXY`, `REQUESTS_CA_BUNDLE`, `CURL_CA_BUNDLE`, and `~/.netrc`).
165
+
166
+ ## Command-Line Interface
167
+
168
+ Run the built-in CLI via `openas` (installed console script) or `python -m openas`:
169
+
170
+ ```bash
171
+ # Show help and version
172
+ python -m openas --help
173
+ python -m openas --version
174
+
175
+ # Stream compressed files with a progress bar and report line/byte throughput
176
+ python -m openas --read --progress path/to/large.zst
177
+
178
+ # Single-pass broadcast (reads source once and writes to one or more destinations)
179
+ python -m openas --write --compresslevel 6 --timeout 30 https://example.com/data.csv.gz local_copy.txt sftp://user@host/path/to/dest.csv.zst
180
+ ```
181
+
182
+ ## Development and Benchmarks
183
+
184
+ Set up a local development environment (Python 3.9+):
185
+
186
+ ```bash
187
+ git clone https://github.com/fariello/openas.git
188
+ cd openas
189
+ pip install -e ".[dev]"
190
+ python -m pytest -v
191
+ ```
192
+
193
+ Run the optional standalone performance benchmark suite (all temporary files stay inside `tempfile.TemporaryDirectory()`):
194
+
195
+ ```bash
196
+ python benchmarks/bench_openas.py
197
+ ```
198
+
199
+ ## Documentation
200
+
201
+ - [Public API Reference](https://github.com/fariello/openas/blob/main/docs/API.md): Signatures, text and binary modes, parameters, exceptions, and handle lifecycle semantics.
202
+ - [CLI Guide](https://github.com/fariello/openas/blob/main/docs/CLI.md): `--read`, `--write`, `--input-file` / `-i`, `--no-backup`, `--compresslevel` / `-c`, `--timeout`, `--progress`, `--version`, and broadcast behavior.
203
+ - [Architecture Overview](https://github.com/fariello/openas/blob/main/ARCHITECTURE.md): Stream layering, transport wrappers, sequential `.bu` backups, and test structure.
204
+ - [Functional Specification](https://github.com/fariello/openas/blob/main/FUNCTIONAL_SPEC.md): Behavioral contracts, edge cases, non-goals, and security boundaries.
205
+ - [Design Decisions](https://github.com/fariello/openas/blob/main/DECISIONS.md): Rationale and trade-offs behind load-bearing invariants.
206
+ - [Guiding Principles](https://github.com/fariello/openas/blob/main/GUIDING_PRINCIPLES.md): Core engineering boundaries of `openas`.
207
+ - [Changelog](https://github.com/fariello/openas/blob/main/CHANGELOG.md): Release history.
208
+ - [Contributing](https://github.com/fariello/openas/blob/main/CONTRIBUTING.md): Development workflow and testing expectations.
209
+
210
+ ## Troubleshooting and Tips
211
+
212
+ - **SSH `known_hosts` / `RejectPolicy` errors:** `openas` loads system host keys (`load_system_host_keys()`) and enforces Paramiko's `RejectPolicy` to protect against Man-in-the-Middle attacks. If a connection fails because the host key is unknown, verify the server's fingerprint out of band and add the verified host key to `~/.ssh/known_hosts` (for example via an interactive `ssh` check or `ssh-keyscan` after verifying the fingerprint). Do not disable host-key verification.
213
+ - **Special characters in URL credentials or paths:** Percent-encode reserved characters (`@` as `%40`, `:` as `%3A`, `/` as `%2F`, space as `%20`, `%` as `%25`) in `ftp://`, `ssh://`, and `sftp://` URLs (for example `sftp://user@host/path/to/logs%202026/data.gz`, or if inline credentials cannot be avoided, `ftp://user:p%40ss@host/path/to/data.txt`). `openas` decodes FTP/SSH/SFTP credentials and paths automatically via `urllib.parse.unquote()`. Prefer SSH agent or `~/.ssh` key authentication over inline passwords.
214
+ - **`UnsupportedArchiveError` on `.zip` or `.tar.*` files:** `openas` handles single-file streams and rejects multi-file container archives to prevent corrupting archive headers or directory tables. Use Python's `zipfile` module for `.zip` archives and `tarfile` for `.tar` and `.tar.*` archives.
215
+ - **Streaming multi-GB `.zst` and `.gz` corpora in `'rb'` mode:** When downstream parsers accept `bytes` directly (for example JSON or byte-level log parsers), open large compressed files with `'rb'` instead of `'r'`. Binary mode avoids per-line UTF-8 decoding overhead and uses C-level `io.BufferedReader` line scanning; benchmark your own environment with `benchmarks/bench_openas.py`.
216
+
217
+ ## Known Limitations
218
+
219
+ - **Sequential Streaming Only:** Streams do not support random-access `seek()`/`tell()`, read-write modes (`r+`, `w+`, `x`), or asynchronous (`async`/`await`) I/O.
220
+ - **Cloud Object Store Exclusions:** Cloud schemes (`s3://`, `gs://`, `az://`, `hdfs://`) raise `UnsupportedProtocolError`. Use `smart_open`, `fsspec`, or dedicated cloud SDKs instead.
221
+ - **FTP Append Not Supported:** `ftp://` supports read and write only; append mode raises `UnsupportedProtocolError` because `ftputil` does not support FTP append.
222
+ - **Synchronous CLI Fan-Out:** Multi-target `--write` reads the source once in 64 KiB binary chunks via `contextlib.ExitStack` and writes exact bytes synchronously to each destination. Use the Python API with threads or processes for concurrent remote uploads.
223
+
224
+ ## License and Citation
225
+
226
+ Licensed under the Apache License, Version 2.0. See [LICENSE](https://github.com/fariello/openas/blob/main/LICENSE) and [NOTICE](https://github.com/fariello/openas/blob/main/NOTICE).
227
+
228
+ If you use `openas` in academic work, technical reports, or publications, please cite it using [CITATION.cff](https://github.com/fariello/openas/blob/main/CITATION.cff).
openas-0.1.0/README.md ADDED
@@ -0,0 +1,190 @@
1
+ # openas
2
+
3
+ A lightweight Python library and CLI for streaming plain and compressed files (`.gz`, `.bz2`, `.xz`, `.zst`) line-by-line or in chunks across local paths and remote protocols (`http://`, `https://`, `ftp://`, `ssh://`, `sftp://`), in both text (`str`, UTF-8 by default) and binary (`bytes`) modes.
4
+
5
+ ## Background and Philosophy
6
+
7
+ `openas` started around 2007 as an internal utility to read and write compressed files (such as logs, CSVs, and JSONL) line-by-line without decompressing full files into memory or writing separate boilerplate for each codec and transport. It has now been extracted into a standalone Apache-2.0 package.
8
+
9
+ **How `openas` compares to `smart_open` and `fsspec`:**
10
+ `smart_open` and `fsspec` also support streaming compressed files line-by-line and excel at cloud object stores (`s3://`, `gs://`, Azure) or full virtual filesystem APIs. `openas` focuses on a smaller, self-contained scope:
11
+
12
+ - **Unified line-by-line compressed streaming across local and POSIX/network transports:** Reads and writes plain, `.gz`, `.bz2`, `.xz`, and multi-frame `.zst` streams line-by-line in both text (`str`, UTF-8 by default) and raw binary (`bytes`) modes, without requiring manual `io.TextIOWrapper` or `io.BufferedReader` glue (including for `zstandard`, whose raw `stream_reader` does not support `readline()` directly).
13
+ - **No cloud SDKs and fast startup:** Explicitly excludes cloud object stores (`s3://`, `gs://`, `az://`, `hdfs://`) so it never pulls in cloud SDKs (`boto3`, GCS, Azure). Optional standard-library codecs (`gzip`, `bz2`, `lzma`, `ftplib`, `argparse`, `urllib.parse`) and runtime transport libraries (`paramiko`, `ftputil`, `requests`, `zstandard`, `tqdm`) are imported lazily on first use, while all five runtime dependencies install by default so every documented protocol and codec works immediately.
14
+ - **Built-in transfer tuning, progress, and overwrite safety:** Includes bounded 4 MiB sliding-window SFTP read streaming and write pipelining, thread-local cookie-free HTTP session reuse, raw-byte `tqdm` progress bars (`show_progress=True`), optional sequential `.NNN.bu` backups on overwrite, and a single-pass 64 KiB binary-chunk multi-destination CLI (`--read` / `--write`).
15
+
16
+ See [GUIDING_PRINCIPLES.md](https://github.com/fariello/openas/blob/main/GUIDING_PRINCIPLES.md) and [DECISIONS.md](https://github.com/fariello/openas/blob/main/DECISIONS.md) for design boundaries and architectural trade-offs.
17
+
18
+ ## Features
19
+
20
+ - **Line-by-Line Streaming and Transparent Compression:** Streams plain, `.gz`, `.bz2`, `.xz`, and multi-frame `.zst` files on the fly in text (`'r'`/`'rt'`, `'w'`/`'wt'`, `'a'`/`'at'`, UTF-8 by default with `builtins.open()`-compatible `encoding`, `errors`, and `newline` options) or raw binary (`'rb'`, `'wb'`, `'ab'`) mode. Accepts optional `compresslevel: Optional[int] = None` (defaulting to each library's own setting: `zstd` level 3, `lzma` preset 6, `bz2` level 9, `gzip` level 9).
21
+ - **Local and Remote Protocols:** Reads and writes over local files (`file://` or plain paths), `ssh://`/`sftp://` (read, write, and append, with optional `key_filename`), and `ftp://` (read and write), and streams read-only `http://`/`https://` responses via thread-local, cookie-free `requests.Session` reuse with optional per-request `headers`. Supports an optional `timeout` parameter across all network transports.
22
+ - **SFTP Pipelining, Progress Bars, and Clean Shutdown:** Uses bounded 4 MiB sliding-window SFTP `readv()` streaming (`max_concurrent_prefetch_requests=64`, O(1) memory on multi-GB files), SFTP write pipelining (`set_pipelined(True)`), optional `tqdm` progress bars tracking exact raw bytes read or written (`show_progress=True` on both `OpenAsReader` and `OpenAsWriter`), and deterministic, idempotent handle closure across all transports.
23
+ - **Standard File-Like Interface:** Supports `with` context management, `read()`, binary `read1()`, `readline()`, `readlines()`, line iteration (`for line in f:`), `write()`, `writelines()`, `flush()`, `closed`, `readable()`, `writable()`, `seekable()`, `encoding` (effective encoding string in text mode, `None` in binary mode), and direct `io.TextIOWrapper(openas(path, "rb"))` composition.
24
+ - **Optional Sequential `.bu` Overwrite Backups:** When overwriting an existing file (`backup=True`, default for write modes; pass `backup=False` to disable), moves the existing file to `<path>.001.bu` (checking `.001.bu` first in O(1), then scanning once up to `.999.bu` with a nanosecond timestamp fallback). Local backups use atomic `os.link`/`os.unlink` and reject directories (`IsADirectoryError`).
25
+
26
+ ## Installation
27
+
28
+ Requires Python 3.9 or newer:
29
+
30
+ ```bash
31
+ pip install openas
32
+ ```
33
+
34
+ *Runtime dependencies installed automatically:* `paramiko`, `zstandard`, `requests`, `tqdm`, and `ftputil` (imported lazily on first use).
35
+
36
+ ## Quick Start
37
+
38
+ Use the unified `openas()` function for local or remote compressed streams in text (`str`) or binary (`bytes`) mode.
39
+
40
+ ### Basic Usage
41
+
42
+ ```python
43
+ from openas import openas
44
+
45
+ # 1. Write a compressed text file (optional compresslevel tunes speed vs ratio)
46
+ with openas("events.jsonl.zst", "w", compresslevel=3) as f:
47
+ f.write('{"event": "start"}\n')
48
+
49
+ # 2. Append to the compressed file without creating a .bu backup
50
+ with openas("events.jsonl.zst", "a") as f:
51
+ f.writelines(['{"event": "tick"}\n', '{"event": "stop"}\n'])
52
+
53
+ # 3. Stream the compressed text file back line-by-line
54
+ with openas("events.jsonl.zst", "r") as f:
55
+ for line in f:
56
+ print(line.strip())
57
+
58
+ # 4. Write and stream back a raw binary compressed file (including non-UTF-8 bytes)
59
+ with openas("payload.bin.gz", "wb", backup=False) as f:
60
+ f.write(b"\x00\xffrecord1\nrecord2\n")
61
+
62
+ with openas("payload.bin.gz", "rb") as f:
63
+ for raw_line in f:
64
+ print(raw_line)
65
+ ```
66
+
67
+ ## Capabilities and Support Matrix
68
+
69
+ `openas` handles single-file plain and compressed streams and rejects multi-file container archives to prevent corruption.
70
+
71
+ ### Supported Stream Formats and Protocols
72
+
73
+ | Format / Protocol | Read | Write | Append | Notes |
74
+ | :--- | :---: | :---: | :---: | :--- |
75
+ | Plain Files (`.txt`, `.jsonl`, `.bin`, etc.) | Yes | Yes | Yes | UTF-8 text (`str`) or binary (`bytes`) streams |
76
+ | Zstandard (`.zst`) | Yes | Yes | Yes | Multi-frame line streaming; default write level 3 (tunable via `compresslevel`) |
77
+ | GZIP (`.gz`) | Yes | Yes | Yes | Standard Python `gzip`; default write level 9 (tunable via `compresslevel`) |
78
+ | BZIP2 (`.bz2`) | Yes | Yes | Yes | Standard Python `bz2`; default write level 9 (tunable via `compresslevel`) |
79
+ | LZMA (`.xz`) | Yes | Yes | Yes | Standard Python `lzma`; default write preset 6 (tunable via `compresslevel`) |
80
+ | Local File (`file://` or implicit) | Yes | Yes | Yes | Atomic `os.link`/`os.unlink` sequential `.bu` backups with `.001.bu` fast-path |
81
+ | SSH / SFTP (`ssh://`, `sftp://`) | Yes | Yes | Yes | System host-key verification, bounded 4 MiB SFTP `readv()` streaming, write pipelining, sequential `.bu` backups |
82
+ | FTP (`ftp://`) | Yes | Yes | No | Read and write with sequential `.bu` backups; append raises `UnsupportedProtocolError` |
83
+ | HTTP / HTTPS (`http://`, `https://`) | Yes | No | No | Thread-local cookie-free session reuse; write/append raises `ReadOnlyProtocolError` |
84
+
85
+ ### Unsupported Archive Formats
86
+
87
+ Container archives embed directory tables and multi-file headers rather than a single data stream. Passing any of these extensions raises `UnsupportedArchiveError`:
88
+
89
+ | Container Extensions | Supported | Reason | Alternative |
90
+ | :--- | :---: | :--- | :--- |
91
+ | `.zip` | No | Stream writes overwrite the Central Directory table | Python `zipfile` |
92
+ | `.tar`, `.tar.gz`, `.tgz`, `.tar.bz2`, `.tbz`, `.tbz2`, `.tar.xz`, `.txz`, `.tar.zst`, `.tzst`, `.tar.lzma`, `.tlz`, `.gz.tar`, `.bz2.tar`, `.xz.tar`, `.zst.tar` | No | Contains POSIX tar archive headers | Python `tarfile` |
93
+ | `.rar`, `.7z` | No | Multi-file container formats, not single streams | Dedicated archive libraries |
94
+
95
+ ### Remote Streaming Examples
96
+
97
+ Pass remote URLs directly; `openas` detects `.gz`, `.bz2`, `.xz`, and `.zst` from the URL path (ignoring query strings):
98
+
99
+ ```python
100
+ from openas import openas
101
+
102
+ # Write over SSH/SFTP using an explicit deploy key or SSH agent / ~/.ssh keys
103
+ with openas(
104
+ "sftp://user@hostname/path/to/data.csv.zst",
105
+ "w",
106
+ backup=True,
107
+ timeout=30,
108
+ newline="\n",
109
+ key_filename="/path/to/id_ed25519",
110
+ ) as f:
111
+ f.write("id,name\n1,alice\n")
112
+
113
+ # Stream a remote compressed HTTP file line-by-line with custom request headers
114
+ with openas(
115
+ "https://example.com/data.jsonl.gz",
116
+ "r",
117
+ timeout=30,
118
+ headers={"Authorization": "Bearer <token>", "User-Agent": "my-app/1.0"},
119
+ ) as f:
120
+ for line in f:
121
+ print(line.strip())
122
+ ```
123
+
124
+ > **Credential safety:** Prefer SSH agent, `~/.ssh` keys, or explicit `key_filename` authentication (`sftp://user@host/path/to/file`) over inline passwords (`user:pass@host`). Avoid putting plaintext passwords on command lines where they can appear in shell history or process listings. `openas` redacts URL passwords and query strings in CLI output, `__repr__()`, and archive error messages, and never exposes HTTP `headers` or SSH `key_filename` in `__repr__()`. On cross-host HTTP redirects, `requests` strips `Authorization` automatically while forwarding other custom headers (such as `X-API-Key`).
125
+
126
+ > **Remote URL paths, authentication, and environment variables:** `sftp://` and `ssh://` URLs pass the URL path verbatim as an absolute remote path (for example `/path/to/data.csv.zst`) with no `~/` expansion and do not parse `~/.ssh/config`. Omitting the SSH username defaults to the local OS user authenticating via the SSH agent, `~/.ssh/id_*` keys, or `key_filename`; omitting FTP credentials logs in anonymously. `openas` defines no custom environment variables, while HTTP/HTTPS inherits `requests.Session` `trust_env=True` defaults (`HTTP_PROXY`, `HTTPS_PROXY`, `NO_PROXY`, `REQUESTS_CA_BUNDLE`, `CURL_CA_BUNDLE`, and `~/.netrc`).
127
+
128
+ ## Command-Line Interface
129
+
130
+ Run the built-in CLI via `openas` (installed console script) or `python -m openas`:
131
+
132
+ ```bash
133
+ # Show help and version
134
+ python -m openas --help
135
+ python -m openas --version
136
+
137
+ # Stream compressed files with a progress bar and report line/byte throughput
138
+ python -m openas --read --progress path/to/large.zst
139
+
140
+ # Single-pass broadcast (reads source once and writes to one or more destinations)
141
+ python -m openas --write --compresslevel 6 --timeout 30 https://example.com/data.csv.gz local_copy.txt sftp://user@host/path/to/dest.csv.zst
142
+ ```
143
+
144
+ ## Development and Benchmarks
145
+
146
+ Set up a local development environment (Python 3.9+):
147
+
148
+ ```bash
149
+ git clone https://github.com/fariello/openas.git
150
+ cd openas
151
+ pip install -e ".[dev]"
152
+ python -m pytest -v
153
+ ```
154
+
155
+ Run the optional standalone performance benchmark suite (all temporary files stay inside `tempfile.TemporaryDirectory()`):
156
+
157
+ ```bash
158
+ python benchmarks/bench_openas.py
159
+ ```
160
+
161
+ ## Documentation
162
+
163
+ - [Public API Reference](https://github.com/fariello/openas/blob/main/docs/API.md): Signatures, text and binary modes, parameters, exceptions, and handle lifecycle semantics.
164
+ - [CLI Guide](https://github.com/fariello/openas/blob/main/docs/CLI.md): `--read`, `--write`, `--input-file` / `-i`, `--no-backup`, `--compresslevel` / `-c`, `--timeout`, `--progress`, `--version`, and broadcast behavior.
165
+ - [Architecture Overview](https://github.com/fariello/openas/blob/main/ARCHITECTURE.md): Stream layering, transport wrappers, sequential `.bu` backups, and test structure.
166
+ - [Functional Specification](https://github.com/fariello/openas/blob/main/FUNCTIONAL_SPEC.md): Behavioral contracts, edge cases, non-goals, and security boundaries.
167
+ - [Design Decisions](https://github.com/fariello/openas/blob/main/DECISIONS.md): Rationale and trade-offs behind load-bearing invariants.
168
+ - [Guiding Principles](https://github.com/fariello/openas/blob/main/GUIDING_PRINCIPLES.md): Core engineering boundaries of `openas`.
169
+ - [Changelog](https://github.com/fariello/openas/blob/main/CHANGELOG.md): Release history.
170
+ - [Contributing](https://github.com/fariello/openas/blob/main/CONTRIBUTING.md): Development workflow and testing expectations.
171
+
172
+ ## Troubleshooting and Tips
173
+
174
+ - **SSH `known_hosts` / `RejectPolicy` errors:** `openas` loads system host keys (`load_system_host_keys()`) and enforces Paramiko's `RejectPolicy` to protect against Man-in-the-Middle attacks. If a connection fails because the host key is unknown, verify the server's fingerprint out of band and add the verified host key to `~/.ssh/known_hosts` (for example via an interactive `ssh` check or `ssh-keyscan` after verifying the fingerprint). Do not disable host-key verification.
175
+ - **Special characters in URL credentials or paths:** Percent-encode reserved characters (`@` as `%40`, `:` as `%3A`, `/` as `%2F`, space as `%20`, `%` as `%25`) in `ftp://`, `ssh://`, and `sftp://` URLs (for example `sftp://user@host/path/to/logs%202026/data.gz`, or if inline credentials cannot be avoided, `ftp://user:p%40ss@host/path/to/data.txt`). `openas` decodes FTP/SSH/SFTP credentials and paths automatically via `urllib.parse.unquote()`. Prefer SSH agent or `~/.ssh` key authentication over inline passwords.
176
+ - **`UnsupportedArchiveError` on `.zip` or `.tar.*` files:** `openas` handles single-file streams and rejects multi-file container archives to prevent corrupting archive headers or directory tables. Use Python's `zipfile` module for `.zip` archives and `tarfile` for `.tar` and `.tar.*` archives.
177
+ - **Streaming multi-GB `.zst` and `.gz` corpora in `'rb'` mode:** When downstream parsers accept `bytes` directly (for example JSON or byte-level log parsers), open large compressed files with `'rb'` instead of `'r'`. Binary mode avoids per-line UTF-8 decoding overhead and uses C-level `io.BufferedReader` line scanning; benchmark your own environment with `benchmarks/bench_openas.py`.
178
+
179
+ ## Known Limitations
180
+
181
+ - **Sequential Streaming Only:** Streams do not support random-access `seek()`/`tell()`, read-write modes (`r+`, `w+`, `x`), or asynchronous (`async`/`await`) I/O.
182
+ - **Cloud Object Store Exclusions:** Cloud schemes (`s3://`, `gs://`, `az://`, `hdfs://`) raise `UnsupportedProtocolError`. Use `smart_open`, `fsspec`, or dedicated cloud SDKs instead.
183
+ - **FTP Append Not Supported:** `ftp://` supports read and write only; append mode raises `UnsupportedProtocolError` because `ftputil` does not support FTP append.
184
+ - **Synchronous CLI Fan-Out:** Multi-target `--write` reads the source once in 64 KiB binary chunks via `contextlib.ExitStack` and writes exact bytes synchronously to each destination. Use the Python API with threads or processes for concurrent remote uploads.
185
+
186
+ ## License and Citation
187
+
188
+ Licensed under the Apache License, Version 2.0. See [LICENSE](https://github.com/fariello/openas/blob/main/LICENSE) and [NOTICE](https://github.com/fariello/openas/blob/main/NOTICE).
189
+
190
+ If you use `openas` in academic work, technical reports, or publications, please cite it using [CITATION.cff](https://github.com/fariello/openas/blob/main/CITATION.cff).