Metadata-Version: 2.1
Name: tapest-client
Version: 0.0.17
Summary: TapeSt API command-line tool and client library
Home-page: https://github.com/Digital-Preservation-Finland/tapest-client
Author: CSC — IT Center for Science
Author-email: pas-support@csc.fi
License: AGPL-3.0-or-later
Platform: linux
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: certifi
Requires-Dist: platformdirs
Requires-Dist: requests
Requires-Dist: tuspy @ git+https://github.com/tus/tus-py-client.git@e786fa850f0d8e0a2bd137dd91b5fef7c7b703a7
Provides-Extra: testing
Requires-Dist: pytest ; extra == 'testing'
Requires-Dist: pytest-benchmark ; extra == 'testing'

# tapest-client

TapeSt API command-line tool and Python library for interacting with
the TapeSt API service.

Used by `tapest-tape-worker` and by the storage clients of TapeSt.

## Quick start

Install using RPM (preferred):

```
sudo dnf install python3-tapest-client
```

Or install from source:

```
git clone https://github.com/Digital-Preservation-Finland/tapest-client.git
cd tapest-client
pip install .
```

Create a configuration file and write the token and the host into the file:

```
tapest-client write-config
vi ~/.config/tapest-client/client.conf
```

Check the connection:

```
tapest-client status
```

## Configuration

The CLI looks for configuration in this order:

1. `--config /path/to/config.conf` (explicit)
2. `/etc/tapest-client/client.conf` (system-wide)
3. `~/.config/tapest-client/client.conf` (user-level)

Environment variables (`TAPEST_CLIENT_*`) override file values,
e.g. `TAPEST_CLIENT_TOKEN`.

Config file format (JSON):

```json
{
  "token": "<token>",
  "host": "https://tapest.example.com",
  "verify_ssl": true
}
```

### Config fields

| Field                               | Type   | Default                     | Description                                                                                                            |
|-------------------------------------|--------|-----------------------------|------------------------------------------------------------------------------------------------------------------------|
| `token`                             | string | `""`                        | API token for authentication.                                                                                          |
| `host`                              | string | `""`                        | TapeSt API host URL.                                                                                                   |
| `storage_account_name`              | string | `""`                        | Account name used for storage operations. Only needed for agent accounts; leave empty for storage client accounts.     |
| `max_retry_attempts`                | int    | `10`                        | Maximum number of retry attempts when an ingest or recache upload gets 202.                                            |
| `default_sleep_duration`            | int    | `120`                       | Sleep duration (seconds) between retries when the service gives no Retry-After.                                        |
| `extract_timeout`                   | int    | `7200`                      | Seconds an extract waits for the next file to come from tape. A file that arrives starts the wait again.               |
| `cleanup_on_fail`                   | bool   | `false`                     | Remove local files on failed operations.                                                                               |
| `verify_ssl`                        | bool   | `true`                      | Verify the SSL certificate of the host. Do *not* change this except for testing purposes.                              |
| `ca_cert_path`                      | string | `""`                        | Path to a CA certificate bundle (PEM). When set, overrides the default certifi bundle. Leave empty to use the default. |
| `tus_chunk_size`                    | string | `"16 MiB"`                  | Size of one chunk of a chunked TUS upload.                                                                             |
| `tus_creation_with_upload_max_size` | string | `"1 GiB"`                   | Largest file sent as one TUS creation-with-upload POST. A larger file is sent in chunks.                               |
| `partfile_suffix`                   | string | `".tapest-client-partfile"` | Suffix of the partial file of a download. See [Extract](#extract-download).                                            |

## File identifiers

The client sends an identifier as a path with one leading slash (`a//b/./c`
becomes `/a/b/c`). The API stores identifiers in UTF-8 NFC, so the identifier
in a response can differ from the identifier sent (NFD `a` + combining
diaeresis comes back as NFC `ä`).

## Command-line usage

For per-command help, use `tapest-client <command> --help`.

### Global options

| Flag              | Description                                      |
|-------------------|--------------------------------------------------|
| `-v`, `--verbose` | Verbose output                                   |
| `--debug`         | Debug output (implies verbose)                   |
| `--config`        | Configuration file                               |
| `--host`          | API host URL                                     |
| `--ca-cert PATH`  | CA certificate bundle (PEM) for SSL verification |

The global options are accepted before and after the command:
`tapest-client -v --config c.conf ingest file.dat` and
`tapest-client ingest file.dat -v --config c.conf` are the same command.

Uploads use the TUS protocol: one POST up to
`tus_creation_with_upload_max_size`, chunks of `tus_chunk_size` above that size.

### Ingest (upload)

```
tapest-client ingest PATH [PATH ...] [--identifier ID] [--checksum SHA256]
                     [--prefix PFX] [--skip] [--client-metadata JSON]
```

`ingest` accepts any mix of file paths and directory paths. Directories are
walked recursively.

Without `--prefix`, the identifier of a file is the path of the file as given
on the command line:

```
tapest-client ingest data/assets/
# data/assets/2026/x.ts  ->  /data/assets/2026/x.ts
```

With `--prefix`, the identifier of a file in a directory is the prefix and the
path of the file inside the directory. For a file path, the identifier is the
prefix and the file name. A relative and an absolute path of the same
directory result in the same identifiers:

```
tapest-client ingest --prefix /archived /data/assets/
# /data/assets/2026/x.ts  ->  /archived/2026/x.ts
tapest-client ingest --prefix /archived /data/assets/2026/x.ts
# /data/assets/2026/x.ts  ->  /archived/x.ts
```

`--identifier` gives the identifier of one file, independent of the local
path, and is accepted with exactly one PATH.

`--checksum` is the SHA-256 of one file, 64 hex digits, and is accepted with
exactly one PATH. The service computes the SHA-256 of the upload and refuses
the file when the two checksums differ. Without `--checksum`, the client
computes the SHA-256 of the file.

`--client-metadata` gives a JSON object, for example more checksums. The
service stores the object with all new files of the run, in the field
`client_metadata`. The JSON is at most 4096 bytes as UTF-8, without `NaN` or
`Infinity`, and no key at any depth starts with `$`. A later ingest of a
stored file keeps the stored `client_metadata`.

The client continues an interrupted ingest at the next attempt: the client
keeps the upload URL and sends the rest of the file. The service keeps the
checksum and the `client_metadata` of the first attempt. When the next
attempt has a different checksum or `client_metadata`, the client stops with
an error. To continue the upload, ingest with the values of the first
attempt. To send new values, delete the identifier with `tapest-client
delete` and ingest the file again.

Examples:

```
tapest-client ingest 2024/q1/*.dat 2024/q2/*.dat
tapest-client ingest --prefix /acme some_dir extra-file.dat --skip
tapest-client ingest --identifier /path/to/identifier /local/file.dat
tapest-client ingest --identifier /path/to/identifier --checksum "$(sha256sum file.dat | cut -d' ' -f1)" file.dat
tapest-client ingest --client-metadata '{"sha1": "da39a3ee5e6b4b0d3255bfef95601890afd80709"}' file.dat
```

### Extract (download)

```
tapest-client extract FILE_ID [FILE_ID ...] DEST [--force] [--no-wait]
tapest-client extract --prefix PFX DEST [--force] [--no-wait]
```

The last argument is the destination: a file when one identifier is given
and the destination is not a directory that exists, and a directory in all
other cases.

A file that is on tape only must be read back into the cache first. By
default, extract waits for these files. When no file arrives in
`extract_timeout` seconds, extract exits with code 117. With `--no-wait`,
extract takes only the files that are in the cache now and exits with code 0.
Run the command again later to get the other files.

A download is written to `<DEST><partfile_suffix>` first, and renamed to
`DEST` after the size and the checksum match the metadata. When an interrupted
download left a partial file, the next extract continues from the end of the
partial file with a range request (206). With `cleanup_on_fail`, a size or
checksum mismatch removes the partial file.

The service refuses an upload when the SHA-256 of the upload differs from
the checksum of the ingest. A refused file has no tape copy, and the service
keeps only the record of the file. With several files, `extract` skips a
refused file, extracts the other files, lists the skipped files at the end
and exits with code 1. `tapest-client delete` removes the record of a refused
file. `extract` also skips a file with a failed checksum verification after
the recall from tape; the administrators handle such a file.

Examples:

```
tapest-client extract /path/to/identifier /local/output.dat
tapest-client extract /data/a.dat /data/b.dat /local/dir
tapest-client extract --prefix /data /local/dir --no-wait
```

### Delete

```
tapest-client delete FILE_ID [FILE_ID ...]
```

### Query metadata

```
tapest-client query-metadata [FILE_ID] [options]
```

| Flag           | Description                                       |
|----------------|---------------------------------------------------|
| `--prefix`     | File identifier prefix (repeatable)               |
| `--regex`      | File identifier regex pattern (repeatable)        |
| `--parent`     | List one directory level under PATH               |
| `--identifier` | File identifier (repeatable)                      |
| `--storage`    | Storage name                                      |
| `--limit`      | Page size, at most 1000 files                     |
| `--page-token` | Resume from a previous page's nextPageToken       |
| `--pending`    | Pending files only                                |
| `--errors`     | Files with errors only                            |
| `--order`      | Order by `identifier` (default) or `ingested`     |
| `--desc`       | Sort descending (use with `--order`)              |
| `--format`     | `json` (default) or `table` (copies of the files) |

`--regex` is a MongoDB `$regex` pattern, unanchored (use `^` and `$` to
anchor), and matches the files of the account of the token only. Quote the
pattern for the shell.

`--parent PATH` lists one directory level (like `ls`, not `ls -R`): the files
of the directory in `metadata`, the subdirectories in `commonPrefixes`, ending in
`/`. An empty path or `/` lists the root.

A page holds at most 1000 files. When more files match, pass the
`nextPageToken` of the response to `--page-token`.

Examples:

```
tapest-client query-metadata /path/to/identifier
tapest-client query-metadata --pending
tapest-client query-metadata --prefix /prefix --limit 100
tapest-client query-metadata --regex '/2022/.*\.dat$'
tapest-client query-metadata --parent /200182/2022/
tapest-client query-metadata --prefix /200182/ --order ingested --desc --limit 1000
tapest-client query-metadata --prefix /200182/ --limit 1000 --page-token <nextPageToken>
```

### Update metadata

The file is named by the internal `file_id`, which only tokens that are not
storage client tokens may use.

```
tapest-client update-metadata FILE_ID [JSON] [--file FILE] [--stdin]
```

JSON can be provided as:
- Inline string: `tapest-client update-metadata /id '{"key": "val"}'`
- From file: `tapest-client update-metadata /id --file update.json`
- From stdin: `cat update.json | tapest-client update-metadata /id --stdin`
- From stdin (POSIX): `cat update.json | tapest-client update-metadata /id -`

### Output

Logs go to stderr, data to stdout. A command that handles one file prints one
JSON object. `ingest PATH...` and `extract FILE_ID... DEST` print one JSON
record per line, as soon as a file is done, so the output of a long run can be
read and piped during the run:

```
tapest-client ingest --prefix acme some_dir | jq -r .identifier
```

### Batch option flags

| Flag        | `ingest`                                  | `extract`                                                |
|-------------|-------------------------------------------|----------------------------------------------------------|
| `--skip`    | Do not send a file that is stored already | not available (a local file that matches is always kept) |
| `--force`   | not available                             | Overwrite a local file that differs                      |
| `--no-wait` | not available                             | Take only the files that are in the cache now            |

`ingest` of an identifier in use is an error. `delete` frees the identifier at
once, and `ingest` with the same identifier then sends the new content.

### Other commands

```
tapest-client status                 # Retrieve service status
tapest-client write-config           # Create default configuration file
```

## Python library usage

The commands of `tapest-client` call the functions of the `tapest_client`
package. A command runs in a new Python interpreter, so a program that sends
many files calls the functions in one Python process.

### Config

```python
import tapest_client

config = tapest_client.Config()
config.read("/home/user/.config/tapest-client/prod.conf")
```

- `tapest_client.get_config()` reads `/etc/tapest-client/client.conf`.
- `tapest_client.Config(host="https://api.tapest.csc.fi", token="<token>")`
  sets the values in the code.

### Commands and functions

| Command                                         | Function                                                                     | Return value                                |
|-------------------------------------------------|------------------------------------------------------------------------------|---------------------------------------------|
| `ingest`, one file                              | `ingest_file(config, identifier, path, checksum=None, client_metadata=None)` | metadata of the file                        |
| `query-metadata IDENTIFIER`                     | `retrieve_file_metadata(config, identifier)`                                 | metadata of the file                        |
| `query-metadata IDENTIFIER`, unknown identifier | `retrieve_file_metadata(config, identifier, missing_ok=True)`                | `None`                                      |
| `query-metadata --prefix`, `--regex`            | `retrieve_metadata(config, query)`                                           | `{"metadata": [...], "nextPageToken": ...}` |
| `extract`, one file                             | `extract_file(config, identifier, local_path)`                               | metadata of the file                        |
| `delete`                                        | `delete_file(config, identifier)`                                            | `None`                                      |
| `status`                                        | `retrieve_status(config)`                                                    | `{"tapest_api_version": ...}`               |

### Errors

The functions raise exceptions in place of the exit codes of the command line.

| Command line                                                      | Library                                                              |
|-------------------------------------------------------------------|----------------------------------------------------------------------|
| exit code 0                                                       | the return value                                                     |
| exit code 1                                                       | `TapestClientError`, with the status code and the message of the API |
| exit code 1, connection failed                                    | `requests.ConnectionError`                                           |
| exit code 117, the file is on tape only                           | `extract_file` waits, then `TapestClientError`                       |
| `extract`: the local file exists                                  | `FileAlreadyExistsError`, also a `FileExistsError`                   |
| `extract`: the checksum verification of the file failed in TapeSt | `VerifyFailedError`, also a `TapestClientError`                      |
| exit code 130, Ctrl-C                                             | `KeyboardInterrupt`                                                  |

- `extract_file` waits until the file is read from tape: `extract_timeout`
  seconds (default 7200), or longer for a file that takes longer to read at
  100 MB/s.
- `extract_file` checks the size and the SHA-256 of the written file. On a
  mismatch, `extract_file` deletes the file and raises `TapestClientError`.

### Many files, with a checksum and client metadata per file

```python
for identifier, path, sha256, sha1 in files:
    tapest_client.ingest_file(
        config,
        identifier,
        path,
        checksum=f"sha256:{sha256}",
        client_metadata={"sha1": sha1},
    )
```

- `checksum` is `sha256:` and 64 lowercase hex digits. Without `checksum`,
  the client computes the SHA-256 of the local file.
- `client_metadata` is a JSON object of at most 4096 bytes. TapeSt keeps the
  client metadata of the first `ingest_file` call of an identifier.

### Queries

```python
# Exact identifiers
tapest_client.retrieve_metadata(config, {"identifiers": ["/a/x.ts", "/a/y.ts"]})

# All identifiers that start with a prefix
tapest_client.retrieve_metadata(config, {"prefixes": ["/a/"]})
```

`retrieve_metadata` returns at most 1000 files per call. The next pages:

```python
query = {"prefixes": ["/a/"]}
while True:
    result = tapest_client.retrieve_metadata(config, query)
    for file_metadata in result["metadata"]:
        print(file_metadata["identifier"])
    if not result.get("nextPageToken"):
        break
    query["page_token"] = result["nextPageToken"]
```

### Files that already exist

- `ingest_file` of an identifier in use raises `TapestClientError` with the
  message of the server.
- `ingest_file` of the same file again, with the same checksum and size,
  returns the stored metadata. The stored client metadata stays.
- `delete_file` frees the identifier at once; `ingest_file` with the same
  identifier then sends the new content.
- To skip a file that is already stored, compare
  `retrieve_file_metadata(config, identifier, missing_ok=True)` with
  `generate_checksum(path)`. `--skip` of the command line does the same.

## Testing

```
pip install -e .[testing]
pytest
```

### Benchmarks

SHA-256 buffer size benchmark (pytest-benchmark). Without `--run-slow` the
benchmarks are skipped:

```
pytest tests/benchmark --run-slow --benchmark-enable -v
```

To benchmark on a specific directory (e.g. a cache volume):

```
BENCHMARK_DIR=/mnt/storage/cache_vol01 pytest tests/benchmark --run-slow --benchmark-enable -v
```

## Releasing

The version comes from the git tag (setuptools_scm). Add the version to
`CHANGELOG.md`, then tag the repository:

```
git tag -a v<major>.<minor>.<patch> -m 'Version <major>.<minor>.<patch>'
git push -u origin v<major>.<minor>.<patch>
```


