Metadata-Version: 2.1
Name: tapest-client
Version: 0.0.16
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 fill in your credentials:

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

Verify it works:

```
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. Replace with your own token.                                                             |
| `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. Each 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 one you 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 it.

### 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, thus the identifier and
the local path can be different. It accepts 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. The service stores this object with
each new file of the run, in the field `client_metadata`. Use it, for example,
to store more checksums. Its JSON must be at most 4096 bytes as UTF-8, without
`NaN` or `Infinity`, and no key at any depth starts with `$`.

The service stores the object at ingest, and a later ingest does not change
it. If the file is stored already (a file that `--skip` skips, or an
identical file), the stored `client_metadata` stays, also when the object of
the ingest differs.

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. It is a file when one identifier is
given and the destination is not a directory that exists. In each other
case it is a directory.

A file that is on tape only must be read back into the cache first. By
default, extract waits for these files. It stops when no file arrives in
`extract_timeout` seconds, and then 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 (a page holds 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 every file) |

`--regex` is a MongoDB `$regex` pattern, unanchored (use `^` and `$` to
anchor). It matches only the files of your own account. 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 its 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 each file is done, so the output of a long run can be read
and piped while it runs:

```
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              |

An identifier that has been used is not free again, not even after `delete`, so
`ingest` cannot replace a stored file. A local file that differs from the stored
one is an error. Use a new identifier for new content.

### Other commands

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

## Python library usage

### With config file

```python
from tapest_client import get_config, extract_file

config = get_config()  # loads from /etc/tapest-client/client.conf
metadata = extract_file(config, "/path/to/file", "/local/path")
```

### With explicit config

```python
from tapest_client import Config, extract_file

config = Config(
    host="https://tapest.example.com",
    token="<token>",
)

metadata = extract_file(config, "/path/to/file", "/local/path")
```

### Files that already exist

`ingest_file` raises `TapestClientError` with the message of the server when
a different file has the identifier. Your application decides what happens
next.

```python
from tapest_client import TapestClientError, ingest_file

for identifier, path in files:
    try:
        ingest_file(config, identifier, path)
    except TapestClientError as error:
        logger.warning("File %s not sent: %s", identifier, error)
```

An identifier that has been used is not free again, not even after `delete_file`,
so the file cannot be replaced. Send new content under a new identifier.

To send nothing for a file that is already stored, read the metadata first with
`retrieve_file_metadata(config, identifier, missing_ok=True)` and compare it to
`generate_checksum(path)`. This is what `--skip` of the command-line client
does.

## 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>
```


