Metadata-Version: 2.5
Name: runline-u
Version: 0.1.6
Summary: Python client for Runline's U data distribution platform.
Project-URL: Homepage, https://www.runline.com/
Author-email: Runline <support@runline.com>
License-Expression: LicenseRef-Proprietary
License-File: LICENSE
Keywords: client,data-distribution,runline,u
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Office/Business :: Financial :: Spreadsheet
Requires-Python: >=3.8
Provides-Extra: dev
Requires-Dist: build; extra == 'dev'
Requires-Dist: pytest>=7.0; extra == 'dev'
Requires-Dist: twine; extra == 'dev'
Description-Content-Type: text/markdown

# Runline U Python Client

This package provides a Python API for interacting with Runline's U platform. Use of Runline services requires an active Runline customer account and any required service credentials.

The package is publicly downloadable for customer convenience, but it remains subject to the included proprietary license.

## Installation

```bash
pip install runline-u
```

For local development from this repository:

```bash
pip install -e ".[dev]"
```

## Usage

### Early Access HTTP API

Use `U` to publish, get, and subscribe through a Runline HTTP API endpoint:

```python
import os

from runline_u import U

username = os.environ["RUNLINE_USERNAME"]
topic = "{0}/EXAMPLES/PRICES".format(username)


def on_report(report):
    print(report.topic, report.first_page)


with U(
    "https://api.example.com",
    api_key=os.environ["RUNLINE_API_KEY"],
    message_callback=on_report,
) as u:
    u.publish(
        topic=topic,
        single_page_content=[["Symbol", "Price"], ["ABC", 123.45]],
    )

    current = u.get(topic)
    u.subscribe(topic)
    input("Press Enter to stop...\n")
```

`get()` and its `refresh()` alias conditionally request the current report. Once a report is cached, the client sends its report ID so the API can return no content when the cached report is already current. A missing or deleted report clears that cached value. Subscription updates use the same cache and callback processing as on-demand reports. Wildcard subscriptions are supported for the report-name segment, such as `USERNAME/GROUP/PRICE_*`; callbacks receive each changed report under its concrete topic.

Create an API key from the Runline account page and keep it outside source control, such as in the `RUNLINE_API_KEY` environment variable above. Use your account username as the first topic segment, as shown by `RUNLINE_USERNAME`. `U` exchanges the API key for a short-lived access token and automatically obtains a new access token after expiration. You can omit `api_key` only when using an isolated REST API deployment configured for anonymous access. Request/response support is not part of this slice.

### Demand before production

Both `UClient` (direct HubServer) and `U` (HTTP API) support `demand_exists`. It returns the `DemandStatus` enum; normally produce unless the result is explicitly `NO`:

```python
from runline_u import DemandStatus

if client.demand_exists(topic) != DemandStatus.NO:
    client.publish(topic=topic, single_page_content=compute_report())
```

Optional arguments are `inactivity_minutes` (default 10080, seven days), `refresh_interval_seconds` (default 60), and `ignored_apps` (application names excluded from demand). Both intervals must be finite and greater than zero. Concrete topics and the client's usual default entity/group resolution are supported; wildcard topics are rejected.

`YES` means a current exact subscription or consumption within the inactivity window. `NO` requires a previously published topic and an old enough last consumption time, or a full observation window when never consumed. New topics and insufficient history return `UNKNOWN`, allowing initial publication. An idle wildcard subscription alone does not count; consumption of its concrete topics does. A publication's consumed flag does not keep it in demand forever.

Reports refresh on call and are cached per topic and ignored-app set, with at most 1000 entries per client. Concurrent calls for the same key share refreshes. Up to four distinct keys refresh concurrently; when all refresh slots are busy, other uncached checks immediately return `UNKNOWN` and can be retried on the next call. Cached checks proceed independently. No background demand worker is started. Refreshes can block for network I/O with a five-second request timeout. Failed attempts are throttled by the refresh interval and return `UNKNOWN`. Missing/expired reports, unsupported servers, and reports more than five seconds ahead of the client's UTC clock return `UNKNOWN`. Keep client/server clocks synchronized. Changed credentials, reconnects, or closed connections invalidate cached decisions.

Invalid arguments raise `ValueError`; use explicit enum comparisons rather than truthiness. Cached demand is a snapshot: keep calling the method while production is paused so renewed demand can be detected at the next refresh.

### Automatic demand publishing

Both `UClient` and `U` can automatically avoid publishing reports with no recent demand:

```python
from runline_u import TopicDemandOptions

client.configure_demand_publishing()  # All ordinary topics on this instance
# Or select exact topics / report-name wildcard patterns:
client.configure_demand_publishing(
    topic_patterns=["RUNLINE/RISK/DESK_*"],
    options=TopicDemandOptions(
        report_frequency_minutes=30,
        stale_threshold_minutes=10080,
        report_current_minutes=30,
        ignored_apps=("ReportRecorder",),
    ),
)
```

Disabled by default. When enabled, selected publishes accept a copied snapshot
for asynchronous delivery and return `True`, including calls with `sync=True`.
`NO` retains only the newest pending snapshot per topic; `YES` or `UNKNOWN`
allows sending. A single background worker checks pending topics even when the
application is idle. `None` selects all topics; `[]` selects none. Disabling
with `configure_demand_publishing(False)` releases retained snapshots.

The policy follows .NET SimpleClient/ServerApp: a 30-minute refresh interval,
seven-day inactivity threshold, and 30-minute current window. The last successful
report remains usable through the first two failed refreshes; after three failures,
data beyond the current window becomes `UNKNOWN`. Options use minutes and accept
finite nonnegative intervals (the inactivity threshold must be positive); a zero
refresh interval disables demand checks and sends normally.

`client.get_topic_demand_decision(topic, known_topics=None)` returns `DemandStatus`
using this same configured policy before expensive processing. It shares batched
refreshes and topic coverage with the worker (up to 10000 known topics, in requests
of at most 1000). Refreshes use a five-second overall deadline, with at most four
concurrent refreshes per client. The existing `demand_exists` keeps its stricter
on-call freshness and failure behavior. This setting saves network/server work;
use an upfront demand check when you also want to save computation.

HTTP deadlines include DNS and connection setup. At most four system DNS lookups
run concurrently across clients; if all slots are busy, bounded requests fail
immediately. Python cannot cancel an in-progress system lookup, so expired
lookups finish in daemon resolver threads without opening sockets or sending
requests. Slots become available again when those lookups return.

Deletes bypass demand, clear older deferred snapshots, and precede newer snapshots
for their own topic. Direct-client deletes may be queued for ordering even with
`sync=True`. HTTP `U.delete` remains unsupported. Heartbeats and other admin
traffic, transient reports, records topics, and records marker reports bypass
the policy. Delta preparation and delivery caches only see reports released for
sending; failed deadline-bounded direct sends do not update the delivery cache.

Pending state is limited to 1000 topics per instance; additional topics publish
normally. Failed topics retain their latest snapshot with a five-second retry
delay, and attempts rotate fairly so rejected topics cannot starve other topics.
State is in memory and discarded on close or explicit credential changes;
automatic reconnects retain pending data while invalidating demand reports.
Socket clients sharing a connection also discard pending data when another client
explicitly changes that connection's credentials. Close stops the worker and
waits up to six seconds for its bounded in-flight operation. Configure each
instance whose publishes should be gated; bypassing instances keep publishing
normally on shared socket connections.

### Direct HubServer client

```python
from runline_u import UClient

client = UClient(host="eval.runline.com", port=40001)
client.subscribe(topic="ABC_CORP/MY_REPORT_GROUP/MY_REPORT_NAME")
client.publish(
    topic="ABC_CORP/OTHER_REPORT_GROUP/OTHER_REPORT_NAME",
    single_page_content=get_data_as_list_of_lists()
)
```

The direct host/port constructor remains supported for applications that use a
single HubServer. Applications that need HubServer hot failover can use endpoint
configuration:

```python
from runline_u import UClient, UClientEndpoint

client = UClient(
    primary_endpoint=UClientEndpoint("primary-hub.example.com", 40001, secure=True),
    backup_endpoint=UClientEndpoint("backup-hub.example.com", 40001, secure=True),
)
```

Backup endpoints are optional. A missing, unconfigured, or identical backup
HubServer endpoint is treated as no backup.

For password-based authentication, a backup AuthServer can be supplied. The
primary AuthServer is always tried first:

```python
token = client.get_authn_token(
    "https://primary-auth.example.com:40151/api/v1/basicauthntoken",
    password,
    backup_auth_url="https://backup-auth.example.com:40151/api/v1/basicauthntoken",
)
client.authenticate(token)
```

Applications can also authenticate with a saved token and configure renewal,
which avoids storing user credentials in the application:

```python
client.authenticate(
    saved_token,
    renew_auth_url="https://primary-auth.example.com:40151/api/v1/renewauthntoken",
    backup_renew_auth_url="https://backup-auth.example.com:40151/api/v1/renewauthntoken",
    token_renewal_interval_minutes=60,
)
```

### Records

`UClient` and the REST-backed `U` expose the same Records API. The client keeps
Records implementation topics internal while synchronizing local record state
from authoritative server reports and live events.

```python
from runline_u import U

with U("https://api.example.com", api_key=os.environ["RUNLINE_API_KEY"]) as u:
    topic = "USERNAME/GROUP/CUSTOMERS"

    u.open_records(topic)
    schema = u.get_records_schema(topic)

    customer_id = "2db98009-f7b4-474d-84c8-9160433417db"
    u.create_record(topic, {"Name": "Acme", "Status": "Active"}, record_id=customer_id)
    u.update_record(topic, customer_id, "Status", "Paused")

    customer = u.get_record(topic, customer_id)
    active_customers = u.get_records(topic, filter={"Status": "Active"})
```

Use `initialize_records(topic, create_if_missing=True)` or
`create_records_table(topic, schema=...)` when the table may need to be created.
Use `refresh_records(topic)` to explicitly reconcile local state with the server,
and `wait_for_records_sync(topic, timeout_seconds=...)` or
`get_records_sync_status(topic)` to inspect synchronization.

Create, update, delete, and schema changes return a command result. A successful
publish means the command was submitted; record data commands are not
server-confirmed until a matching authoritative Records event or snapshot
checkpoint is received.
Pass `wait=True` with a bounded `timeout_seconds` for create, update, or delete
when the caller needs confirmation before continuing. Schema updates can be
submitted from Python, but schema confirmation is reported through subsequent
refresh/synchronization rather than `wait=True`. Pending record data commands
are persisted under the configured `data_directory` and are available with
`get_pending_record_commands(topic)` after restart.

Retry a failed or unconfirmed record command with
`retry_record_command(topic, command_id, wait=True, timeout_seconds=10)`.
The retry preserves its original ID, payload, and topic. Retries are explicit;
an unconfirmed command may already have reached the server. Supply any required
`secret`, `pub_secret`, and `prior_pub_secret` again: credentials are not stored
with pending commands. Commands persisted by older clients without a payload
cannot be retried.

### Delta Publishing Settings

Delta publishing is disabled by default. Enable it for all direct `UClient`
connections, including existing clients, with:

```python
UClient.configure_delta_publishing(
    enabled=True,
    min_cells=3000,
    full_report_fraction=0.7,
    base_update_interval_seconds=86400.0,
)
```

The values above are the default settings. `min_cells` is the minimum report
size eligible for delta publishing. `full_report_fraction` triggers a new full
base when changed cells reach that fraction of the base's cell count.
`base_update_interval_seconds` defaults to 24 hours (86,400 seconds); use `-1`
to disable timed refreshes. Large changes can still require a new base.

Omitted options reset to their defaults on each call. Use
`UClient.configure_delta_publishing(enabled=False)` to turn it off globally.
The HTTP `U` client continues to publish full reports.

### Local Report Storage

Pass `data_directory` to `UClient` or `U` to retain reports between application
runs:

```python
client = UClient(host="eval.runline.com", port=40001, data_directory="./runline-data")
```

The directory is created if necessary. A directory that cannot be created or
written raises an exception without replacing the previously configured
directory. Omitting it (or passing an empty string) leaves the shared default
unchanged. All clients in the process use the latest valid directory; its
current path is available as `client.data_directory`.

Stored reports supply conditional request IDs and, for direct HubServer
connections, hashes, so unchanged reports need not be downloaded again.
Later storage errors are logged without stopping network operations. Files
contain unencrypted report data, so use a directory appropriate for that data
and keep it out of source control. Use separate directories for different
environments or accounts. This storage format is private to the Python client.

## UpTickXL backward compatibility

Existing UpTickXL Python applications can install the `runline-u` package and
continue using legacy imports:

```bash
pip install runline-u
```

```python
from uptickxl_client import UpTickXLClient
```

New applications should prefer the modern API:

```python
from runline_u import UClient
```

Both import styles use the same underlying Runline U implementation. The legacy
facade preserves the old top-level import path and public compatibility names,
while falsey client host values intentionally use the modern `RUNLINE-PROD1`
default.

## Complete Example

Complete example applications are included with the `runline-u` package. `uclient_socket_example.py` uses the direct socket `UClient` API, while `uclient_rest_example.py` uses the REST `U` API with an API key. They intentionally follow the same topic, callback, response, and periodic-publish flow so the transport difference is easy to compare.

Copy editable examples into your current directory:

```bash
runline-u-copy-examples
```

Or choose a destination:

```bash
runline-u-copy-examples ./my-runline-u-examples
```

For the direct socket API, configure `RUNLINE_USERNAME`, `RUNLINE_U_HOST`, `RUNLINE_U_PORT`, `RUNLINE_U_SECURE`, and authentication variables as needed, then run:

```bash
python runline-u-examples/uclient_socket_example.py
```

For the REST API, create an API key from the Runline.io account page, set `RUNLINE_USERNAME`, `RUNLINE_API_KEY`, and optionally `RUNLINE_API_BASE_URL`, then run:

```bash
python runline-u-examples/uclient_rest_example.py
```

Open the copied `Client_of_U_Server_Example.xlsx` while the example server is running to use the workbook as a front end for publishing requests and viewing responses.

## Release Notes

Release notes are maintained in `CHANGELOG.md`.
