Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

labapi-deploy-test

A minimal Streamlit app to test whether Posit Connect can restore a Python environment from manifest.json, install labapi from PyPI, and serve an interactive app.

The app provides a Log in to LabArchives button, browses accessible notebooks and pages, and previews streams from TDT ZIP attachments. The Deployment diagnostics expander shows package versions and an interaction counter, even before API credentials are configured. LabArchives access is read-only.

For the working authentication flow, deployment details, troubleshooting, and lessons from testing on Connect, see the LabArchives authentication guide.

Run locally

Use Python 3.12, matching the Posit Connect server:

python3.12 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements.txt
export ACCESS_KEYID='your_labarchives_api_key_id'
export ACCESS_PWD='your_labarchives_api_password'
export LABARCHIVES_CALLBACK_URL='http://localhost:8501/'
python -m streamlit run app.py

API_URL defaults to https://api.labarchives.com. Set it to the API URL supplied by LabArchives if your institution uses a different region.

Configure LabArchives login on Connect

Set these variables in the deployed content's Settings > Vars panel, then restart the app:

Variable Value
ACCESS_KEYID Your institution's LabArchives API access key ID.
ACCESS_PWD The corresponding API access password.
API_URL Optional regional API URL; defaults to https://api.labarchives.com.
LABARCHIVES_CALLBACK_URL The app's public HTTPS URL, such as https://connect.example.org/content/CONTENT_GUID/.

Use the direct app URL, including its path and trailing slash, rather than the Connect dashboard URL. Do not include query parameters or a URL fragment. Open the app in its own browser tab for login. API access credentials are issued by LabArchives; they are separate from your Connect API key and your personal login. Keep their values in environment variables, outside the repository and manifest.

Click Log in to LabArchives. The button first opens the configured app URL in a standalone tab, then redirects that tab to LabArchives. This also works when you start in Connect's dashboard iframe or through an alternate app URL. Authenticate on the LabArchives page, including institutional SSO if applicable. LabArchives returns to the app in the new tab; the app exchanges the callback's email and auth_code using Client.login() and displays your notebooks. Complete login within five minutes; use the login button again to start a fresh attempt if needed.

The app creates a random browser token in localStorage to validate the returning login request. It does not need access to Connect or Streamlit cookies, which may be unavailable behind a proxy. A small built-in Streamlit component reads this token in both the original and returning tabs. Browser storage contains only this random token, never login credentials or notebook information. Authentication starts and ends at LABARCHIVES_CALLBACK_URL so both steps use the same browser storage context.

If LabArchives returns an error instead of login credentials, the app explains the rejection separately from browser verification failures. For an invalid access key ID, check ACCESS_KEYID and API_URL. For a rejected signature, check ACCESS_PWD and the region. These must be LabArchives API credentials, separate from your Posit Connect publisher key. A timestamp rejection may require checking the Connect server clock.

The app also handles callbacks that append ?auth_code=... to a URL already containing ?state=.... It repairs the delimiter before decoding the code and still verifies the signed state. Missing, empty, and repeated callback parameters are reported separately.

Callback credentials are removed from the address bar before the API call. Your user ID, email, and notebook list remain in your Streamlit session. Browsing metadata, temporary files, and plot samples use a session-scoped resource; they are not shared between users or tabs. Later API requests use the user ID and the server's signing credentials, without retaining the callback authorization code. Log out clears that session's data. Reloading the page requires logging in again. To refresh notebook access, log out and log back in. Logging out of this app does not end your LabArchives or institutional SSO session.

Preview a TDT ZIP attachment

  1. Choose a Notebook, then its folders and page. Notebook and node IDs keep duplicate names distinguishable. Browsing fetches metadata only.
  2. Choose a ZIP attachment. Attachments without a reported filename are also selectable; the downloaded bytes must still be a valid ZIP. Use Refresh browser to fetch updated folders and attachment metadata.
  3. Click Download and prepare. The app streams the API response directly to temporary server storage, following LabArchives/S3 redirects automatically. No AWS credentials or browser upload are needed, including for attachments larger than 200 MB.
  4. If the archive contains several TDT blocks, choose one. Outer folders are supported. Include each complete standard TDT block in its own folder, with its .tsq, .tev and/or referenced .sev data, and accompanying metadata such as .Tbk and StoresListing.txt. SEV-only archives without a .tsq are not currently supported.
  5. Inspect the store table. The app merges the detailed and flat sections of StoresListing.txt, then uses TDT headers for recorded types, numeric channels, and exact sampling rates. Listed stores absent from the recording are marked not recorded. A missing listing falls back to header metadata.
  6. Choose one Signal store and its numeric channel. Reference store defaults to None. The reference may use a different store, channel, or sampling rate; identical signal/reference selections are disallowed.
  7. Click Extract and plot. Signal and optional reference appear as raw Plotly traces in panels sharing a time axis. There is no reference correction, filtering, normalization, or ΔF/F calculation.

Each selected stream is read for the full recording with tdt.read_block(), filtered to that store and numeric channel. For N samples and a point limit L, the app uses stride = max(1, ceil(N / L)) and values[::stride].copy(). This produces at most 20,000 points per trace by default, sometimes fewer. Timestamps use the retained sample indices and each stream's exact sampling rate and start offset. Stride sampling can miss short transients and is intended here for preview and deployment stability testing.

Increase Maximum plotted points per trace, then click Extract and plot again to display more data, up to full resolution. This rereads local TDT files without downloading or unzipping again. Full arrays are released after copying the plot samples; ordinary UI reruns reuse the existing preview. The point limit bounds the plot payload, not peak memory during the full TDT read.

File and extraction diagnostics reports download/extraction sizes, whether the response redirected to S3, stage timings, sample counts, stride, array sizes, and process lifetime peak resident memory. That peak includes other sessions in the same worker and does not decrease after clearing data.

Chart revision keys are random identifiers and contain no absolute server paths. The TDT reader uses private print/warning destinations so its recording paths and note text do not enter shared server logs. Other sessions' output is unaffected. Warning counts remain visible in the app and diagnostics; warning text is discarded. The parser's checked-in test fixture uses synthetic experiment, subject, user, and acquisition date/time metadata.

Only one archive is retained per session. Clear loaded data, selecting a different source, replacing a download, Refresh browser, and Log out remove the prepared files and samples. Normal session disconnection also releases the resource. An interrupted preparation cleans partial files. A forced worker termination cannot run cleanup; server temporary-directory maintenance handles any abandoned labapi-tdt-* directories. A worker restart or loss of temporary files requires another download. The standard TMPDIR setting chooses the temporary filesystem; allow space for both the ZIP and uncompressed contents during preparation. The ZIP is removed after successful extraction.

Deploy using the manifest

The repository includes a generated manifest.json with app mode python-streamlit, entry point app.py, and requirements.txt for dependencies. The Connect server needs a compatible Python 3.12 runtime and access to PyPI (or a package mirror containing these dependencies), plus outbound access to the LabArchives API and its redirected S3 download hosts. The worker needs writable temporary disk and enough memory to read each selected stream in full. For a different Python runtime, update .python-version, install the requirements in that environment, and regenerate the manifest there before deploying.

Import from Git

  1. Commit and push the application modules (app.py, labarchives_auth.py, labarchives_viewer.py, tdt_preview.py, tdt_reader.py), requirements.txt, .python-version, and the regenerated manifest.json to your Git remote.
  2. In Posit Connect, choose Publish > Import from Git.
  3. Select this repository, the branch containing these files, and the repository root as the content directory.
  4. Deploy, configure the LabArchives variables above, and open the app directly.
  5. Log in and confirm your accessible notebooks are listed. You can also check Python/package versions and the interaction counter in Deployment diagnostics.

Deploy the existing manifest from the CLI

In the activated local environment, install the deployment tool and configure your server using your Connect URL and publisher API key:

python -m pip install rsconnect-python==1.32.0
rsconnect add --name test --server https://connect.example.org --api-key YOUR_CONNECT_API_KEY
rsconnect deploy manifest manifest.json --name test --title "labapi deployment test"

Replace the example URL and key with your own values. rsconnect-python is local deployment tooling and is intentionally separate from the app's requirements.

Regenerate the manifest

After changing the app or dependencies, run this from the repository root in the activated environment with rsconnect-python installed:

rsconnect write-manifest streamlit . \
  --entrypoint app.py \
  --overwrite \
  --exclude '.*' \
  --exclude '.*/**' \
  --exclude '__pycache__/**' \
  --exclude 'tests/**'

Hidden local files (including environments, caches, and secrets) and tests are excluded from the bundle. The CLI still reads .python-version to set the manifest's Python runtime requirement.

Keep the explicit requirements.txt; do not use --force-generate, which would replace it with packages from the local environment. Commit and push the updated manifest with the changed files before requesting a Git-backed redeployment.

Tests

With the app requirements installed, run:

python -m unittest discover -s tests -v

The tests cover authentication, lazy browsing, session isolation, streamed downloads (including a generated 201 MiB payload and a real client following a simulated S3 redirect), archive validation/cleanup, channel metadata, sampling, and Streamlit plotting interactions. They do not require live credentials.

To also compare a full-recording preview with a direct TDT read of your own local block, set TDT_TEST_BLOCK to its folder before running the tests. This opt-in check reads the first recorded stream in full twice.

After redeploying on Connect, verify live login and the real large attachment: download and prepare it, plot signal only and signal/reference, progressively increase the point limit, then repeat extraction, clearing, and logout. Check diagnostics and Connect logs for memory, timings, disk usage, and responsiveness. Automated tests do not establish live S3 access or the deployed worker's limits.

See Posit's documentation on Streamlit manifests and Git-backed deployment, and the labapi authentication guide.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages