From 95ec55471f00402b448ceb0e04b816a4caf4b199 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20J=C3=A4ckle?= Date: Thu, 12 Nov 2026 17:01:29 +0100 Subject: [PATCH] Initial contribution of dittoctl, a command line tool for Eclipse Ditto dittoctl is a vendor-neutral command line tool for operators and developers working with any Eclipse Ditto installation (HTTP API 2, Ditto 3.9). It is written in Python 3.11+ and is meant to be published to PyPI as "dittoctl". It covers: - contexts (named Ditto endpoints) with basic, token, pre-authenticated and OIDC authentication (authorization code + PKCE, device code, client credentials), with credentials kept in the OS keyring - reading, searching, counting, exporting (CSV, NDJSON) and watching things, their history and WoT Thing Descriptions - bulk modifications with Ditto's conditional headers, dry runs, safety limits, concurrency, journals to resume and failure files to retry - messages, policies (incl. subject migration), connections, DevOps commands and the WoT Thing Directory - an output mode for AI agents (compact JSON, structured errors, bounded output) All files are licensed under EPL-2.0. The project was largely created with the assistance of an AI; following the Eclipse Foundation's generative AI guidelines, source files that were largely AI-generated carry an AI disclosure in their header, and their AI-generated portions are made available under CC0-1.0. NOTICE.md declares this for all content, including the Markdown files, which carry no header. Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) --- .github/workflows/ci.yml | 52 + .github/workflows/release.yml | 59 + .gitignore | 13 + CODE_OF_CONDUCT.md | 46 + CONTRIBUTING.md | 150 ++ LICENSE | 89 ++ NOTICE.md | 54 + README.md | 314 ++++- SECURITY.md | 40 + docs/reference.md | 1926 ++++++++++++++++++++++++++ legal/CC0-1.0.txt | 121 ++ legal/NOTICE-THIRD-PARTY.md | 140 ++ pyproject.toml | 100 ++ scripts/gen_reference.py | 75 + src/dittoctl/__init__.py | 19 + src/dittoctl/__main__.py | 21 + src/dittoctl/auth/__init__.py | 49 + src/dittoctl/auth/base.py | 165 +++ src/dittoctl/auth/oidc.py | 404 ++++++ src/dittoctl/auth/store.py | 118 ++ src/dittoctl/cli/__init__.py | 17 + src/dittoctl/cli/api_cmd.py | 121 ++ src/dittoctl/cli/auth_cmd.py | 119 ++ src/dittoctl/cli/bulk_options.py | 309 +++++ src/dittoctl/cli/config_cmd.py | 203 +++ src/dittoctl/cli/connections_cmd.py | 302 ++++ src/dittoctl/cli/devops_cmd.py | 261 ++++ src/dittoctl/cli/main.py | 175 +++ src/dittoctl/cli/messages_cmd.py | 178 +++ src/dittoctl/cli/options.py | 181 +++ src/dittoctl/cli/output.py | 156 +++ src/dittoctl/cli/policies_cmd.py | 452 ++++++ src/dittoctl/cli/rql_cmd.py | 57 + src/dittoctl/cli/state.py | 134 ++ src/dittoctl/cli/things_cmd.py | 645 +++++++++ src/dittoctl/cli/things_write_cmd.py | 605 ++++++++ src/dittoctl/cli/wot_cmd.py | 37 + src/dittoctl/config.py | 248 ++++ src/dittoctl/core/__init__.py | 22 + src/dittoctl/core/bulk.py | 272 ++++ src/dittoctl/core/client.py | 305 ++++ src/dittoctl/core/conditions.py | 100 ++ src/dittoctl/core/connections.py | 72 + src/dittoctl/core/curl.py | 52 + src/dittoctl/core/devops.py | 186 +++ src/dittoctl/core/fields.py | 103 ++ src/dittoctl/core/jsonops.py | 120 ++ src/dittoctl/core/policies.py | 161 +++ src/dittoctl/core/rql.py | 253 ++++ src/dittoctl/core/search.py | 220 +++ src/dittoctl/core/selectors.py | 129 ++ src/dittoctl/core/sse.py | 55 + src/dittoctl/core/streams.py | 127 ++ src/dittoctl/core/things.py | 168 +++ src/dittoctl/core/wot.py | 174 +++ src/dittoctl/core/writes.py | 253 ++++ src/dittoctl/errors.py | 162 +++ src/dittoctl/formats/__init__.py | 113 ++ src/dittoctl/formats/flatten.py | 88 ++ src/dittoctl/formats/tabular.py | 142 ++ tests/conftest.py | 55 + tests/test_agent.py | 374 +++++ tests/test_bulk.py | 149 ++ tests/test_cli.py | 190 +++ tests/test_cli_things.py | 195 +++ tests/test_cli_write.py | 296 ++++ tests/test_client.py | 241 ++++ tests/test_conditions.py | 67 + tests/test_config.py | 130 ++ tests/test_formats.py | 205 +++ tests/test_headers.py | 60 + tests/test_jsonops.py | 82 ++ tests/test_m4.py | 231 +++ tests/test_oidc.py | 283 ++++ tests/test_policies_connections.py | 308 ++++ tests/test_reference.py | 64 + tests/test_rql.py | 115 ++ tests/test_search_things.py | 334 +++++ tests/test_selectors_writes.py | 200 +++ tests/test_wot.py | 212 +++ 80 files changed, 15222 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/ci.yml create mode 100644 .github/workflows/release.yml create mode 100644 .gitignore create mode 100644 CODE_OF_CONDUCT.md create mode 100644 CONTRIBUTING.md create mode 100644 LICENSE create mode 100644 NOTICE.md create mode 100644 SECURITY.md create mode 100644 docs/reference.md create mode 100644 legal/CC0-1.0.txt create mode 100644 legal/NOTICE-THIRD-PARTY.md create mode 100644 pyproject.toml create mode 100644 scripts/gen_reference.py create mode 100644 src/dittoctl/__init__.py create mode 100644 src/dittoctl/__main__.py create mode 100644 src/dittoctl/auth/__init__.py create mode 100644 src/dittoctl/auth/base.py create mode 100644 src/dittoctl/auth/oidc.py create mode 100644 src/dittoctl/auth/store.py create mode 100644 src/dittoctl/cli/__init__.py create mode 100644 src/dittoctl/cli/api_cmd.py create mode 100644 src/dittoctl/cli/auth_cmd.py create mode 100644 src/dittoctl/cli/bulk_options.py create mode 100644 src/dittoctl/cli/config_cmd.py create mode 100644 src/dittoctl/cli/connections_cmd.py create mode 100644 src/dittoctl/cli/devops_cmd.py create mode 100644 src/dittoctl/cli/main.py create mode 100644 src/dittoctl/cli/messages_cmd.py create mode 100644 src/dittoctl/cli/options.py create mode 100644 src/dittoctl/cli/output.py create mode 100644 src/dittoctl/cli/policies_cmd.py create mode 100644 src/dittoctl/cli/rql_cmd.py create mode 100644 src/dittoctl/cli/state.py create mode 100644 src/dittoctl/cli/things_cmd.py create mode 100644 src/dittoctl/cli/things_write_cmd.py create mode 100644 src/dittoctl/cli/wot_cmd.py create mode 100644 src/dittoctl/config.py create mode 100644 src/dittoctl/core/__init__.py create mode 100644 src/dittoctl/core/bulk.py create mode 100644 src/dittoctl/core/client.py create mode 100644 src/dittoctl/core/conditions.py create mode 100644 src/dittoctl/core/connections.py create mode 100644 src/dittoctl/core/curl.py create mode 100644 src/dittoctl/core/devops.py create mode 100644 src/dittoctl/core/fields.py create mode 100644 src/dittoctl/core/jsonops.py create mode 100644 src/dittoctl/core/policies.py create mode 100644 src/dittoctl/core/rql.py create mode 100644 src/dittoctl/core/search.py create mode 100644 src/dittoctl/core/selectors.py create mode 100644 src/dittoctl/core/sse.py create mode 100644 src/dittoctl/core/streams.py create mode 100644 src/dittoctl/core/things.py create mode 100644 src/dittoctl/core/wot.py create mode 100644 src/dittoctl/core/writes.py create mode 100644 src/dittoctl/errors.py create mode 100644 src/dittoctl/formats/__init__.py create mode 100644 src/dittoctl/formats/flatten.py create mode 100644 src/dittoctl/formats/tabular.py create mode 100644 tests/conftest.py create mode 100644 tests/test_agent.py create mode 100644 tests/test_bulk.py create mode 100644 tests/test_cli.py create mode 100644 tests/test_cli_things.py create mode 100644 tests/test_cli_write.py create mode 100644 tests/test_client.py create mode 100644 tests/test_conditions.py create mode 100644 tests/test_config.py create mode 100644 tests/test_formats.py create mode 100644 tests/test_headers.py create mode 100644 tests/test_jsonops.py create mode 100644 tests/test_m4.py create mode 100644 tests/test_oidc.py create mode 100644 tests/test_policies_connections.py create mode 100644 tests/test_reference.py create mode 100644 tests/test_rql.py create mode 100644 tests/test_search_things.py create mode 100644 tests/test_selectors_writes.py create mode 100644 tests/test_wot.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..ebd9379 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,52 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +name: CI + +on: + push: + branches: [main] + pull_request: + +permissions: + contents: read + +jobs: + lint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.11" + - run: python -m pip install --upgrade pip && pip install -e . --group dev + - run: ruff check src tests + - run: ruff format --check src tests + + test: + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + python: ["3.11", "3.12", "3.13", "3.14"] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python }} + - run: python -m pip install --upgrade pip && pip install -e . --group dev + - run: pytest diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..ef7ffe5 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,59 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +# Publishes to PyPI when a version tag (v0.9.0, ...) is pushed, via PyPI trusted publishing: +# the PyPI project "dittoctl" must trust this repository and workflow (environment "pypi"). +name: Release + +on: + push: + tags: ["v*"] + +permissions: + contents: read + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.11" + - name: Check that the tag matches the package version + run: | + version=$(python -c 'import re,pathlib; print(re.search(r"__version__ = \"(.+)\"", pathlib.Path("src/dittoctl/__init__.py").read_text()).group(1))') + test "v$version" = "$GITHUB_REF_NAME" || { echo "tag $GITHUB_REF_NAME != version $version"; exit 1; } + - run: python -m pip install --upgrade pip build && pip install -e . --group dev + - run: pytest + - run: python -m build + - uses: actions/upload-artifact@v4 + with: + name: dist + path: dist/ + + publish: + needs: build + runs-on: ubuntu-latest + environment: pypi + permissions: + id-token: write + steps: + - uses: actions/download-artifact@v4 + with: + name: dist + path: dist/ + - uses: pypa/gh-action-pypi-publish@release/v1 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6089bd2 --- /dev/null +++ b/.gitignore @@ -0,0 +1,13 @@ +__pycache__/ +*.py[cod] +.venv/ +build/ +dist/ +*.egg-info/ +.pytest_cache/ +.ruff_cache/ +.coverage +htmlcov/ +.idea/ +.vscode/ +.DS_Store diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..b7aae33 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,46 @@ +# Community Code of Conduct + +**Version 1.2 +August 19, 2020** + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as community members, contributors, committers, and project leaders pledge to make participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a professional setting + +## Our Responsibilities + +With the support of the Eclipse Foundation staff (the “Staff”), project committers and leaders are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. + +Project committers and leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies within all project spaces, and it also applies when an individual is representing the Eclipse Foundation project or its community in public spaces. Examples of representing a project or community include posting via an official social media account, or acting as a project representative at an online or offline event. Representation of a project may be further defined and clarified by project committers, leaders, or the EMO. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the Staff at codeofconduct@eclipse.org. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The Staff is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. + +Project committers or leaders who do not follow the Code of Conduct in good faith may face temporary or permanent repercussions as determined by the Staff. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org) , version 1.4, available at [https://www.contributor-covenant.org/version/1/4/code-of-conduct.html](https://www.contributor-covenant.org/version/1/4/code-of-conduct/) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..7d2a717 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,150 @@ +# How to contribute to dittoctl + +Thanks for considering a contribution to dittoctl, the command line tool for +[Eclipse Ditto](https://eclipse.dev/ditto/). This page explains the legal requirements, the rules that keep the +code base clean, and how to get a change merged. + +## Legal requirements + +dittoctl is part of the Eclipse Ditto project and follows the +[Eclipse Foundation Development Process](https://www.eclipse.org/projects/dev_process/). Before we can accept +your contribution: + +* Create an [Eclipse Foundation account](https://accounts.eclipse.org/user/register) and sign the + [Eclipse Contributor Agreement (ECA)](https://www.eclipse.org/legal/eca/). +* Add your GitHub username to your Eclipse Foundation account. +* Commit with the email address of your Eclipse Foundation account. The ECA check on each pull request verifies + that every commit author has signed the ECA. + +By contributing, you agree that your contribution is licensed under the +[Eclipse Public License 2.0](LICENSE). + +## Clean-room rules + +dittoctl is implemented only from public sources. This keeps the provenance of every line clear: + +* Use only public sources: the [Ditto documentation](https://eclipse.dev/ditto/), Ditto's OpenAPI specification + (`documentation/src/main/resources/openapi/ditto-api-2.yml` in + [eclipse-ditto/ditto](https://github.com/eclipse-ditto/ditto)), and the relevant RFCs (e.g. 7396 merge patch, + 7636 PKCE, 8628 device authorization grant). +* Don't copy code, tests, fixtures, templates or documentation from other tools, including internal tools of your + employer, unless their license allows it and the origin is stated in the pull request. Ideas and features may be + taken over, code may not. +* Use synthetic test data only, in made-up namespaces such as `org.example`. Never commit real thing ids, policy + ids, customer namespaces, hostnames, tokens or other data from a real Ditto installation, not even in comments, + examples or commit messages. + +## Before you start + +* **Create an issue first** in [eclipse-ditto/dittoctl](https://github.com/eclipse-ditto/dittoctl/issues) for new + features and non-trivial bug fixes, so that the approach can be discussed before much work goes into it. Small + bug fixes and maintenance changes (documentation, build, tooling) don't need an issue; explain the change in the + pull request instead. +* **Keep pull requests small**, well below 1,000 changed lines. Larger contributions trigger an IP review by the + Eclipse Foundation. Split bigger changes into several pull requests that build on each other. +* **Open pull requests early**, as drafts while they aren't ready for review. + +## Development setup + +dittoctl needs Python 3.11 or newer. + +```shell +python3 -m venv .venv +.venv/bin/pip install --upgrade pip # pip 25.1+ for dependency groups +.venv/bin/pip install -e . --group dev +``` + +Before you push, run: + +```shell +.venv/bin/pytest +.venv/bin/ruff check src tests && .venv/bin/ruff format --check src tests +.venv/bin/python scripts/gen_reference.py # after changing commands or help texts (a test checks it) +``` + +CI runs the same checks; the tests run on Linux, macOS and Windows with Python 3.11 to 3.14. + +## Code guidelines + +* Formatting and linting: [ruff](https://docs.astral.sh/ruff/) with a line length of 120, as configured in + `pyproject.toml`. +* `dittoctl.core` is a library: it never prints, it returns data or raises exceptions. The command line layer in + `dittoctl.cli` parses options, calls `core` and renders the result. +* Every command and every option has a help text; `docs/reference.md` is generated from them. Write help texts so + that people and LLM agents can use a command correctly without reading the code. +* Writes must stay safe: keep `--dry-run`, the `--max-affected` limit, the confirmation of protected contexts and + Ditto's conditional headers working for every command that changes data. +* Add unit tests for every change (pytest, with [respx](https://lundberg.github.io/respx/) to mock Ditto's HTTP + API). +* Use descriptive commit messages that explain why a change was made. + +## License header + +Every new source file (Python, YAML, TOML) starts with this header, with the current year: + +```python +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# SPDX-License-Identifier: EPL-2.0 +``` + +Files that were largely generated by an AI carry an AI disclosure instead (see below): + +```python +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +``` + +Markdown files carry no header; [NOTICE.md](NOTICE.md) covers them. A test checks the headers of all source +files. + +## Contributions created with generative AI + +Content created with the assistance of an AI is welcome, under the Eclipse Foundation's +[Generative AI Usage Guidelines](https://www.eclipse.org/projects/handbook/#genai): + +* You are responsible for the content: review and test it like your own, and only contribute what you understand + and are willing to support. +* Disclose the use of AI: if you would give a human credit for the contribution, give the AI credit. Use the + header with the AI disclosure above for source files that are largely AI-generated, naming the assistant you + used. +* Name the AI assistant in an `Assisted-by:` trailer of the commit message, e.g. + `Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5)`. +* Make sure your use of the AI platform is consistent with its terms of use and with your employer's policy, and + don't put confidential information or personal data into its prompts. + +## Submitting a pull request + +1. Fork the repository and create a branch for your change. +2. Make the change, with tests and updated documentation (README, generated reference). +3. Push the branch to your fork and open a pull request against `main`. +4. Don't use that branch for other work while the pull request is open. + +The project-wide rules of Eclipse Ditto apply as well, for example for approving and merging pull requests: see +[Ditto's CONTRIBUTING.md](https://github.com/eclipse-ditto/ditto/blob/master/CONTRIBUTING.md). + +## Code of conduct and security + +Please follow the [Code of Conduct](CODE_OF_CONDUCT.md). Report vulnerabilities as described in +[SECURITY.md](SECURITY.md), never in public issues. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..b5575fc --- /dev/null +++ b/LICENSE @@ -0,0 +1,89 @@ +Eclipse Public License - v 2.0 + +THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE (“AGREEMENT”). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. + +1. DEFINITIONS + +“Contribution” means: + +a) in the case of the initial Contributor, the initial content Distributed under this Agreement, and +b) in the case of each subsequent Contributor: +i) changes to the Program, and +ii) additions to the Program; +where such changes and/or additions to the Program originate from and are Distributed by that particular Contributor. A Contribution “originates” from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor's behalf. Contributions do not include changes or additions to the Program that are not Modified Works. +“Contributor” means any person or entity that Distributes the Program. + +“Licensed Patents” mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program. + +“Program” means the Contributions Distributed in accordance with this Agreement. + +“Recipient” means anyone who receives the Program under this Agreement or any Secondary License (as applicable), including Contributors. + +“Derivative Works” shall mean any work, whether in Source Code or other form, that is based on (or derived from) the Program and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. + +“Modified Works” shall mean any work in Source Code or other form that results from an addition to, deletion from, or modification of the contents of the Program, including, for purposes of clarity any new file in Source Code form that contains any contents of the Program. Modified Works shall not include works that contain only declarations, interfaces, types, classes, structures, or files of the Program solely in each case in order to link to, bind by name, or subclass the Program or Modified Works thereof. + +“Distribute” means the acts of a) distributing or b) making available in any manner that enables the transfer of a copy. + +“Source Code” means the form of a Program preferred for making modifications, including but not limited to software source code, documentation source, and configuration files. + +“Secondary License” means either the GNU General Public License, Version 2.0, or any later versions of that license, including any exceptions or additional permissions as identified by the initial Contributor. + +2. GRANT OF RIGHTS + +a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, Distribute and sublicense the Contribution of such Contributor, if any, and such Derivative Works. +b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in Source Code or other form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder. +c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to Distribute the Program, it is Recipient's responsibility to acquire that license before distributing the Program. +d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement. +e) Notwithstanding the terms of any Secondary License, no Contributor makes additional grants to any Recipient (other than those set forth in this Agreement) as a result of such Recipient's receipt of the Program under the terms of a Secondary License (if permitted under the terms of Section 3). +3. REQUIREMENTS + +3.1 If a Contributor Distributes the Program in any form, then: + +a) the Program must also be made available as Source Code, in accordance with section 3.2, and the Contributor must accompany the Program with a statement that the Source Code for the Program is available under this Agreement, and informs Recipients how to obtain it in a reasonable manner on or through a medium customarily used for software exchange; and +b) the Contributor may Distribute the Program under a license different than this Agreement, provided that such license: +i) effectively disclaims on behalf of all other Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose; +ii) effectively excludes on behalf of all other Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits; +iii) does not attempt to limit or alter the recipients' rights in the Source Code under section 3.2; and +iv) requires any subsequent distribution of the Program by any party to be under a license that satisfies the requirements of this section 3. +3.2 When the Program is Distributed as Source Code: + +a) it must be made available under this Agreement, or if the Program (i) is combined with other material in a separate file or files made available under a Secondary License, and (ii) the initial Contributor attached to the Source Code the notice described in Exhibit A of this Agreement, then the Program may be made available under the terms of such Secondary Licenses, and +b) a copy of this Agreement must be included with each copy of the Program. +3.3 Contributors may not remove or alter any copyright, patent, trademark, attribution notices, disclaimers of warranty, or limitations of liability (‘notices’) contained within the Program from any copy of the Program which they Distribute, provided that Contributors may add their own appropriate notices. + +4. COMMERCIAL DISTRIBUTION + +Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor (“Commercial Contributor”) hereby agrees to defend and indemnify every other Contributor (“Indemnified Contributor”) against any losses, damages and costs (collectively “Losses”) arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense. + +For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages. + +5. NO WARRANTY + +EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE PROGRAM IS PROVIDED ON AN “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement, including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations. + +6. DISCLAIMER OF LIABILITY + +EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT PERMITTED BY APPLICABLE LAW, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +7. GENERAL + +If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable. + +If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient's patent(s), then such Recipient's rights granted under Section 2(b) shall terminate as of the date such litigation is filed. + +All Recipient's rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient's rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient's obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive. + +Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be Distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to Distribute the Program (including its Contributions) under the new version. + +Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved. Nothing in this Agreement is intended to be enforceable by any entity that is not a Contributor or Recipient. No third-party beneficiary rights are created under this Agreement. + +Exhibit A – Form of Secondary Licenses Notice + +“This Source Code may also be made available under the following Secondary Licenses when the conditions for such availability set forth in the Eclipse Public License, v. 2.0 are satisfied: {name license(s), version(s), and exceptions or additional permissions here}.” + +Simply including a copy of this Agreement, including this Exhibit A is not sufficient to license the Source Code under Secondary Licenses. + +If it is not possible or desirable to put the notice in a particular file, then You may include the notice in a location (such as a LICENSE file in a relevant directory) where a recipient would be likely to look for such a notice. + +You may add additional accurate notices of copyright ownership. diff --git a/NOTICE.md b/NOTICE.md new file mode 100644 index 0000000..01d8b33 --- /dev/null +++ b/NOTICE.md @@ -0,0 +1,54 @@ +This content is produced and maintained by the Eclipse Ditto project. + +* Project home: https://www.eclipse.dev/ditto/ + +# Trademarks + +* Eclipse Ditto and the Eclipse Ditto project logo are trademarks of the Eclipse Foundation. +* Eclipse and the Eclipse logo are registered trademarks of The Eclipse Foundation. +* Python is a registered trademark of the Python Software Foundation. + +# Copyright + +All content is the property of the respective authors or their employers. +For more information regarding authorship of content, please consult the +listed source code repository logs. + +# Declared Project Licenses + +This program and the accompanying materials are made available under the terms +of the Eclipse Public License 2.0 which is available at https://www.eclipse.org/legal/epl-2.0/. + +The AI-generated portions of the content are made available under CC0-1.0 (see "Use of Generative AI" below +and [legal/CC0-1.0.txt](legal/CC0-1.0.txt)). + +SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 + +# Source Code + +* https://github.com/eclipse-ditto/dittoctl + +# Use of Generative AI + +This content was largely generated with the assistance of an AI: Anthropic Claude Opus 5.5 (claude-opus-5-5). +The design decisions, the review of the generated content and its testing were done by humans; the human +contributors have reviewed and verified the content. + +Following the Eclipse Foundation's guidelines for content generated by an AI +(https://www.eclipse.org/projects/handbook/#genai-disclosure), the AI-generated portions are made available under +CC0-1.0 ("No Rights Reserved", [legal/CC0-1.0.txt](legal/CC0-1.0.txt)) and are not subject to the project's +licence. Source files that were largely AI-generated say so in their header (Markdown files carry no header and +are covered by this notice), and commits name the AI assistant in an `Assisted-by:` trailer. + +# Third-party Content + +This software includes third party content listed in [NOTICE-THIRD-PARTY.md](legal/NOTICE-THIRD-PARTY.md) + +# Cryptography + +Content may contain encryption software. The country in which you are currently +may have restrictions on the import, possession, and use, and/or re-export to +another country, of encryption software. BEFORE using any encryption software, +please check the country's laws, regulations and policies concerning the import, +possession, or use, and re-export of encryption software, to see if this is +permitted. diff --git a/README.md b/README.md index bae9ad7..35df6f3 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,314 @@ # dittoctl -Eclipse Ditto™: Digital Twin framework - Command line tool (dittoctl) + +A command line tool for [Eclipse Ditto](https://eclipse.dev/ditto/): inspect things, policies and connections; search with RQL and +export the results; run bulk modifications and message invocations safely; watch change streams; run DevOps commands. + +> Status: early development (milestones M0–M4 done). See [PLAN.md](PLAN.md) for the roadmap and +> [docs/reference.md](docs/reference.md) for all commands and options. + +## Install + +Requires Python 3.11+. + +```shell +pipx install dittoctl # or: uv tool install dittoctl +``` + +From a checkout: + +```shell +python3 -m venv .venv && .venv/bin/pip install -e . --group dev +``` + +## Quick start + +Create a context for a Ditto instance and log in: + +```shell +# Ditto's docker-compose setup with nginx basic auth +dittoctl config add-context local --url http://localhost:8080 --auth basic --username ditto +dittoctl auth login # prompts for the password, stores it in the OS keyring + +# an OIDC provider, logging in with the browser (authorization code + PKCE) +dittoctl config add-context prod --url https://ditto.example.com --protected \ + --auth oidc --issuer https://idp.example.com/realms/iot --client-id dittoctl --scope openid --scope offline_access +dittoctl --context prod auth login +``` + +Then: + +```shell +dittoctl whoami # subjects Ditto derives from your credentials +dittoctl api GET /api/2/things/org.example:sensor-1 +dittoctl api PATCH /api/2/things/org.example:sensor-1/attributes -d '{"location":"lab"}' --if-equal skip +dittoctl -v api GET /api/2/whoami # also prints the request as a curl command (token redacted) +``` + +Without a context, `--url` plus `DITTOCTL_TOKEN` (or `DITTOCTL_USERNAME`/`DITTOCTL_PASSWORD`) is enough, which suits CI jobs. + +## Reading things + +```shell +dittoctl things get org.example:sensor-1 # whole thing as JSON +dittoctl things get org.example:sensor-1 --path attributes/location --at-revision 42 +dittoctl things count -f 'exists(features/temp)' +dittoctl things fields -n org.example --path attributes # which paths exist, with types and examples +dittoctl things search -f 'gt(_modified,"2026-11-01T00:00:00Z")' --sort -_modified --limit 20 -o table +dittoctl things search -n org.example -o ids > ids.txt # one thing id per line, for piping +dittoctl things export -f @filter.rql --fields thingId,attributes,features/temp/properties --out temp.csv --excel +dittoctl things watch -n org.example # live changes as NDJSON, Ctrl+C to stop +dittoctl things watch --ids org.example:sensor-1 --max-events 1 --duration 2m # wait for the next change +``` + +`things fields` inspects the first `--sample` matching things (default 100) and lists every path with its JSON +types, how many things have it and a few example values: what to filter on and which fields to select, also for +things without a WoT model. + +Searches follow Ditto's result cursor through all pages. Long filters are sent as a form-encoded POST, so URL +length limits don't apply. `export` streams: memory use stays flat no matter how many things are exported. + +When only thing ids are needed (`-o ids`), dittoctl uses Ditto's SSE search stream instead: one request, about +twice as fast and cheaper for Ditto. As soon as other fields are selected, paging is about 4x faster and cheaper, +because Ditto retrieves each streamed thing with its own command. `--transport paging|sse` overrides the choice. +If a Ditto gateway throttles SSE search (`GATEWAY_SSE_THROTTLING_*`), turn the automatic streaming off for that +context with `config add-context ... --no-search-streaming`. + +Output formats (`-o`): `table` (default on a terminal), `ndjson` (default when piped), `json`, `csv`, `ids`. +For CSV, nested JSON is flattened into `/`-separated columns, discovered from the first 100 rows +(`--discover-rows N`, `0` for all rows) or set explicitly with `--columns`. `--short-headers` shortens the column +names, `--excel` writes a UTF-8 BOM and Excel-friendly timestamps. +On a terminal, JSON and NDJSON output is syntax-highlighted (`NO_COLOR=1` turns colors off); piped output and +files are plain. + +## Changing things + +Write commands act on a selection: thing ids as arguments, `--ids-file FILE` (or `-` for stdin), or +`-f/--filter RQL` (with `-n` namespaces), optionally narrowed with `--include-file`/`--exclude-file`. + +```shell +dittoctl things set attributes/location/room lab org.example:sensor-1 +dittoctl things patch features/config/properties -d '{"interval":60}' -f 'eq(attributes/model,"X1")' --dry-run +dittoctl things array add attributes/tags --items '["maintenance"]' --as-set -f 'eq(attributes/building,"B1")' +dittoctl things unset attributes/obsolete -f 'exists(attributes/obsolete)' +dittoctl things verify features/config/properties/interval --equals 60 -f 'eq(attributes/model,"X1")' +dittoctl things delete -f 'eq(attributes/decommissioned,true)' --yes +dittoctl things import backup.ndjson # create things from an NDJSON export +dittoctl things edit org.example:sensor-1 # in $EDITOR, written back with If-Match +dittoctl things diff org.example:sensor-1 --file sensor-1.json +dittoctl messages send reboot -f 'eq(attributes/firmware,"1.2.0")' --timeout 0 +``` + +Safety: + +- `--dry-run` shows what would be sent, without writing anything. +- Above `--max-affected` things (default 100) `--yes` is required. +- Deleting asks for confirmation, or needs `--yes` when not interactive. +- Contexts created with `--protected` require typing the context name, or `--confirm-context NAME`, for every + command that writes (also single writes such as `policies put`, and `api` with a writing method). +- Merge writes on the whole thing (`set`, `unset`, `patch /`) send `If-Match: *`: a thing that doesn't exist is + reported as `not-found` rather than created by Ditto. +- Bulk writes send `If-Equal: skip`, so re-running a command doesn't change anything that is already right. +- Array changes are read-modify-write with `If-Match`, so concurrent changes are never lost. +- A merge patch containing an array is refused, because it would replace the whole array (`--replace-array` + allows it). + +Bulk runs use `--concurrency` (default 8) parallel requests, optionally limited by `--rate N` per second, and print +a summary per result: `ok`, `unchanged`, `condition-not-met`, `exists`, `conflict`, `not-found`, `failed`. +`--failed-out FILE` lists the failed things; the file can be passed back as `--ids-file` to retry them. +`--journal FILE` records finished things, so that a run interrupted with Ctrl+C continues with `--resume`. +`--results failures|all` prints a JSON line per thing on stdout (failures with Ditto's error and its description), +then a summary line. Exit code 2 means some things failed. + +## Policies + +```shell +dittoctl policies get org.example:policy-1 --resolved # with imported entries (Ditto 3.9+) +dittoctl policies entries list org.example:policy-1 +dittoctl policies subjects add org.example:policy-1 users nginx:alice --expiring-at 2027-01-01T00:00:00Z +dittoctl policies imports add org.example:policy-1 org.example:shared-policy +dittoctl policies check org.example:sensor-1 --resource thing:/attributes --permission WRITE +dittoctl policies list -f 'like(policyId,"org.example:customer-*")' # policies of the matching things +``` + +`policies subjects migrate` adds a new subject next to (or, with `--remove-old`, instead of) every subject matching +a regular expression, with the same permissions and expiry. That's useful when switching identity providers. +Each policy is written atomically with `If-Match`, re-running is safe, and the bulk options (`--dry-run`, +`--journal`, ...) apply: + +```shell +dittoctl policies subjects migrate -f 'like(policyId,"org.example:customer-*")' \ + --match 'oldidp:(?P[0-9a-f-]{36})' --template 'newidp:fed-sub:\g' --dry-run +``` + +## Connections + +Ditto's connections API usually requires its DevOps login, so use a separate context for it: + +```shell +dittoctl config add-context prod-devops --url https://ditto.example.com --auth basic --username devops +dittoctl -c prod-devops connections list # URIs without passwords +dittoctl -c prod-devops connections test -d @mqtt-connection.json # connects once, creates nothing +dittoctl -c prod-devops connections put my-mqtt -d @mqtt-connection.json +dittoctl -c prod-devops connections status my-mqtt +dittoctl -c prod-devops connections logs my-mqtt --enable --follow +``` + +Ditto's connection log messages include the headers of the request that caused a message, including +`Authorization`. dittoctl masks those values and URI passwords unless `--no-redact` is given. + +## Live channel and paged messages + +```shell +# ask the device instead of the twin; fall back to the twin if it doesn't answer within 3s +dittoctl things get org.example:sensor-1 --path features --live --live-timeout 3 --live-timeout-strategy use-twin +# devices answering in pages: re-send while the answer contains "next", passing it on as "token" +dittoctl messages send history org.example:sensor-1 -d '{"from":"2026-11-01"}' --paginate next:token +dittoctl messages claim org.example:sensor-1 +``` + +## History + +With history retention configured in Ditto, earlier states of a thing can be read and streamed: + +```shell +dittoctl things get org.example:sensor-1 --at-revision 42 +dittoctl things get org.example:sensor-1 --at-time 2026-11-01T12:00:00Z +dittoctl things history org.example:sensor-1 --from-revision -10 # the last ten changes, as NDJSON +dittoctl things history org.example:sensor-1 --from-time 2026-11-01T00:00:00Z --to-time 2026-11-02T00:00:00Z +``` + +## Web of Things + +```shell +dittoctl things create org.example:lamp-1 --definition https://models.example.org/lamp-1.0.0.tm.jsonld +dittoctl things td org.example:lamp-1 # the Thing Description Ditto generates +dittoctl things td org.example:lamp-1 --with-features --compact # all features, in a compact form +dittoctl things migrate-definition --definition https://models.example.org/lamp-2.0.0.tm.jsonld \ + --init-defaults -f 'eq(definition,"https://models.example.org/lamp-1.0.0.tm.jsonld")' --dry-run +dittoctl wot directory # Ditto's Thing Directory (3.9+) +``` + +`migrate-definition --dry-run` lets Ditto compute the migration without applying it. + +`td --with-features` returns a thing's Thing Description together with those of all its features, in one +call. `--compact` leaves out what follows from Ditto's conventions: forms, security and error schemas. It +keeps titles, descriptions, data schemas, units and semantic types, plus the Ditto path of every property, +action and event. Features with the same description are listed once (`{"sameAs": ""}`), and so are +repeated data schemas (`{"$ref": "#/"}`). That makes it 7 to 12 times smaller for small models and +about 2.5 times for large real-world ones, which makes it a good way to tell an LLM agent what a thing offers. +`--no-schema-descriptions` also leaves out the descriptions inside data schemas, for another 20 to 25%. + +## DevOps + +Like connections, these commands need Ditto's DevOps login: + +```shell +dittoctl -c prod-devops devops status --health +dittoctl -c prod-devops devops logging set org.eclipse.ditto debug --service things +dittoctl -c prod-devops devops config gateway --path ditto.gateway.streaming +dittoctl -c prod-devops devops reindex -n org.example # rebuild the search index of a namespace +dittoctl -c prod-devops devops piggyback things -d @command.json +dittoctl -c prod-devops devops namespace erase org.example.old # block, shut down, purge, unblock +``` + +## RQL + +Filters are checked locally before they're sent, and errors point at the position: + +```shell +$ dittoctl rql lint 'and(eq(attributes/room,lab),exists(features/temp))' +Error: invalid RQL: expected a value: a quoted string, a number, true, false or null (strings need quotes) (at position 23) + and(eq(attributes/room,lab),exists(features/temp)) + ^ +$ dittoctl rql fmt 'and(eq(attributes/room,"lab"),exists(features/temp))' +and( + eq(attributes/room,"lab"), + exists(features/temp) +) +``` + +Filters may be written over several lines (e.g. in a file passed as `-f @filter.rql`); dittoctl removes the +whitespace before sending them. + +## Authentication + +| Method | Settings | Credentials | +|-----------|------------------------------------------------|---------------------------------------------------------------------| +| `none` | | | +| `basic` | `--username` | password via `auth login`, or `DITTOCTL_PASSWORD` | +| `token` | | bearer token via `auth login`, or `DITTOCTL_TOKEN` | +| `preauth` | `--subject`, e.g. `nginx:ditto` | none; sends the `x-ditto-pre-authenticated` header | +| `oidc` | `--issuer`, `--client-id`, `--flow`, `--scope` | `auth login` runs the `pkce`, `device` or `client-credentials` flow | + +Secrets are stored in the OS keyring. Where no keyring is available they go to a file readable only by you +(`~/.local/state/dittoctl/secrets.json`). Set `DITTOCTL_SECRET_STORE=keyring|file` to choose explicitly. +The config file (`~/.config/dittoctl/config.toml`) never contains secrets. + +## Conditional requests + +Ditto's conditional headers are first-class options on write commands: + +| Option | Ditto header / parameter | +|--------------------------------------------------|--------------------------------| +| `--if-match ETAG\|*` | `If-Match` | +| `--if-none-match ETAG\|*` | `If-None-Match` | +| `--if-equal update\|skip\|skip-minimizing-merge` | `If-Equal` | +| `--condition RQL` | `condition` | +| `--patch-condition PATH=RQL` | `merge-thing-patch-conditions` | +| `--live-condition RQL` | `live-channel-condition` | + +## Shell completion + +```shell +eval "$(dittoctl completion zsh)" # or bash; fish: dittoctl completion fish | source +``` + +## Use by AI agents + +dittoctl detects AI coding agents such as Claude Code (by the `CLAUDECODE` or `AI_AGENT` environment variables) +and then adapts its output; `--agent`/`--no-agent` or `DITTOCTL_AGENT=1|0` set it explicitly: + +- JSON on stdout is a single line, and errors are one JSON line on stderr: `exitCode`, `message`, and for Ditto + errors `status`, `error`, `description`, `correlationId`; usage errors include the usage line. +- `things search`, `export` (to stdout), `history` and `policies list` show the first 50 results and say so on + stderr if there are more; `--limit N` or `--all` override that. +- `things watch` and `connections logs --follow` stop after 30 seconds unless `--duration` (`0` for no limit) or + `--max-events` is given. +- Bulk writes print `--results failures`: a JSON line per failed thing, then a summary line. In a dry run, these + are the first planned requests. +- `things diff` prints a JSON list of changes. +- Writes to protected contexts are refused: a person should run those. + +Two commands tell an agent what it can work with: `things fields` (the paths and types of real things) and +`things td --with-features --compact` (the WoT Thing Description of modelled things, 2 to 12 times smaller). + +## Exit codes + +| Code | Meaning | +|------|-------------------------------------------------------------------------------------------------------| +| 0 | success | +| 1 | usage error or failed request | +| 2 | partial failure of a bulk operation | +| 3 | authentication failed | +| 4 | not found | +| 5 | aborted (e.g. by a safety check) | +| 6 | a check failed: differences (`diff`), mismatches (`verify`), denied permissions, invalid RQL (`lint`) | + +## Development + +```shell +.venv/bin/pytest +.venv/bin/ruff check src tests && .venv/bin/ruff format --check src tests +.venv/bin/python scripts/gen_reference.py # after changing commands or help texts (a test checks it) +``` + +## Contributing + +Contributions are welcome: see [CONTRIBUTING.md](CONTRIBUTING.md) and the [Code of Conduct](CODE_OF_CONDUCT.md). +Please report vulnerabilities as described in [SECURITY.md](SECURITY.md), not in public issues. + +## License + +[Eclipse Public License 2.0](https://www.eclipse.org/legal/epl-2.0/). dittoctl was largely created with the +assistance of an AI; the AI-generated portions are made available under +[CC0-1.0](legal/CC0-1.0.txt), as described in [NOTICE.md](NOTICE.md). diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..db7e635 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,40 @@ +# Security Policy + +Eclipse Ditto follows the [Eclipse Vulnerability Reporting Policy](https://www.eclipse.org/security/policy/). +Vulnerabilities are tracked by the Eclipse security team, in cooperation with the Ditto project leads. +Fixing vulnerabilities is taken care of by the Ditto project committers, with assistance and guidance of the security team. + +## How To Report a Vulnerability + +If you think you have found a vulnerability in this repository, please report it to us through coordinated disclosure. + +**Please do not report security vulnerabilities through public issues, discussions, or change requests.** + +Instead, report it using one of the following ways: + +* Create a [confidential issue](https://gitlab.eclipse.org/security/vulnerability-reports/-/issues/new?issuable_template=new_vulnerability) in the Eclipse Foundation Vulnerability Reporting Tracker + +You can find more information about reporting and disclosure at the [Eclipse Foundation Security page](https://www.eclipse.org/security/). + +Please include as much of the information listed below as you can to help us better understand and resolve the issue: + +* The type of issue (e.g., credential leakage, token handling, or command injection) +* Affected version(s) +* Impact of the issue, including how an attacker might exploit the issue +* Step-by-step instructions to reproduce the issue +* The location of the affected source code (tag/branch/commit or direct URL) +* Full paths of source file(s) related to the manifestation of the issue +* Configuration required to reproduce the issue +* Log files that are related to this issue (if possible) +* Proof-of-concept or exploit code (if possible) + +This information will help us triage your report more quickly. + +## Supported Versions + +dittoctl is in early development. Until 1.0, only the latest release receives security updates. + +| Version | Supported | +|------------------|--------------------| +| latest 0.x | :white_check_mark: | +| older 0.x | :x: | diff --git a/docs/reference.md b/docs/reference.md new file mode 100644 index 0000000..bff2654 --- /dev/null +++ b/docs/reference.md @@ -0,0 +1,1926 @@ +# Command reference + +Generated from the commands' help texts by `scripts/gen_reference.py`; don't edit by hand. + +## `dittoctl` + +```text +Usage: dittoctl [OPTIONS] COMMAND [ARGS]... + + dittoctl - command line tool for Eclipse Ditto. + +Options: + -V, --version Show the version and exit. + -c, --context TEXT Context to use instead of the current one. [env: DITTOCTL_CONTEXT] + --url TEXT Ditto base URL. Without --context, credentials come from DITTOCTL_TOKEN + or DITTOCTL_USERNAME/DITTOCTL_PASSWORD. [env: DITTOCTL_URL] + -H, --header NAME:VALUE Extra request header. Repeatable. + --timeout FLOAT Request timeout in seconds. + --correlation-id TEXT Prefix for the correlation-id of each request (default: random per run). + -v, --verbose -v prints requests as curl commands, -vv also response headers. + --config FILE Config file. [env: DITTOCTL_CONFIG] + --agent / --no-agent Output for AI agents: single-line JSON, errors as JSON, limited result + sizes, per-thing results of bulk writes, no writes to protected contexts. + Default: on if CLAUDECODE or AI_AGENT is set. [env: DITTOCTL_AGENT] + -h, --help Show this message and exit. + +Commands: + api Send an authenticated request to any Ditto endpoint and print the response. + auth Log in to the current context and manage its credentials. + completion Print the shell completion script. + config Manage contexts: named Ditto endpoints with their authentication settings. + connections Manage connections (usually needs Ditto's DevOps login: use a separate context). + devops Operate Ditto: log levels, configuration, piggyback commands, reindexing,... + messages Send messages to things and their features, for example commands for devices. + policies Read and change policies: entries, subjects, imports; check permissions; migrate... + rql Check and format RQL filter expressions, without contacting Ditto. + things Read, search, count, export and watch things. + whoami Show the subjects Ditto derives from your credentials. + wot Web of Things (WoT): Ditto's Thing Directory. +``` + +### `dittoctl api` + +```text +Usage: dittoctl api [OPTIONS] METHOD PATH + + Send an authenticated request to any Ditto endpoint and print the response. + + Examples: + dittoctl api GET /api/2/whoami + dittoctl api GET /api/2/things/org.example:sensor-1 -q fields=thingId,attributes + dittoctl api PATCH /api/2/things/org.example:sensor-1/attributes -d '{"location":"lab"}' --if-equal skip + dittoctl api PUT /api/2/things/org.example:sensor-2 -d @thing.json --if-none-match '*' + +Options: + -d, --data TEXT Request body: inline, @file, or @- for stdin. + -q, --query NAME=VALUE Query parameter. Repeatable. + --content-type TEXT Content type of the body (default: derived from method and body). + -i, --include Print the response status and headers to stderr. + -o, --output [json|ndjson|raw] Output format. [default: json] + --if-match ETAG|* Only apply if the entity has this ETag (e.g. rev:5); '*' requires + that it exists. + --if-none-match ETAG|* '*' only creates and never overwrites; with an ETag on reads, + Ditto answers 304 if unchanged. + --if-equal [update|skip|skip-minimizing-merge] + What Ditto does if the new value equals the current one; 'skip' + avoids no-op events. + --condition RQL Only apply if the entity matches this RQL condition. + --patch-condition PATH=RQL Per-path condition for merge requests (Ditto 3.8+). Repeatable. + --live-condition RQL Route retrieves to the live channel if this matches. + --live-timeout-strategy [fail|use-twin] + What to do if the device doesn't answer a live request in time. + --confirm-context NAME Confirm a protected context without the prompt (for scripts). + -h, --help Show this message and exit. +``` + +### `dittoctl auth` + +```text +Usage: dittoctl auth [OPTIONS] COMMAND [ARGS]... + + Log in to the current context and manage its credentials. + +Options: + -h, --help Show this message and exit. + +Commands: + login Obtain credentials and store them in the OS keyring. + logout Delete the stored credentials of the current context. + status Show how the current context authenticates and whether credentials are available. + token Print a valid bearer token, for example to paste into the Ditto UI or use with curl. +``` + +#### `dittoctl auth login` + +```text +Usage: dittoctl auth login [OPTIONS] + + Obtain credentials and store them in the OS keyring. + + basic prompts for the password (or reads it with --password-stdin) + token prompts for the token (or reads it with --token-stdin) + oidc runs the configured flow: browser login (pkce), device code (device), + or client credentials (with the client secret from --secret-stdin) + +Options: + --password-stdin [basic] Read the password from stdin. + --token-stdin [token] Read the bearer token from stdin. + --secret-stdin [oidc] Read the client secret from stdin. + --no-browser [oidc pkce] Print the login URL instead of opening a browser. + -h, --help Show this message and exit. +``` + +#### `dittoctl auth logout` + +```text +Usage: dittoctl auth logout [OPTIONS] + + Delete the stored credentials of the current context. + +Options: + -h, --help Show this message and exit. +``` + +#### `dittoctl auth status` + +```text +Usage: dittoctl auth status [OPTIONS] + + Show how the current context authenticates and whether credentials are available. + +Options: + -o, --output [text|json] Output format. [default: text] + -h, --help Show this message and exit. +``` + +#### `dittoctl auth token` + +```text +Usage: dittoctl auth token [OPTIONS] + + Print a valid bearer token, for example to paste into the Ditto UI or use with curl. + +Options: + -h, --help Show this message and exit. +``` + +### `dittoctl completion` + +```text +Usage: dittoctl completion [OPTIONS] {bash|zsh|fish} + + Print the shell completion script. + + bash: eval "$(dittoctl completion bash)" + zsh: eval "$(dittoctl completion zsh)" + fish: dittoctl completion fish | source + +Options: + -h, --help Show this message and exit. +``` + +### `dittoctl config` + +```text +Usage: dittoctl config [OPTIONS] COMMAND [ARGS]... + + Manage contexts: named Ditto endpoints with their authentication settings. + +Options: + -h, --help Show this message and exit. + +Commands: + add-context Add a context. + current-context Print the name of the current context. + delete-context Delete a context and its stored credentials. + get-contexts List all contexts. + path Print the path of the config file. + use-context Select the context used when --context is not given. + view Print the configuration, or a single context, as TOML. +``` + +#### `dittoctl config add-context` + +```text +Usage: dittoctl config add-context [OPTIONS] NAME + + Add a context. + +Options: + --url TEXT Base URL of Ditto, e.g. https://ditto.example.com [required] + --auth [none|basic|token|preauth|oidc] + How to authenticate; the options below marked [method] configure + it. [default: none] + --username TEXT [basic] User name. + --subject TEXT [preauth] Value of the x-ditto-pre-authenticated header, e.g. + nginx:ditto. + --issuer TEXT [oidc] Issuer URL used for discovery. + --client-id TEXT [oidc] OAuth2 client id. + --flow [pkce|device|client-credentials] + [oidc] Login flow. [default: pkce] + --scope TEXT [oidc] Scope to request; repeatable. Default: openid. + --auth-param NAME=VALUE [oidc] Extra parameter for the authorization request, e.g. + audience=ditto. Repeatable. + --redirect-port INTEGER [oidc] Fixed loopback port for the PKCE redirect (default: + random). + --use-id-token [oidc] Send the id token to Ditto instead of the access token. + --namespace TEXT Default namespace for searches. Repeatable. + --header NAME=VALUE Header sent with every request. + --protected Require typing the context name to confirm writes (e.g. + production). + --timeout FLOAT Request timeout in seconds. [default: 30.0] + --ca-cert FILE CA bundle to verify TLS with. + --insecure Don't verify TLS certificates. + --no-search-streaming Never stream searches via SSE automatically, e.g. if the Ditto + gateway throttles SSE search. + --use / --no-use Make it the current context (default: if it's the first). + --overwrite Replace an existing context with the same name. + -h, --help Show this message and exit. +``` + +#### `dittoctl config current-context` + +```text +Usage: dittoctl config current-context [OPTIONS] + + Print the name of the current context. + +Options: + -h, --help Show this message and exit. +``` + +#### `dittoctl config delete-context` + +```text +Usage: dittoctl config delete-context [OPTIONS] NAME + + Delete a context and its stored credentials. + +Options: + -h, --help Show this message and exit. +``` + +#### `dittoctl config get-contexts` + +```text +Usage: dittoctl config get-contexts [OPTIONS] + + List all contexts. + +Options: + -h, --help Show this message and exit. +``` + +#### `dittoctl config path` + +```text +Usage: dittoctl config path [OPTIONS] + + Print the path of the config file. + +Options: + -h, --help Show this message and exit. +``` + +#### `dittoctl config use-context` + +```text +Usage: dittoctl config use-context [OPTIONS] NAME + + Select the context used when --context is not given. + +Options: + -h, --help Show this message and exit. +``` + +#### `dittoctl config view` + +```text +Usage: dittoctl config view [OPTIONS] [NAME] + + Print the configuration, or a single context, as TOML. + +Options: + -h, --help Show this message and exit. +``` + +### `dittoctl connections` + +```text +Usage: dittoctl connections [OPTIONS] COMMAND [ARGS]... + + Manage connections (usually needs Ditto's DevOps login: use a separate context). + +Options: + -h, --help Show this message and exit. + +Commands: + close Close a connection. + create Create a connection; fails if it exists. + delete Delete a connection. + get Retrieve a connection's configuration. + list List all connections. + logs Show a connection's logs: successful and failed messages per source/target... + metrics Show a connection's message metrics. + open Open a connection. + put Create or replace a connection with the given id. + reset-metrics Reset a connection's metrics. + status Show the live status of a connection, its clients, sources and targets. + test Check a connection configuration (Ditto connects once, then discards it;... +``` + +#### `dittoctl connections close` + +```text +Usage: dittoctl connections close [OPTIONS] CONNECTION_ID + + Close a connection. + +Options: + --confirm-context NAME Confirm a protected context without the prompt (for scripts). + -h, --help Show this message and exit. +``` + +#### `dittoctl connections create` + +```text +Usage: dittoctl connections create [OPTIONS] + + Create a connection; fails if it exists. Without an "id" in the JSON, Ditto generates one. + + See 'connections test' to check a connection without creating it. + +Options: + -d, --data JSON|@FILE|@- The connection JSON. [required] + --confirm-context NAME Confirm a protected context without the prompt (for scripts). + -h, --help Show this message and exit. +``` + +#### `dittoctl connections delete` + +```text +Usage: dittoctl connections delete [OPTIONS] CONNECTION_ID + + Delete a connection. + +Options: + -y, --yes Don't ask for confirmation. + --confirm-context NAME Confirm a protected context without the prompt (for scripts). + -h, --help Show this message and exit. +``` + +#### `dittoctl connections get` + +```text +Usage: dittoctl connections get [OPTIONS] CONNECTION_ID + + Retrieve a connection's configuration. + +Options: + -h, --help Show this message and exit. +``` + +#### `dittoctl connections list` + +```text +Usage: dittoctl connections list [OPTIONS] + + List all connections. URIs are shown without passwords. + +Options: + -o, --output [table|json|ids] Output format. [default: table] + -h, --help Show this message and exit. +``` + +#### `dittoctl connections logs` + +```text +Usage: dittoctl connections logs [OPTIONS] CONNECTION_ID + + Show a connection's logs: successful and failed messages per source/target address. + + Ditto's log messages contain the headers of the request that caused a message, including + Authorization headers; dittoctl masks them unless --no-redact is given. The table shortens long + messages; -o ndjson shows them completely. + + Example: + dittoctl connections logs my-connection --enable --follow -o ndjson + +Options: + --enable Enable logging first (Ditto keeps it on for a limited time). + --reset Clear the logs first. + --follow Keep polling and print new entries as they appear, until Ctrl+C or + --duration. + --interval FLOAT Seconds between polls with --follow. [default: 2.0] + --duration DURATION Stop following after this long, e.g. 30s or 5m; 0 never stops + (default; agent mode: 30s). + --no-redact Show Authorization headers and URI passwords in log messages. + -o, --output [table|ndjson] Output format. [default: table] + --confirm-context NAME Confirm a protected context without the prompt (for scripts). + -h, --help Show this message and exit. +``` + +#### `dittoctl connections metrics` + +```text +Usage: dittoctl connections metrics [OPTIONS] CONNECTION_ID + + Show a connection's message metrics. + +Options: + -h, --help Show this message and exit. +``` + +#### `dittoctl connections open` + +```text +Usage: dittoctl connections open [OPTIONS] CONNECTION_ID + + Open a connection. + +Options: + --confirm-context NAME Confirm a protected context without the prompt (for scripts). + -h, --help Show this message and exit. +``` + +#### `dittoctl connections put` + +```text +Usage: dittoctl connections put [OPTIONS] CONNECTION_ID + + Create or replace a connection with the given id. + +Options: + -d, --data JSON|@FILE|@- The connection JSON. [required] + --confirm-context NAME Confirm a protected context without the prompt (for scripts). + -h, --help Show this message and exit. +``` + +#### `dittoctl connections reset-metrics` + +```text +Usage: dittoctl connections reset-metrics [OPTIONS] CONNECTION_ID + + Reset a connection's metrics. + +Options: + --confirm-context NAME Confirm a protected context without the prompt (for scripts). + -h, --help Show this message and exit. +``` + +#### `dittoctl connections status` + +```text +Usage: dittoctl connections status [OPTIONS] CONNECTION_ID + + Show the live status of a connection, its clients, sources and targets. + +Options: + -o, --output [table|json] Output format. [default: table] + -h, --help Show this message and exit. +``` + +#### `dittoctl connections test` + +```text +Usage: dittoctl connections test [OPTIONS] + + Check a connection configuration (Ditto connects once, then discards it; nothing is created). + +Options: + -d, --data JSON|@FILE|@- The connection JSON to test. [required] + -h, --help Show this message and exit. +``` + +### `dittoctl devops` + +```text +Usage: dittoctl devops [OPTIONS] COMMAND [ARGS]... + + Operate Ditto: log levels, configuration, piggyback commands, reindexing, namespaces, status. + + These endpoints need Ditto's DevOps login; use a separate context, e.g. 'dittoctl -c prod-devops + devops ...'. + +Options: + -h, --help Show this message and exit. + +Commands: + config Show the runtime configuration of services (large: narrow it down with --path). + logging Show and change log levels at runtime. + namespace Namespace operations. + piggyback Send a piggyback command to actors in the Ditto cluster (SERVICE: things, search,... + reindex Rebuild search index entries: of single things immediately, or of all things (or... + status Show the Ditto version and gateway status, optionally with the cluster health. +``` + +#### `dittoctl devops config` + +```text +Usage: dittoctl devops config [OPTIONS] [gateway|things|things-search|policies|connectivity] + + Show the runtime configuration of services (large: narrow it down with --path). + +Options: + --instance TEXT Only this instance of the service. + --path TEXT Only this part of the configuration, e.g. ditto.gateway.streaming. + -h, --help Show this message and exit. +``` + +#### `dittoctl devops logging` + +```text +Usage: dittoctl devops logging [OPTIONS] COMMAND [ARGS]... + + Show and change log levels at runtime. + +Options: + -h, --help Show this message and exit. + +Commands: + get Show the log levels of all services, or of one. + set Set the level of a logger, such as 'org.eclipse.ditto debug'. +``` + +#### `dittoctl devops logging get` + +```text +Usage: dittoctl devops logging get [OPTIONS] [gateway|things|things-search|policies|connectivity] + + Show the log levels of all services, or of one. + +Options: + -o, --output [table|json] Output format. [default: table] + -h, --help Show this message and exit. +``` + +#### `dittoctl devops logging set` + +```text +Usage: dittoctl devops logging set [OPTIONS] LOGGER {trace|debug|info|warn|error|off} + + Set the level of a logger, such as 'org.eclipse.ditto debug'. Takes effect immediately, until a + restart. + +Options: + --service [gateway|things|things-search|policies|connectivity] + Only this service (default: all). + --confirm-context NAME Confirm a protected context without the prompt (for scripts). + -h, --help Show this message and exit. +``` + +#### `dittoctl devops namespace` + +```text +Usage: dittoctl devops namespace [OPTIONS] COMMAND [ARGS]... + + Namespace operations. + +Options: + -h, --help Show this message and exit. + +Commands: + erase Erase ALL data of a namespace: things, policies, connections' data and search index... +``` + +#### `dittoctl devops namespace erase` + +```text +Usage: dittoctl devops namespace erase [OPTIONS] NAMESPACE + + Erase ALL data of a namespace: things, policies, connections' data and search index entries. + + Runs Ditto's documented sequence: block the namespace, shut down its actors, purge its data from + the persistence, unblock it. Cannot be undone. + +Options: + --confirm-namespace NAMESPACE Confirm without the prompt (for scripts). + --purge-timeout TEXT How long Ditto waits for the services to confirm the erasure. + [default: 10s] + --confirm-context NAME Confirm a protected context without the prompt (for scripts). + -h, --help Show this message and exit. +``` + +#### `dittoctl devops piggyback` + +```text +Usage: dittoctl devops piggyback [OPTIONS] [SERVICE] + + Send a piggyback command to actors in the Ditto cluster (SERVICE: things, search, connectivity, + ...). + + See https://eclipse.dev/ditto/installation-operating.html#piggyback-commands + +Options: + -d, --data JSON|@FILE|@- The piggyback command: targetActorSelection, headers, piggybackCommand. + [required] + --instance TEXT Only this instance of the service. + --timeout TEXT How long Ditto waits for responses, e.g. 30s. [default: 10s] + --confirm-context NAME Confirm a protected context without the prompt (for scripts). + -h, --help Show this message and exit. +``` + +#### `dittoctl devops reindex` + +```text +Usage: dittoctl devops reindex [OPTIONS] + + Rebuild search index entries: of single things immediately, or of all things (or namespaces) in + the next background sync. Ditto doesn't report progress; follow the search service's logs. + +Options: + -n, --namespace TEXT Only things of this namespace. Repeatable. + --thing THING_ID Update this thing now. Repeatable. + --confirm-context NAME Confirm a protected context without the prompt (for scripts). + -h, --help Show this message and exit. +``` + +#### `dittoctl devops status` + +```text +Usage: dittoctl devops status [OPTIONS] + + Show the Ditto version and gateway status, optionally with the cluster health. + +Options: + --health Also show the health of all cluster members. + -o, --output [text|json] Output format. [default: text] + -h, --help Show this message and exit. +``` + +### `dittoctl messages` + +```text +Usage: dittoctl messages [OPTIONS] COMMAND [ARGS]... + + Send messages to things and their features, for example commands for devices. + +Options: + -h, --help Show this message and exit. + +Commands: + claim Claim a thing: send a claim message to its inbox, which the device (or a connected... + send Send the message SUBJECT to each selected thing and print the responses as NDJSON. +``` + +#### `dittoctl messages claim` + +```text +Usage: dittoctl messages claim [OPTIONS] THING_ID + + Claim a thing: send a claim message to its inbox, which the device (or a connected service) + answers, for example by granting you access in the thing's policy. + +Options: + --timeout INTEGER RANGE Seconds to wait for the device's answer. [default: 10; 0<=x<=60] + --confirm-context NAME Confirm a protected context without the prompt (for scripts). + -h, --help Show this message and exit. +``` + +#### `dittoctl messages send` + +```text +Usage: dittoctl messages send [OPTIONS] SUBJECT [THING_ID]... + + Send the message SUBJECT to each selected thing and print the responses as NDJSON. + + Each response line has thingId, result, status and response; with --results, failed things get a + line too. + + Messages are not retried automatically, as devices may not handle duplicates. + + Examples: + dittoctl messages send reboot org.example:sensor-1 --timeout 0 + dittoctl messages send set-interval -d '{"seconds":60}' --feature config -f 'eq(attributes/model,"X1")' + +Options: + -d, --data JSON|TEXT|@FILE|@- Message payload; JSON if it parses, else text. + --content-type TEXT Content type of the payload (default: application/json, or + text/plain). + --feature TEXT Send to this feature of each thing instead of the thing itself. + --outbox Send from the thing (outbox) instead of to it (inbox). + --timeout INTEGER RANGE Seconds to wait for each response; 0 sends without waiting (fire + and forget). [default: 10; 0<=x<=60] + --paginate RESPONSE_FIELD[:REQUEST_FIELD] + Follow paged answers: re-send while the response contains + RESPONSE_FIELD, passing its value as REQUEST_FIELD (default: the + same name) in the payload. + --max-pages INTEGER RANGE Upper limit of pages per thing with --paginate. [default: 100; + x>=1] + --ids-file FILE Thing ids, one per line (first column); - reads stdin. + -f, --filter RQL Select by RQL filter; @file reads it. + --no-validate Send the filter without checking it locally first. + -n, --namespaces NS[,NS] Namespaces for --filter. + --include-file FILE Only things whose id is also in this file. + --exclude-file FILE Leave out things whose id is in this file. + --dry-run Show what would be sent, without writing anything. + -y, --yes Don't ask; required above --max-affected things. + --max-affected INTEGER RANGE Above this many things, --yes is required. [default: 100; x>=0] + --confirm-context NAME Confirm a protected context without the prompt (for scripts). + --concurrency INTEGER RANGE Requests in flight at the same time. [default: 8; 1<=x<=64] + --rate N At most N requests per second. + --journal FILE Record finished things here, to --resume later. + --resume Skip the things already recorded in --journal. + --failed-out FILE Write failed things here (usable as --ids-file to retry them). + --results [none|failures|all] Print a JSON line per thing on stdout: 'failures' (with Ditto's + error and its description; in a dry run, the first planned + requests) or 'all', then a summary line. Default: none; agent + mode: failures. + -h, --help Show this message and exit. +``` + +### `dittoctl policies` + +```text +Usage: dittoctl policies [OPTIONS] COMMAND [ARGS]... + + Read and change policies: entries, subjects, imports; check permissions; migrate subjects in bulk. + +Options: + -h, --help Show this message and exit. + +Commands: + activate-token-integration Add the subject derived from your token to the policy's entries... + check Check which of the given resources of a thing or policy you may... + deactivate-token-integration Remove the subject derived from your token from the policy's... + delete Delete a policy. + entries Policy entries: who (subjects) may do what (resources). + get Retrieve a policy. + imports Policy imports: reuse entries of other policies. + list List the distinct policy ids of the things matching a filter. + put Create or completely replace a policy. + subjects Subjects of policy entries: add, remove, and migrate them... +``` + +#### `dittoctl policies activate-token-integration` + +```text +Usage: dittoctl policies activate-token-integration [OPTIONS] POLICY_ID + + Add the subject derived from your token to the policy's entries (needs EXECUTE permission on the + action and a token-based login; the subject expires with the token). + +Options: + --label TEXT Only this entry (default: all entries you may execute it on). + --confirm-context NAME Confirm a protected context without the prompt (for scripts). + -h, --help Show this message and exit. +``` + +#### `dittoctl policies check` + +```text +Usage: dittoctl policies check [OPTIONS] ENTITY_ID + + Check which of the given resources of a thing or policy you may access (Ditto 3.7+). + + Exit code 6 if any check is denied. + + Example: + dittoctl policies check org.example:sensor-1 --resource thing:/attributes --resource thing:/features/temp \ + --permission READ --permission WRITE + +Options: + --resource RESOURCE E.g. thing:/attributes/location, thing:/features/temp, policy:/, + message:/. Repeatable. [required] + --permission [READ|WRITE] Permissions to check. Repeatable. [default: READ] + -h, --help Show this message and exit. +``` + +#### `dittoctl policies deactivate-token-integration` + +```text +Usage: dittoctl policies deactivate-token-integration [OPTIONS] POLICY_ID + + Remove the subject derived from your token from the policy's entries (needs EXECUTE permission on + the action and a token-based login; the subject expires with the token). + +Options: + --label TEXT Only this entry (default: all entries you may execute it on). + --confirm-context NAME Confirm a protected context without the prompt (for scripts). + -h, --help Show this message and exit. +``` + +#### `dittoctl policies delete` + +```text +Usage: dittoctl policies delete [OPTIONS] POLICY_ID + + Delete a policy. Things that still use it become inaccessible. + +Options: + -y, --yes Don't ask for confirmation. + --confirm-context NAME Confirm a protected context without the prompt (for scripts). + -h, --help Show this message and exit. +``` + +#### `dittoctl policies entries` + +```text +Usage: dittoctl policies entries [OPTIONS] COMMAND [ARGS]... + + Policy entries: who (subjects) may do what (resources). + +Options: + -h, --help Show this message and exit. + +Commands: + delete Delete one entry. + get Retrieve one entry. + list Show the entries of a policy as a table. + put Create or replace one entry. +``` + +#### `dittoctl policies entries delete` + +```text +Usage: dittoctl policies entries delete [OPTIONS] POLICY_ID LABEL + + Delete one entry. + +Options: + --allow-lockout Allow a change that removes your own WRITE permission on the policy (Ditto + refuses it otherwise). + --confirm-context NAME Confirm a protected context without the prompt (for scripts). + -h, --help Show this message and exit. +``` + +#### `dittoctl policies entries get` + +```text +Usage: dittoctl policies entries get [OPTIONS] POLICY_ID LABEL + + Retrieve one entry. + +Options: + -h, --help Show this message and exit. +``` + +#### `dittoctl policies entries list` + +```text +Usage: dittoctl policies entries list [OPTIONS] POLICY_ID + + Show the entries of a policy as a table. + +Options: + -h, --help Show this message and exit. +``` + +#### `dittoctl policies entries put` + +```text +Usage: dittoctl policies entries put [OPTIONS] POLICY_ID LABEL + + Create or replace one entry. + +Options: + -d, --data JSON|@FILE|@- The entry: subjects and resources. [required] + --allow-lockout Allow a change that removes your own WRITE permission on the + policy (Ditto refuses it otherwise). + --if-match ETAG|* Only apply if the entity has this ETag (e.g. rev:5); '*' requires + that it exists. + --if-none-match ETAG|* '*' only creates and never overwrites; with an ETag on reads, + Ditto answers 304 if unchanged. + --if-equal [update|skip|skip-minimizing-merge] + What Ditto does if the new value equals the current one; 'skip' + avoids no-op events. + --condition RQL Only apply if the entity matches this RQL condition. + --patch-condition PATH=RQL Per-path condition for merge requests (Ditto 3.8+). Repeatable. + --live-condition RQL Route retrieves to the live channel if this matches. + --live-timeout-strategy [fail|use-twin] + What to do if the device doesn't answer a live request in time. + --confirm-context NAME Confirm a protected context without the prompt (for scripts). + -h, --help Show this message and exit. +``` + +#### `dittoctl policies get` + +```text +Usage: dittoctl policies get [OPTIONS] POLICY_ID + + Retrieve a policy. + +Options: + --resolved Show the effective policy with imports resolved (Ditto 3.9+). + --path TEXT Only this part, e.g. entries/owner or imports. + -o, --output [json|ndjson] Output format. [default: json] + --if-match ETAG|* Only apply if the entity has this ETag (e.g. rev:5); '*' requires + that it exists. + --if-none-match ETAG|* '*' only creates and never overwrites; with an ETag on reads, + Ditto answers 304 if unchanged. + --if-equal [update|skip|skip-minimizing-merge] + What Ditto does if the new value equals the current one; 'skip' + avoids no-op events. + --condition RQL Only apply if the entity matches this RQL condition. + --patch-condition PATH=RQL Per-path condition for merge requests (Ditto 3.8+). Repeatable. + --live-condition RQL Route retrieves to the live channel if this matches. + --live-timeout-strategy [fail|use-twin] + What to do if the device doesn't answer a live request in time. + -h, --help Show this message and exit. +``` + +#### `dittoctl policies imports` + +```text +Usage: dittoctl policies imports [OPTIONS] COMMAND [ARGS]... + + Policy imports: reuse entries of other policies. + +Options: + -h, --help Show this message and exit. + +Commands: + add Import the entries of another policy. + list Show the imports of a policy. + remove Remove an import. +``` + +#### `dittoctl policies imports add` + +```text +Usage: dittoctl policies imports add [OPTIONS] POLICY_ID IMPORTED_POLICY_ID + + Import the entries of another policy. + +Options: + --entry LABEL Import only this entry (it must be importable). Repeatable; default: all + implicit ones. + --confirm-context NAME Confirm a protected context without the prompt (for scripts). + -h, --help Show this message and exit. +``` + +#### `dittoctl policies imports list` + +```text +Usage: dittoctl policies imports list [OPTIONS] POLICY_ID + + Show the imports of a policy. + +Options: + -h, --help Show this message and exit. +``` + +#### `dittoctl policies imports remove` + +```text +Usage: dittoctl policies imports remove [OPTIONS] POLICY_ID IMPORTED_POLICY_ID + + Remove an import. + +Options: + --confirm-context NAME Confirm a protected context without the prompt (for scripts). + -h, --help Show this message and exit. +``` + +#### `dittoctl policies list` + +```text +Usage: dittoctl policies list [OPTIONS] + + List the distinct policy ids of the things matching a filter. + + Ditto can't search policies directly, so they are found via the things using them. + + Example: + dittoctl policies list -f 'like(policyId,"org.example:customer-*")' > policies.txt + +Options: + -f, --filter RQL Filter on things; @file reads it. + --no-validate Send the filter without checking it locally first. + -n, --namespaces NS[,NS] Namespaces of the things. + --all Don't limit the output (agent mode shows the first 50 by default). + -h, --help Show this message and exit. +``` + +#### `dittoctl policies put` + +```text +Usage: dittoctl policies put [OPTIONS] POLICY_ID + + Create or completely replace a policy. + +Options: + -d, --data JSON|@FILE|@- The complete policy JSON. [required] + --allow-lockout Allow a change that removes your own WRITE permission on the + policy (Ditto refuses it otherwise). + --if-match ETAG|* Only apply if the entity has this ETag (e.g. rev:5); '*' requires + that it exists. + --if-none-match ETAG|* '*' only creates and never overwrites; with an ETag on reads, + Ditto answers 304 if unchanged. + --if-equal [update|skip|skip-minimizing-merge] + What Ditto does if the new value equals the current one; 'skip' + avoids no-op events. + --condition RQL Only apply if the entity matches this RQL condition. + --patch-condition PATH=RQL Per-path condition for merge requests (Ditto 3.8+). Repeatable. + --live-condition RQL Route retrieves to the live channel if this matches. + --live-timeout-strategy [fail|use-twin] + What to do if the device doesn't answer a live request in time. + --confirm-context NAME Confirm a protected context without the prompt (for scripts). + -h, --help Show this message and exit. +``` + +#### `dittoctl policies subjects` + +```text +Usage: dittoctl policies subjects [OPTIONS] COMMAND [ARGS]... + + Subjects of policy entries: add, remove, and migrate them across many policies. + +Options: + -h, --help Show this message and exit. + +Commands: + add Add (or update) a subject of an entry, such as 'integration:my-app' or 'nginx:alice'. + migrate Add a new subject next to (or instead of) every subject matching --match, with the... + remove Remove a subject from an entry. +``` + +#### `dittoctl policies subjects add` + +```text +Usage: dittoctl policies subjects add [OPTIONS] POLICY_ID LABEL SUBJECT_ID + + Add (or update) a subject of an entry, such as 'integration:my-app' or 'nginx:alice'. + +Options: + --type TEXT Subject type. [default: added by dittoctl] + --expiring-at TIMESTAMP ISO-8601 time after which Ditto removes the subject. + --confirm-context NAME Confirm a protected context without the prompt (for scripts). + -h, --help Show this message and exit. +``` + +#### `dittoctl policies subjects migrate` + +```text +Usage: dittoctl policies subjects migrate [OPTIONS] [POLICY_ID]... + + Add a new subject next to (or instead of) every subject matching --match, with the same + permissions. + + Typical when switching identity providers: users keep their permissions under their new subject + ids. Each policy is written atomically with If-Match; running the migration again changes nothing. + + Example (add a twin subject for every user of an old IdP, keep the old one for now): + dittoctl policies subjects migrate -f 'like(policyId,"org.example:customer-*")' \ + --match 'oldidp:(?P[0-9a-f-]{36})' --template 'newidp:fed-sub:\g' --dry-run + +Options: + --ids-file FILE Policy ids, one per line; - reads stdin. + -f, --filter RQL Migrate the policies of the things matching this. + --no-validate Send the filter without checking it locally first. + -n, --namespaces NS[,NS] Namespaces of the things for --filter. + --match REGEX Subject ids to migrate (full match). [required] + --template TEMPLATE The new subject id; \1 or \g insert groups of --match. + [required] + --label TEXT Only in entries with this label. Repeatable. + --remove-old Replace the matching subjects instead of adding next to them. + --conflict-retries INTEGER RANGE + How often to re-read and retry when a policy was changed + concurrently. [default: 3; x>=0] + --allow-lockout Allow a change that removes your own WRITE permission on the + policy (Ditto refuses it otherwise). + --dry-run Show what would be sent, without writing anything. + -y, --yes Don't ask; required above --max-affected things. + --max-affected INTEGER RANGE Above this many things, --yes is required. [default: 100; x>=0] + --confirm-context NAME Confirm a protected context without the prompt (for scripts). + --concurrency INTEGER RANGE Requests in flight at the same time. [default: 8; 1<=x<=64] + --rate N At most N requests per second. + --journal FILE Record finished things here, to --resume later. + --resume Skip the things already recorded in --journal. + --failed-out FILE Write failed things here (usable as --ids-file to retry them). + --results [none|failures|all] Print a JSON line per thing on stdout: 'failures' (with Ditto's + error and its description; in a dry run, the first planned + requests) or 'all', then a summary line. Default: none; agent + mode: failures. + -h, --help Show this message and exit. +``` + +#### `dittoctl policies subjects remove` + +```text +Usage: dittoctl policies subjects remove [OPTIONS] POLICY_ID LABEL SUBJECT_ID + + Remove a subject from an entry. + +Options: + --allow-lockout Allow a change that removes your own WRITE permission on the policy (Ditto + refuses it otherwise). + --confirm-context NAME Confirm a protected context without the prompt (for scripts). + -h, --help Show this message and exit. +``` + +### `dittoctl rql` + +```text +Usage: dittoctl rql [OPTIONS] COMMAND [ARGS]... + + Check and format RQL filter expressions, without contacting Ditto. + +Options: + -h, --help Show this message and exit. + +Commands: + fmt Pretty-print an RQL filter, one condition per line. + lint Check an RQL filter; on error, show where it is. +``` + +#### `dittoctl rql fmt` + +```text +Usage: dittoctl rql fmt [OPTIONS] EXPRESSION|@FILE|@- + + Pretty-print an RQL filter, one condition per line. + +Options: + --compact Single line without whitespace (the form sent to Ditto). + -h, --help Show this message and exit. +``` + +#### `dittoctl rql lint` + +```text +Usage: dittoctl rql lint [OPTIONS] EXPRESSION|@FILE|@- + + Check an RQL filter; on error, show where it is. Exit code 6 if invalid. + +Options: + -h, --help Show this message and exit. +``` + +### `dittoctl things` + +```text +Usage: dittoctl things [OPTIONS] COMMAND [ARGS]... + + Read, search, count, export and watch things. + +Options: + -h, --help Show this message and exit. + +Commands: + array Add items to, or remove them from, an array in each selected thing,... + count Count the things matching an RQL filter. + create Create a thing; fails if it already exists. + delete Delete the selected things. + diff Show the differences between a local JSON file and the thing in Ditto... + edit Edit a thing in $EDITOR; the changes are sent as a merge patch with... + export Export search results to a file, streaming: memory use stays flat... + fields Show which paths the matching things have, with JSON types, frequency and... + get Retrieve one or more things. + history Show the changes of a thing per revision as NDJSON, oldest first (needs... + import Create (or replace) things from NDJSON or a JSON array, such as a 'things... + migrate-definition Move each selected thing to a new thing definition (Thing Model version),... + patch Merge-patch (RFC 7396) a part of each selected thing; PATH '/' patches... + put Create or completely replace a thing. + search Search things with RQL, following the result cursor through all pages. + set Set the value at PATH of each selected thing, creating missing parents. + td Show the WoT Thing Description Ditto generates from the thing's... + unset Remove the value at PATH of each selected thing (absent values are fine,... + verify Check that PATH has the expected value in each selected thing, for... + watch Follow thing changes as they happen, one JSON object per line. +``` + +#### `dittoctl things array` + +```text +Usage: dittoctl things array [OPTIONS] COMMAND [ARGS]... + + Add items to, or remove them from, an array in each selected thing, without losing concurrent + changes. + +Options: + -h, --help Show this message and exit. + +Commands: + add Append the --items to the array at PATH of each selected thing. + remove Remove every occurrence of the --items from the array at PATH of each selected thing. +``` + +#### `dittoctl things array add` + +```text +Usage: dittoctl things array add [OPTIONS] PATH [THING_ID]... + + Append the --items to the array at PATH of each selected thing. + + Each array is read with its ETag and written with If-Match, so concurrent changes are never lost; + things whose array wouldn't change aren't written. + + Example: + dittoctl things array add attributes/tags --items '["maintenance"]' --as-set -f 'eq(attributes/building,"B1")' + +Options: + --items JSON|@FILE A JSON array of the items. [required] + --as-set Only add items that aren't present yet. + --compare [deep|json] Item equality: 'deep' (1 equals 1.0) or 'json' (canonical text). + [default: deep] + --conflict-retries INTEGER RANGE + How often to re-read and retry when the array was changed + concurrently. [default: 3; x>=0] + --ids-file FILE Thing ids, one per line (first column); - reads stdin. + -f, --filter RQL Select by RQL filter; @file reads it. + --no-validate Send the filter without checking it locally first. + -n, --namespaces NS[,NS] Namespaces for --filter. + --include-file FILE Only things whose id is also in this file. + --exclude-file FILE Leave out things whose id is in this file. + --dry-run Show what would be sent, without writing anything. + -y, --yes Don't ask; required above --max-affected things. + --max-affected INTEGER RANGE Above this many things, --yes is required. [default: 100; x>=0] + --confirm-context NAME Confirm a protected context without the prompt (for scripts). + --concurrency INTEGER RANGE Requests in flight at the same time. [default: 8; 1<=x<=64] + --rate N At most N requests per second. + --journal FILE Record finished things here, to --resume later. + --resume Skip the things already recorded in --journal. + --failed-out FILE Write failed things here (usable as --ids-file to retry them). + --results [none|failures|all] Print a JSON line per thing on stdout: 'failures' (with Ditto's + error and its description; in a dry run, the first planned + requests) or 'all', then a summary line. Default: none; agent + mode: failures. + -h, --help Show this message and exit. +``` + +#### `dittoctl things array remove` + +```text +Usage: dittoctl things array remove [OPTIONS] PATH [THING_ID]... + + Remove every occurrence of the --items from the array at PATH of each selected thing. + + Each array is read with its ETag and written with If-Match, so concurrent changes are never lost; + things whose array wouldn't change aren't written. + + Example: + dittoctl things array remove attributes/tags --items '["maintenance"]' -f 'eq(attributes/building,"B1")' + +Options: + --items JSON|@FILE A JSON array of the items. [required] + --compare [deep|json] Item equality: 'deep' (1 equals 1.0) or 'json' (canonical text). + [default: deep] + --conflict-retries INTEGER RANGE + How often to re-read and retry when the array was changed + concurrently. [default: 3; x>=0] + --ids-file FILE Thing ids, one per line (first column); - reads stdin. + -f, --filter RQL Select by RQL filter; @file reads it. + --no-validate Send the filter without checking it locally first. + -n, --namespaces NS[,NS] Namespaces for --filter. + --include-file FILE Only things whose id is also in this file. + --exclude-file FILE Leave out things whose id is in this file. + --dry-run Show what would be sent, without writing anything. + -y, --yes Don't ask; required above --max-affected things. + --max-affected INTEGER RANGE Above this many things, --yes is required. [default: 100; x>=0] + --confirm-context NAME Confirm a protected context without the prompt (for scripts). + --concurrency INTEGER RANGE Requests in flight at the same time. [default: 8; 1<=x<=64] + --rate N At most N requests per second. + --journal FILE Record finished things here, to --resume later. + --resume Skip the things already recorded in --journal. + --failed-out FILE Write failed things here (usable as --ids-file to retry them). + --results [none|failures|all] Print a JSON line per thing on stdout: 'failures' (with Ditto's + error and its description; in a dry run, the first planned + requests) or 'all', then a summary line. Default: none; agent + mode: failures. + -h, --help Show this message and exit. +``` + +#### `dittoctl things count` + +```text +Usage: dittoctl things count [OPTIONS] + + Count the things matching an RQL filter. + +Options: + -f, --filter RQL RQL filter; @file reads it from a file. + --no-validate Send the filter as is, without checking it locally first. + -n, --namespaces NS[,NS] Namespaces to search in (default: the context's namespaces, else all). + Repeatable. + -h, --help Show this message and exit. +``` + +#### `dittoctl things create` + +```text +Usage: dittoctl things create [OPTIONS] [THING_ID] + + Create a thing; fails if it already exists. Without THING_ID, Ditto generates the id. + + Examples: + dittoctl things create org.example:sensor-1 -d '{"attributes":{"room":"lab"}}' + dittoctl things create org.example:lamp-1 --definition https://example.org/models/lamp-1.0.0.tm.jsonld + +Options: + -d, --data JSON|@FILE|@- The thing JSON (attributes, features, ...). + --definition URL|NS:NAME:VERSION + Thing definition; a WoT Thing Model URL makes Ditto generate the + thing's skeleton. + --policy-id TEXT Use this existing policy instead of a new one. + --confirm-context NAME Confirm a protected context without the prompt (for scripts). + -h, --help Show this message and exit. +``` + +#### `dittoctl things delete` + +```text +Usage: dittoctl things delete [OPTIONS] [THING_ID]... + + Delete the selected things. Their policies are kept. + + Examples: + dittoctl things delete org.example:sensor-1 + dittoctl things delete -f 'eq(attributes/decommissioned,true)' --dry-run + +Options: + --ids-file FILE Thing ids, one per line (first column); - reads stdin. + -f, --filter RQL Select by RQL filter; @file reads it. + --no-validate Send the filter without checking it locally first. + -n, --namespaces NS[,NS] Namespaces for --filter. + --include-file FILE Only things whose id is also in this file. + --exclude-file FILE Leave out things whose id is in this file. + --if-match ETAG|* Only apply if the entity has this ETag (e.g. rev:5); '*' requires + that it exists. + --if-none-match ETAG|* '*' only creates and never overwrites; with an ETag on reads, + Ditto answers 304 if unchanged. + --if-equal [update|skip|skip-minimizing-merge] + What Ditto does if the new value equals the current one; 'skip' + avoids no-op events. + --condition RQL Only apply if the entity matches this RQL condition. + --patch-condition PATH=RQL Per-path condition for merge requests (Ditto 3.8+). Repeatable. + --live-condition RQL Route retrieves to the live channel if this matches. + --live-timeout-strategy [fail|use-twin] + What to do if the device doesn't answer a live request in time. + --dry-run Show what would be sent, without writing anything. + -y, --yes Don't ask; required above --max-affected things. + --max-affected INTEGER RANGE Above this many things, --yes is required. [default: 100; x>=0] + --confirm-context NAME Confirm a protected context without the prompt (for scripts). + --concurrency INTEGER RANGE Requests in flight at the same time. [default: 8; 1<=x<=64] + --rate N At most N requests per second. + --journal FILE Record finished things here, to --resume later. + --resume Skip the things already recorded in --journal. + --failed-out FILE Write failed things here (usable as --ids-file to retry them). + --results [none|failures|all] Print a JSON line per thing on stdout: 'failures' (with Ditto's + error and its description; in a dry run, the first planned + requests) or 'all', then a summary line. Default: none; agent + mode: failures. + -h, --help Show this message and exit. +``` + +#### `dittoctl things diff` + +```text +Usage: dittoctl things diff [OPTIONS] THING_ID + + Show the differences between a local JSON file and the thing in Ditto (exit code 6 if they + differ). + +Options: + --file FILE|- Local JSON to compare with. [required] + --path TEXT Compare only this part of the thing. + -o, --output [text|json] Output format: a unified diff, or a JSON list of {"op", "path", "old", + "new"} with op add, remove or replace and old being the value in Ditto + (default: text; agent mode: json). + -h, --help Show this message and exit. +``` + +#### `dittoctl things edit` + +```text +Usage: dittoctl things edit [OPTIONS] THING_ID + + Edit a thing in $EDITOR; the changes are sent as a merge patch with If-Match. + + If the thing was changed by someone else in the meantime, nothing is written. + +Options: + --path TEXT Only edit this part, e.g. attributes. + --confirm-context NAME Confirm a protected context without the prompt (for scripts). + -h, --help Show this message and exit. +``` + +#### `dittoctl things export` + +```text +Usage: dittoctl things export [OPTIONS] + + Export search results to a file, streaming: memory use stays flat regardless of the number of + things. + + Examples: + dittoctl things export -f 'exists(features/temp)' --fields thingId,features/temp/properties --out temp.csv + dittoctl things export -n org.example -o ndjson --out backup.ndjson + +Options: + -f, --filter RQL RQL filter; @file reads it from a file. + --no-validate Send the filter as is, without checking it locally first. + -n, --namespaces NS[,NS] Namespaces to search in (default: the context's namespaces, else + all). Repeatable. + --fields TEXT Field selector, e.g. thingId,attributes,features/temp/properties. + --sort [+-]PATH[,...] Sort order, e.g. +thingId. + --limit INTEGER RANGE Stop after this many things. [x>=1] + -o, --output [csv|ndjson|json|ids] + Output format. [default: csv] + --no-progress Don't count the things first or show progress. + --all Don't limit the output (agent mode shows the first 50 by default). + --transport [auto|paging|sse] How results are fetched: 'paging' through the search cursor, or + Ditto's SSE search 'sse' stream. 'auto' streams when only thing + ids are needed (-o ids) and the context allows it, else it pages. + [default: auto] + --columns PATH[,PATH] Fixed columns (paths like attributes/location). + --discover-rows INTEGER Rows to inspect for column discovery; 0 inspects all (buffers the + whole result). [default: 100] + --short-headers Use the shortest unambiguous path suffix as header. + --delimiter TEXT CSV delimiter. [default: ,] + --no-header Leave out the CSV header row. + --excel CSV for Excel: UTF-8 BOM, timestamps as 'YYYY-MM-DD HH:MM:SS' + (UTC). + --out FILE Write to this file instead of stdout. + -h, --help Show this message and exit. +``` + +#### `dittoctl things fields` + +```text +Usage: dittoctl things fields [OPTIONS] + + Show which paths the matching things have, with JSON types, frequency and example values. + + Ditto things are schemaless: this shows what to filter on (RQL) and which fields to select, also + for things without a WoT model (for those, see 'things td'). Each line has path, types, count, + share (of the inspected things) and examples. + + Examples: + dittoctl things fields -n org.example + dittoctl things fields -f 'eq(attributes/model,"X1")' --path features --sample 500 + +Options: + -f, --filter RQL RQL filter; @file reads it from a file. + --no-validate Send the filter as is, without checking it locally first. + -n, --namespaces NS[,NS] Namespaces to search in (default: the context's namespaces, else + all). Repeatable. + --sample INTEGER RANGE How many matching things to inspect: the first ones Ditto returns, + not a random sample. [default: 100; 1<=x<=10000] + --path PATH Only paths below this one, e.g. attributes or features/temp. + --examples INTEGER RANGE Distinct example values per path. [default: 3; 0<=x<=20] + -o, --output [table|json|ndjson|csv] + Output format (default: table on a terminal, ndjson otherwise). + -h, --help Show this message and exit. +``` + +#### `dittoctl things get` + +```text +Usage: dittoctl things get [OPTIONS] THING_ID... + + Retrieve one or more things. + + Examples: + dittoctl things get org.example:sensor-1 + dittoctl things get org.example:sensor-1 --path attributes/location + dittoctl things get org.example:sensor-1 --at-revision 42 + dittoctl things get org.example:sensor-1 org.example:sensor-2 --fields thingId,attributes -o table + +Options: + --path TEXT Only this part of the thing, e.g. attributes/location or + features/temp/properties. + --fields TEXT Field selector, e.g. + thingId,attributes/location,features/temp/properties/value. + --at-revision INTEGER Read the thing as it was at this revision (needs Ditto history). + --at-time TIMESTAMP Read the thing as it was at this ISO-8601 time. + --live Ask the device (live channel) instead of the twin; see --live- + condition, --live-timeout-strategy. + --live-timeout SECONDS With --live: how long to wait for the device (Ditto's default: + 10s). [1<=x<=60] + -o, --output [json|table|ndjson|csv] + Output format. [default: json] + --if-match ETAG|* Only apply if the entity has this ETag (e.g. rev:5); '*' requires + that it exists. + --if-none-match ETAG|* '*' only creates and never overwrites; with an ETag on reads, + Ditto answers 304 if unchanged. + --if-equal [update|skip|skip-minimizing-merge] + What Ditto does if the new value equals the current one; 'skip' + avoids no-op events. + --condition RQL Only apply if the entity matches this RQL condition. + --patch-condition PATH=RQL Per-path condition for merge requests (Ditto 3.8+). Repeatable. + --live-condition RQL Route retrieves to the live channel if this matches. + --live-timeout-strategy [fail|use-twin] + What to do if the device doesn't answer a live request in time. + -h, --help Show this message and exit. +``` + +#### `dittoctl things history` + +```text +Usage: dittoctl things history [OPTIONS] THING_ID + + Show the changes of a thing per revision as NDJSON, oldest first (needs history retention in + Ditto). + + Each line has the changed parts only, like 'things watch'; 'things get --at-revision N' shows the + complete thing at a revision. + + Examples: + dittoctl things history org.example:sensor-1 --from-revision -10 + dittoctl things history org.example:sensor-1 --from-time 2026-11-01T00:00:00Z --to-time 2026-11-02T00:00:00Z + +Options: + --from-revision INTEGER First revision; negative counts back from the current one. + --to-revision INTEGER Last revision; 0 is the current one, negative counts back. + --from-time TIMESTAMP First point in time (ISO-8601). + --to-time TIMESTAMP Last point in time (ISO-8601). + --fields TEXT Fields of each change; add _context for the command that caused it. + [default: thingId,_revision,_modified,attributes,features] + -f, --filter RQL Only states matching this filter. + --limit INTEGER RANGE Stop after this many changes. [x>=1] + --all Don't limit the output (agent mode shows the first 50 by default). + -h, --help Show this message and exit. +``` + +#### `dittoctl things import` + +```text +Usage: dittoctl things import [OPTIONS] FILE|- + + Create (or replace) things from NDJSON or a JSON array, such as a 'things export -o ndjson'. + + Each thing needs a thingId. Importing again is safe: existing things are reported as 'exists' + (create) or left alone when unchanged (upsert). + + Examples: + dittoctl things export -n org.example -o ndjson --out backup.ndjson + dittoctl --context staging things import backup.ndjson --yes + +Options: + --mode [create|upsert] 'create' only creates things that don't exist; 'upsert' also + replaces existing ones. [default: create] + --dry-run Show what would be sent, without writing anything. + -y, --yes Don't ask; required above --max-affected things. + --max-affected INTEGER RANGE Above this many things, --yes is required. [default: 100; x>=0] + --confirm-context NAME Confirm a protected context without the prompt (for scripts). + --concurrency INTEGER RANGE Requests in flight at the same time. [default: 8; 1<=x<=64] + --rate N At most N requests per second. + --journal FILE Record finished things here, to --resume later. + --resume Skip the things already recorded in --journal. + --failed-out FILE Write failed things here (usable as --ids-file to retry them). + --results [none|failures|all] Print a JSON line per thing on stdout: 'failures' (with Ditto's + error and its description; in a dry run, the first planned + requests) or 'all', then a summary line. Default: none; agent mode: + failures. + -h, --help Show this message and exit. +``` + +#### `dittoctl things migrate-definition` + +```text +Usage: dittoctl things migrate-definition [OPTIONS] [THING_ID]... + + Move each selected thing to a new thing definition (Thing Model version), optionally updating it. + + --dry-run lets Ditto compute the result without applying it (Ditto 3.7+). + + Example: + dittoctl things migrate-definition --definition https://models.example.org/sensor-2.0.0.tm.jsonld \ + --init-defaults -f 'eq(definition,"https://models.example.org/sensor-1.0.0.tm.jsonld")' --dry-run + +Options: + --definition TM_URL URL of the new WoT Thing Model. [required] + --payload JSON|@FILE Attributes/features to merge, may use {{ thing-json:... }}. + --patch-condition PATH=RQL Only merge the payload at PATH if the RQL matches, e.g. + features/temp=not(exists(features/temp)). + --init-defaults Initialize missing properties from the model's defaults. + --ids-file FILE Thing ids, one per line (first column); - reads stdin. + -f, --filter RQL Select by RQL filter; @file reads it. + --no-validate Send the filter without checking it locally first. + -n, --namespaces NS[,NS] Namespaces for --filter. + --include-file FILE Only things whose id is also in this file. + --exclude-file FILE Leave out things whose id is in this file. + --dry-run Show what would be sent, without writing anything. + -y, --yes Don't ask; required above --max-affected things. + --max-affected INTEGER RANGE Above this many things, --yes is required. [default: 100; x>=0] + --confirm-context NAME Confirm a protected context without the prompt (for scripts). + --concurrency INTEGER RANGE Requests in flight at the same time. [default: 8; 1<=x<=64] + --rate N At most N requests per second. + --journal FILE Record finished things here, to --resume later. + --resume Skip the things already recorded in --journal. + --failed-out FILE Write failed things here (usable as --ids-file to retry them). + --results [none|failures|all] Print a JSON line per thing on stdout: 'failures' (with Ditto's + error and its description; in a dry run, the first planned + requests) or 'all', then a summary line. Default: none; agent mode: + failures. + -h, --help Show this message and exit. +``` + +#### `dittoctl things patch` + +```text +Usage: dittoctl things patch [OPTIONS] PATH [THING_ID]... + + Merge-patch (RFC 7396) a part of each selected thing; PATH '/' patches the whole thing. + + Unchanged values are skipped (--if-equal skip) unless --if-equal update is given. Things that + don't exist are reported as not-found; they are never created. + + Examples: + dittoctl things patch attributes/location -d '{"room":"lab"}' org.example:sensor-1 + dittoctl things patch / -d @patch.json -f 'eq(attributes/model,"X1")' --dry-run + dittoctl things search -f 'exists(features/temp)' -o ids | dittoctl things patch features/temp/properties \ + -d '{"unit":"°C"}' --ids-file - --yes + +Options: + -d, --data JSON|@FILE|@- The merge patch to apply. [required] + --replace-array Allow arrays in the patch (they replace the whole array). + --ids-file FILE Thing ids, one per line (first column); - reads stdin. + -f, --filter RQL Select by RQL filter; @file reads it. + --no-validate Send the filter without checking it locally first. + -n, --namespaces NS[,NS] Namespaces for --filter. + --include-file FILE Only things whose id is also in this file. + --exclude-file FILE Leave out things whose id is in this file. + --if-match ETAG|* Only apply if the entity has this ETag (e.g. rev:5); '*' requires + that it exists. + --if-none-match ETAG|* '*' only creates and never overwrites; with an ETag on reads, + Ditto answers 304 if unchanged. + --if-equal [update|skip|skip-minimizing-merge] + What Ditto does if the new value equals the current one; 'skip' + avoids no-op events. + --condition RQL Only apply if the entity matches this RQL condition. + --patch-condition PATH=RQL Per-path condition for merge requests (Ditto 3.8+). Repeatable. + --live-condition RQL Route retrieves to the live channel if this matches. + --live-timeout-strategy [fail|use-twin] + What to do if the device doesn't answer a live request in time. + --dry-run Show what would be sent, without writing anything. + -y, --yes Don't ask; required above --max-affected things. + --max-affected INTEGER RANGE Above this many things, --yes is required. [default: 100; x>=0] + --confirm-context NAME Confirm a protected context without the prompt (for scripts). + --concurrency INTEGER RANGE Requests in flight at the same time. [default: 8; 1<=x<=64] + --rate N At most N requests per second. + --journal FILE Record finished things here, to --resume later. + --resume Skip the things already recorded in --journal. + --failed-out FILE Write failed things here (usable as --ids-file to retry them). + --results [none|failures|all] Print a JSON line per thing on stdout: 'failures' (with Ditto's + error and its description; in a dry run, the first planned + requests) or 'all', then a summary line. Default: none; agent + mode: failures. + -h, --help Show this message and exit. +``` + +#### `dittoctl things put` + +```text +Usage: dittoctl things put [OPTIONS] THING_ID + + Create or completely replace a thing. + + Example: + dittoctl things put org.example:sensor-1 -d @sensor-1.json --if-match rev:7 + +Options: + -d, --data JSON|@FILE|@- The complete thing JSON. [required] + --if-match ETAG|* Only apply if the entity has this ETag (e.g. rev:5); '*' requires + that it exists. + --if-none-match ETAG|* '*' only creates and never overwrites; with an ETag on reads, + Ditto answers 304 if unchanged. + --if-equal [update|skip|skip-minimizing-merge] + What Ditto does if the new value equals the current one; 'skip' + avoids no-op events. + --condition RQL Only apply if the entity matches this RQL condition. + --patch-condition PATH=RQL Per-path condition for merge requests (Ditto 3.8+). Repeatable. + --live-condition RQL Route retrieves to the live channel if this matches. + --live-timeout-strategy [fail|use-twin] + What to do if the device doesn't answer a live request in time. + --confirm-context NAME Confirm a protected context without the prompt (for scripts). + -h, --help Show this message and exit. +``` + +#### `dittoctl things search` + +```text +Usage: dittoctl things search [OPTIONS] + + Search things with RQL, following the result cursor through all pages. + + Examples: + dittoctl things search -f 'eq(attributes/manufacturer,"ACME")' --fields thingId,attributes + dittoctl things search -f 'gt(_modified,"2026-11-01T00:00:00Z")' --sort -_modified --limit 20 + dittoctl things search -n org.example -o ids > ids.txt + +Options: + -f, --filter RQL RQL filter; @file reads it from a file. + --no-validate Send the filter as is, without checking it locally first. + -n, --namespaces NS[,NS] Namespaces to search in (default: the context's namespaces, else + all). Repeatable. + --fields TEXT Field selector, e.g. thingId,attributes/location,_modified. + --sort [+-]PATH[,...] Sort order, e.g. -_modified or +attributes/name. + --limit INTEGER RANGE Stop after this many things. [x>=1] + --page-size INTEGER RANGE Things per request. [default: 200; 1<=x<=200] + -o, --output [table|json|ndjson|csv|ids] + Output format (default: table on a terminal, ndjson otherwise). + --all Don't limit the output (agent mode shows the first 50 by default). + --transport [auto|paging|sse] How results are fetched: 'paging' through the search cursor, or + Ditto's SSE search 'sse' stream. 'auto' streams when only thing + ids are needed (-o ids) and the context allows it, else it pages. + [default: auto] + --columns PATH[,PATH] Fixed columns (paths like attributes/location). + --discover-rows INTEGER Rows to inspect for column discovery; 0 inspects all (buffers the + whole result). [default: 100] + --short-headers Use the shortest unambiguous path suffix as header. + --delimiter TEXT CSV delimiter. [default: ,] + --no-header Leave out the CSV header row. + --excel CSV for Excel: UTF-8 BOM, timestamps as 'YYYY-MM-DD HH:MM:SS' + (UTC). + --out FILE Write to this file instead of stdout. + -h, --help Show this message and exit. +``` + +#### `dittoctl things set` + +```text +Usage: dittoctl things set [OPTIONS] PATH VALUE [THING_ID]... + + Set the value at PATH of each selected thing, creating missing parents. + + VALUE is parsed as JSON if possible (42, true, {"a":1}), otherwise taken as a string. Things that + don't exist are reported as not-found; they are never created. + + Examples: + dittoctl things set attributes/location/room lab org.example:sensor-1 + dittoctl things set features/config/properties/interval 60 -f 'eq(attributes/model,"X1")' + +Options: + --string Treat VALUE as a string even if it is valid JSON. + --ids-file FILE Thing ids, one per line (first column); - reads stdin. + -f, --filter RQL Select by RQL filter; @file reads it. + --no-validate Send the filter without checking it locally first. + -n, --namespaces NS[,NS] Namespaces for --filter. + --include-file FILE Only things whose id is also in this file. + --exclude-file FILE Leave out things whose id is in this file. + --if-match ETAG|* Only apply if the entity has this ETag (e.g. rev:5); '*' requires + that it exists. + --if-none-match ETAG|* '*' only creates and never overwrites; with an ETag on reads, + Ditto answers 304 if unchanged. + --if-equal [update|skip|skip-minimizing-merge] + What Ditto does if the new value equals the current one; 'skip' + avoids no-op events. + --condition RQL Only apply if the entity matches this RQL condition. + --patch-condition PATH=RQL Per-path condition for merge requests (Ditto 3.8+). Repeatable. + --live-condition RQL Route retrieves to the live channel if this matches. + --live-timeout-strategy [fail|use-twin] + What to do if the device doesn't answer a live request in time. + --dry-run Show what would be sent, without writing anything. + -y, --yes Don't ask; required above --max-affected things. + --max-affected INTEGER RANGE Above this many things, --yes is required. [default: 100; x>=0] + --confirm-context NAME Confirm a protected context without the prompt (for scripts). + --concurrency INTEGER RANGE Requests in flight at the same time. [default: 8; 1<=x<=64] + --rate N At most N requests per second. + --journal FILE Record finished things here, to --resume later. + --resume Skip the things already recorded in --journal. + --failed-out FILE Write failed things here (usable as --ids-file to retry them). + --results [none|failures|all] Print a JSON line per thing on stdout: 'failures' (with Ditto's + error and its description; in a dry run, the first planned + requests) or 'all', then a summary line. Default: none; agent + mode: failures. + -h, --help Show this message and exit. +``` + +#### `dittoctl things td` + +```text +Usage: dittoctl things td [OPTIONS] THING_ID + + Show the WoT Thing Description Ditto generates from the thing's definition (a Thing Model URL). + + --compact leaves out what follows from Ditto's conventions (forms, security, error schemas) and + lists repeated parts once, which makes the description 2 to 12 times smaller, e.g. for an LLM. + Paths are relative to the thing, or to features/ for a feature's properties, actions and + events. A feature described exactly like an earlier one is shown as {"sameAs": ""}, a + repeated data schema as {"$ref": "#/"}. + + Examples: + dittoctl things td org.example:lamp-1 + dittoctl things td org.example:lamp-1 --feature Spot1 + dittoctl things td org.example:lamp-1 --with-features --compact + +Options: + --feature TEXT The Thing Description of this feature instead. + --with-features Add the Thing Descriptions of all the thing's features, under + 'features'. + --compact Only titles, descriptions, data schemas and the path of each property, + action and event; single-line JSON when piped. + --no-schema-descriptions With --compact: leave out the descriptions inside data schemas (those of + properties, actions and events stay). + -h, --help Show this message and exit. +``` + +#### `dittoctl things unset` + +```text +Usage: dittoctl things unset [OPTIONS] PATH [THING_ID]... + + Remove the value at PATH of each selected thing (absent values are fine, absent things are not- + found). + + Example: + dittoctl things unset attributes/obsolete -f 'exists(attributes/obsolete)' + +Options: + --ids-file FILE Thing ids, one per line (first column); - reads stdin. + -f, --filter RQL Select by RQL filter; @file reads it. + --no-validate Send the filter without checking it locally first. + -n, --namespaces NS[,NS] Namespaces for --filter. + --include-file FILE Only things whose id is also in this file. + --exclude-file FILE Leave out things whose id is in this file. + --if-match ETAG|* Only apply if the entity has this ETag (e.g. rev:5); '*' requires + that it exists. + --if-none-match ETAG|* '*' only creates and never overwrites; with an ETag on reads, + Ditto answers 304 if unchanged. + --if-equal [update|skip|skip-minimizing-merge] + What Ditto does if the new value equals the current one; 'skip' + avoids no-op events. + --condition RQL Only apply if the entity matches this RQL condition. + --patch-condition PATH=RQL Per-path condition for merge requests (Ditto 3.8+). Repeatable. + --live-condition RQL Route retrieves to the live channel if this matches. + --live-timeout-strategy [fail|use-twin] + What to do if the device doesn't answer a live request in time. + --dry-run Show what would be sent, without writing anything. + -y, --yes Don't ask; required above --max-affected things. + --max-affected INTEGER RANGE Above this many things, --yes is required. [default: 100; x>=0] + --confirm-context NAME Confirm a protected context without the prompt (for scripts). + --concurrency INTEGER RANGE Requests in flight at the same time. [default: 8; 1<=x<=64] + --rate N At most N requests per second. + --journal FILE Record finished things here, to --resume later. + --resume Skip the things already recorded in --journal. + --failed-out FILE Write failed things here (usable as --ids-file to retry them). + --results [none|failures|all] Print a JSON line per thing on stdout: 'failures' (with Ditto's + error and its description; in a dry run, the first planned + requests) or 'all', then a summary line. Default: none; agent + mode: failures. + -h, --help Show this message and exit. +``` + +#### `dittoctl things verify` + +```text +Usage: dittoctl things verify [OPTIONS] PATH [THING_ID]... + + Check that PATH has the expected value in each selected thing, for example after a bulk change. + + Prints the things that don't match as NDJSON and exits with code 6 if there are any. + + Example: + dittoctl things verify features/config/properties/interval --equals 60 -f 'eq(attributes/model,"X1")' + +Options: + --equals JSON|@FILE The expected value at PATH. [required] + --compare [deep|json] Value equality: 'deep' (1 equals 1.0) or 'json' (canonical text). + [default: deep] + --failed-out FILE Write the things that don't match here (usable as --ids-file). + --ids-file FILE Thing ids, one per line (first column); - reads stdin. + -f, --filter RQL Select by RQL filter; @file reads it. + --no-validate Send the filter without checking it locally first. + -n, --namespaces NS[,NS] Namespaces for --filter. + --include-file FILE Only things whose id is also in this file. + --exclude-file FILE Leave out things whose id is in this file. + -h, --help Show this message and exit. +``` + +#### `dittoctl things watch` + +```text +Usage: dittoctl things watch [OPTIONS] + + Follow thing changes as they happen, one JSON object per line. Stop with Ctrl+C, --duration or + --max-events. + + Examples: + dittoctl things watch -n org.example + dittoctl things watch -f 'exists(features/temp)' --fields thingId,features/temp/properties/value + dittoctl things watch --ids org.example:sensor-1 --max-events 1 --duration 2m + +Options: + -f, --filter RQL RQL filter; @file reads it from a file. + --no-validate Send the filter as is, without checking it locally first. + -n, --namespaces NS[,NS] Namespaces to search in (default: the context's namespaces, else all). + Repeatable. + --ids ID[,ID] Only these things. + --fields TEXT Fields of each change to show (default: the changed parts). + --extra-fields TEXT Unchanged fields to add to each change, e.g. attributes/location. + --duration DURATION Stop watching after this long, e.g. 30s or 5m; 0 never stops (default; + agent mode: 30s). + --max-events INTEGER RANGE Stop after this many changes. [x>=1] + -h, --help Show this message and exit. +``` + +### `dittoctl whoami` + +```text +Usage: dittoctl whoami [OPTIONS] + + Show the subjects Ditto derives from your credentials. + +Options: + -o, --output [json|text] Output format. [default: text] + -h, --help Show this message and exit. +``` + +### `dittoctl wot` + +```text +Usage: dittoctl wot [OPTIONS] COMMAND [ARGS]... + + Web of Things (WoT): Ditto's Thing Directory. See also 'things td' and 'things migrate- + definition'. + +Options: + -h, --help Show this message and exit. + +Commands: + directory Show Ditto's WoT Thing Directory description (/.well-known/wot, Ditto 3.9+). +``` + +#### `dittoctl wot directory` + +```text +Usage: dittoctl wot directory [OPTIONS] + + Show Ditto's WoT Thing Directory description (/.well-known/wot, Ditto 3.9+). + +Options: + -h, --help Show this message and exit. +``` diff --git a/legal/CC0-1.0.txt b/legal/CC0-1.0.txt new file mode 100644 index 0000000..0e259d4 --- /dev/null +++ b/legal/CC0-1.0.txt @@ -0,0 +1,121 @@ +Creative Commons Legal Code + +CC0 1.0 Universal + + CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE + LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN + ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS + INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES + REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS + PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM + THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED + HEREUNDER. + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator +and subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for +the purpose of contributing to a commons of creative, cultural and +scientific works ("Commons") that the public can reliably and without fear +of later claims of infringement build upon, modify, incorporate in other +works, reuse and redistribute as freely as possible in any form whatsoever +and for any purposes, including without limitation commercial purposes. +These owners may contribute to the Commons to promote the ideal of a free +culture and the further production of creative, cultural and scientific +works, or to gain reputation or greater distribution for their Work in +part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any +expectation of additional consideration or compensation, the person +associating CC0 with a Work (the "Affirmer"), to the extent that he or she +is an owner of Copyright and Related Rights in the Work, voluntarily +elects to apply CC0 to the Work and publicly distribute the Work under its +terms, with knowledge of his or her Copyright and Related Rights in the +Work and the meaning and intended legal effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not +limited to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, + communicate, and translate a Work; + ii. moral rights retained by the original author(s) and/or performer(s); +iii. publicity and privacy rights pertaining to a person's image or + likeness depicted in a Work; + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + v. rights protecting the extraction, dissemination, use and reuse of data + in a Work; + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation + thereof, including any amended or successor version of such + directive); and +vii. other similar, equivalent or corresponding rights throughout the + world based on applicable law or treaty, and any national + implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention +of, applicable law, Affirmer hereby overtly, fully, permanently, +irrevocably and unconditionally waives, abandons, and surrenders all of +Affirmer's Copyright and Related Rights and associated claims and causes +of action, whether now known or unknown (including existing as well as +future claims and causes of action), in the Work (i) in all territories +worldwide, (ii) for the maximum duration provided by applicable law or +treaty (including future time extensions), (iii) in any current or future +medium and for any number of copies, and (iv) for any purpose whatsoever, +including without limitation commercial, advertising or promotional +purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each +member of the public at large and to the detriment of Affirmer's heirs and +successors, fully intending that such Waiver shall not be subject to +revocation, rescission, cancellation, termination, or any other legal or +equitable action to disrupt the quiet enjoyment of the Work by the public +as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason +be judged legally invalid or ineffective under applicable law, then the +Waiver shall be preserved to the maximum extent permitted taking into +account Affirmer's express Statement of Purpose. In addition, to the +extent the Waiver is so judged Affirmer hereby grants to each affected +person a royalty-free, non transferable, non sublicensable, non exclusive, +irrevocable and unconditional license to exercise Affirmer's Copyright and +Related Rights in the Work (i) in all territories worldwide, (ii) for the +maximum duration provided by applicable law or treaty (including future +time extensions), (iii) in any current or future medium and for any number +of copies, and (iv) for any purpose whatsoever, including without +limitation commercial, advertising or promotional purposes (the +"License"). The License shall be deemed effective as of the date CC0 was +applied by Affirmer to the Work. Should any part of the License for any +reason be judged legally invalid or ineffective under applicable law, such +partial invalidity or ineffectiveness shall not invalidate the remainder +of the License, and in such case Affirmer hereby affirms that he or she +will not (i) exercise any of his or her remaining Copyright and Related +Rights in the Work or (ii) assert any associated claims and causes of +action with respect to the Work, in either case contrary to Affirmer's +express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + b. Affirmer offers the Work as-is and makes no representations or + warranties of any kind concerning the Work, express, implied, + statutory or otherwise, including without limitation warranties of + title, merchantability, fitness for a particular purpose, non + infringement, or the absence of latent or other defects, accuracy, or + the present or absence of errors, whether or not discoverable, all to + the greatest extent permissible under applicable law. + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without + limitation any person's Copyright and Related Rights in the Work. + Further, Affirmer disclaims responsibility for obtaining any necessary + consents, permissions or other rights required for any use of the + Work. + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to + this CC0 or use of the Work. diff --git a/legal/NOTICE-THIRD-PARTY.md b/legal/NOTICE-THIRD-PARTY.md new file mode 100644 index 0000000..476eceb --- /dev/null +++ b/legal/NOTICE-THIRD-PARTY.md @@ -0,0 +1,140 @@ +# Third-party Content + +dittoctl is distributed as a Python package without bundled dependencies: the packages below are installed +from PyPI next to it. Versions are the ones dittoctl is currently tested with; `pyproject.toml` declares the +accepted ranges of the direct dependencies. + +## click (8.5.0) + +* PyPI: `click==8.5.0` +* License: [BSD-3-Clause](https://spdx.org/licenses/BSD-3-Clause.html) +* Project: https://palletsprojects.com/p/click/ +* Sources: https://github.com/pallets/click + +## httpx (0.28.1) + +* PyPI: `httpx==0.28.1` +* License: [BSD-3-Clause](https://spdx.org/licenses/BSD-3-Clause.html) +* Project: https://www.python-httpx.org/ +* Sources: https://github.com/encode/httpx + +## httpcore (1.0.9) + +* PyPI: `httpcore==1.0.9` +* License: [BSD-3-Clause](https://spdx.org/licenses/BSD-3-Clause.html) +* Project: https://www.encode.io/httpcore/ +* Sources: https://github.com/encode/httpcore + +## h11 (0.16.0) + +* PyPI: `h11==0.16.0` +* License: [MIT](https://spdx.org/licenses/MIT.html) +* Sources: https://github.com/python-hyper/h11 + +## anyio (4.16.0) + +* PyPI: `anyio==4.16.0` +* License: [MIT](https://spdx.org/licenses/MIT.html) +* Project: https://anyio.readthedocs.io/ +* Sources: https://github.com/agronholm/anyio + +## idna (3.20) + +* PyPI: `idna==3.20` +* License: [BSD-3-Clause](https://spdx.org/licenses/BSD-3-Clause.html) +* Sources: https://github.com/kjd/idna + +## certifi (2026.10.23) + +* PyPI: `certifi==2026.10.23` +* License: [MPL-2.0](https://spdx.org/licenses/MPL-2.0.html) +* Sources: https://github.com/certifi/python-certifi + +## keyring (25.7.0) + +* PyPI: `keyring==25.7.0` +* License: [MIT](https://spdx.org/licenses/MIT.html) +* Sources: https://github.com/jaraco/keyring + +## jaraco.classes (3.4.0) + +* PyPI: `jaraco.classes==3.4.0` +* License: [MIT](https://spdx.org/licenses/MIT.html) +* Sources: https://github.com/jaraco/jaraco.classes + +## jaraco.context (6.1.2) + +* PyPI: `jaraco.context==6.1.2` +* License: [MIT](https://spdx.org/licenses/MIT.html) +* Sources: https://github.com/jaraco/jaraco.context + +## jaraco.functools (4.6.0) + +* PyPI: `jaraco.functools==4.6.0` +* License: [MIT](https://spdx.org/licenses/MIT.html) +* Sources: https://github.com/jaraco/jaraco.functools + +## more-itertools (11.2.1) + +* PyPI: `more-itertools==11.2.1` +* License: [MIT](https://spdx.org/licenses/MIT.html) +* Sources: https://github.com/more-itertools/more-itertools + +## rich (15.0.0) + +* PyPI: `rich==15.0.0` +* License: [MIT](https://spdx.org/licenses/MIT.html) +* Project: https://rich.readthedocs.io/ +* Sources: https://github.com/Textualize/rich + +## markdown-it-py (4.2.0) + +* PyPI: `markdown-it-py==4.2.0` +* License: [MIT](https://spdx.org/licenses/MIT.html) +* Sources: https://github.com/executablebooks/markdown-it-py + +## mdurl (0.1.2) + +* PyPI: `mdurl==0.1.2` +* License: [MIT](https://spdx.org/licenses/MIT.html) +* Sources: https://github.com/executablebooks/mdurl + +## Pygments (2.21.0) + +* PyPI: `Pygments==2.21.0` +* License: [BSD-2-Clause](https://spdx.org/licenses/BSD-2-Clause.html) +* Project: https://pygments.org/ +* Sources: https://github.com/pygments/pygments + +## tomli-w (1.2.0) + +* PyPI: `tomli-w==1.2.0` +* License: [MIT](https://spdx.org/licenses/MIT.html) +* Sources: https://github.com/hukkin/tomli-w + +# Platform-specific dependencies + +Installed only on some platforms or Python versions; versions are resolved at install time. + +## Linux: SecretStorage, jeepney, cryptography, cffi, pycparser (keyring backend) + +* SecretStorage: [BSD-3-Clause](https://spdx.org/licenses/BSD-3-Clause.html), https://github.com/mitya57/secretstorage +* jeepney: [MIT](https://spdx.org/licenses/MIT.html), https://gitlab.com/takluyver/jeepney +* cryptography: [Apache-2.0](https://spdx.org/licenses/Apache-2.0.html) OR [BSD-3-Clause](https://spdx.org/licenses/BSD-3-Clause.html), https://github.com/pyca/cryptography +* cffi: [MIT](https://spdx.org/licenses/MIT.html), https://github.com/python-cffi/cffi +* pycparser: [BSD-3-Clause](https://spdx.org/licenses/BSD-3-Clause.html), https://github.com/eliben/pycparser + +## Windows: pywin32-ctypes (keyring backend) + +* License: [BSD-3-Clause](https://spdx.org/licenses/BSD-3-Clause.html) +* Sources: https://github.com/enthought/pywin32-ctypes + +## Python < 3.12: importlib-metadata, zipp (keyring) + +* importlib-metadata: [Apache-2.0](https://spdx.org/licenses/Apache-2.0.html), https://github.com/python/importlib_metadata +* zipp: [MIT](https://spdx.org/licenses/MIT.html), https://github.com/jaraco/zipp + +## Python < 3.13: typing-extensions (anyio) + +* License: [PSF-2.0](https://spdx.org/licenses/PSF-2.0.html) +* Sources: https://github.com/python/typing_extensions diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..be2471b --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,100 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) + +[build-system] +requires = ["hatchling>=1.27"] +build-backend = "hatchling.build" + +[project] +name = "dittoctl" +dynamic = ["version"] +description = "Command line tool for Eclipse Ditto: search, export, bulk modification, messages, policies, connections and DevOps" +readme = "README.md" +requires-python = ">=3.11" +# the AI-generated portions of the code are dedicated to the public domain, see NOTICE.md +license = "EPL-2.0 AND CC0-1.0" +license-files = ["LICENSE", "NOTICE.md", "legal/*"] +authors = [{ name = "Contributors to the Eclipse Foundation" }] +keywords = ["eclipse-ditto", "ditto", "digital-twin", "iot", "cli"] +classifiers = [ + "Development Status :: 2 - Pre-Alpha", + "Environment :: Console", + "Intended Audience :: Developers", + "Intended Audience :: System Administrators", + "Operating System :: OS Independent", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: Only", + "Topic :: Internet :: WWW/HTTP", + "Topic :: System :: Systems Administration", +] +dependencies = [ + "click>=8.1", + "httpx>=0.27", + "keyring>=25", + "rich>=13.7", + "tomli-w>=1.0", +] + +[project.scripts] +dittoctl = "dittoctl.cli.main:main" + +[project.urls] +Homepage = "https://github.com/eclipse-ditto/dittoctl" +Issues = "https://github.com/eclipse-ditto/dittoctl/issues" +Ditto = "https://eclipse.dev/ditto/" + +[dependency-groups] +dev = [ + "build>=1.2", + "pytest>=8", + "respx>=0.21", + "ruff>=0.6", +] + +[tool.hatch.version] +path = "src/dittoctl/__init__.py" + +[tool.hatch.build.targets.wheel] +packages = ["src/dittoctl"] + +[tool.hatch.build.targets.sdist] +# PLAN.md is a local working document and not part of releases +exclude = ["PLAN.md", ".github"] + +[tool.pytest.ini_options] +testpaths = ["tests"] +addopts = "-ra" + +[tool.ruff] +line-length = 120 +target-version = "py311" +src = ["src", "tests"] + +[tool.ruff.lint] +select = ["E", "F", "W", "I", "B", "UP", "SIM", "RUF", "S", "PT"] +ignore = [ + "S101", # assert is fine in tests + "S105", # false positives on token-related names such as use_token = "access" +] + +[tool.ruff.lint.per-file-ignores] +"tests/**" = ["S105", "S106"] + +[tool.pyright] +include = ["src"] +pythonVersion = "3.11" +typeCheckingMode = "basic" diff --git a/scripts/gen_reference.py b/scripts/gen_reference.py new file mode 100644 index 0000000..af9f817 --- /dev/null +++ b/scripts/gen_reference.py @@ -0,0 +1,75 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +"""Generate docs/reference.md from the help texts of all commands. + +python scripts/gen_reference.py # write docs/reference.md +python scripts/gen_reference.py --check # exit 1 if docs/reference.md is outdated +""" + +from __future__ import annotations + +import sys +from pathlib import Path + +import click + +from dittoctl.cli.main import cli + +TARGET = Path(__file__).resolve().parent.parent / "docs" / "reference.md" +HEADER = """# Command reference + +Generated from the commands' help texts by `scripts/gen_reference.py`; don't edit by hand. + +""" + + +def _commands(command: click.Command, path: list[str]) -> list[tuple[list[str], click.Command]]: + found = [(path, command)] + if isinstance(command, click.Group): + for name in sorted(command.commands): + found.extend(_commands(command.commands[name], [*path, name])) + return found + + +def render() -> str: + parts = [HEADER] + for path, command in _commands(cli, ["dittoctl"]): + name = " ".join(path) + with click.Context( + command, info_name=name, terminal_width=100, max_content_width=100, help_option_names=["-h", "--help"] + ) as ctx: + help_text = command.get_help(ctx) + level = "#" * min(len(path) + 1, 4) + parts.append(f"{level} `{name}`\n\n```text\n{help_text}\n```\n\n") + return "".join(parts).rstrip("\n") + "\n" + + +def main() -> int: + text = render() + if "--check" in sys.argv: + if not TARGET.exists() or TARGET.read_text(encoding="utf-8") != text: + print(f"{TARGET} is outdated; run python scripts/gen_reference.py", file=sys.stderr) + return 1 + return 0 + TARGET.parent.mkdir(exist_ok=True) + TARGET.write_text(text, encoding="utf-8") + print(f"wrote {TARGET}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/dittoctl/__init__.py b/src/dittoctl/__init__.py new file mode 100644 index 0000000..107ff25 --- /dev/null +++ b/src/dittoctl/__init__.py @@ -0,0 +1,19 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +"""dittoctl - a command line tool for Eclipse Ditto.""" + +__version__ = "0.1.0.dev0" diff --git a/src/dittoctl/__main__.py b/src/dittoctl/__main__.py new file mode 100644 index 0000000..55aa743 --- /dev/null +++ b/src/dittoctl/__main__.py @@ -0,0 +1,21 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +import sys + +from dittoctl.cli.main import main + +sys.exit(main()) diff --git a/src/dittoctl/auth/__init__.py b/src/dittoctl/auth/__init__.py new file mode 100644 index 0000000..a3ab5fa --- /dev/null +++ b/src/dittoctl/auth/__init__.py @@ -0,0 +1,49 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +"""Authentication against Ditto.""" + +from __future__ import annotations + +from dittoctl.auth.base import AuthProvider, BasicAuth, NoAuth, Notify, PreAuthenticated, StaticToken +from dittoctl.auth.oidc import OidcAuth +from dittoctl.auth.store import SecretStore, default_store +from dittoctl.config import Context + +_PROVIDERS: dict[str, type[AuthProvider]] = { + "none": NoAuth, + "basic": BasicAuth, + "token": StaticToken, + "preauth": PreAuthenticated, + "oidc": OidcAuth, +} + + +def provider_for(context: Context, store: SecretStore | None = None, *, notify: Notify | None = None) -> AuthProvider: + return _PROVIDERS[context.auth.method](context, store or default_store(), notify=notify) + + +__all__ = [ + "AuthProvider", + "BasicAuth", + "NoAuth", + "OidcAuth", + "PreAuthenticated", + "SecretStore", + "StaticToken", + "default_store", + "provider_for", +] diff --git a/src/dittoctl/auth/base.py b/src/dittoctl/auth/base.py new file mode 100644 index 0000000..5b2a926 --- /dev/null +++ b/src/dittoctl/auth/base.py @@ -0,0 +1,165 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +"""Auth providers: turn a context's auth settings into request headers.""" + +from __future__ import annotations + +import base64 +import json +import os +import sys +from collections.abc import Callable +from typing import Any, ClassVar + +from dittoctl.auth.store import SecretStore +from dittoctl.config import Context +from dittoctl.errors import AuthError + +PRE_AUTHENTICATED_HEADER = "x-ditto-pre-authenticated" + +Notify = Callable[[str], None] + + +def _stderr(message: str) -> None: + print(message, file=sys.stderr) + + +def decode_jwt_claims(token: str) -> dict[str, Any] | None: + """Decode the payload of a JWT without verifying it, for display purposes only.""" + parts = token.split(".") + if len(parts) != 3: + return None + payload = parts[1] + "=" * (-len(parts[1]) % 4) + try: + claims = json.loads(base64.urlsafe_b64decode(payload)) + except ValueError: + return None + return claims if isinstance(claims, dict) else None + + +class AuthProvider: + method: ClassVar[str] = "none" + + def __init__(self, context: Context, store: SecretStore, *, notify: Notify | None = None) -> None: + self.context = context + self.store = store + self.notify = notify or _stderr + + def secret_key(self, name: str) -> str: + return f"{self.context.name}/{name}" + + def headers(self) -> dict[str, str]: + """Headers to add to every Ditto request. Raises AuthError if credentials are missing.""" + return {} + + def refresh(self) -> bool: + """Called after a 401. Returns True if new credentials were obtained and the request should be retried.""" + return False + + def login(self, *, secret: str | None = None, open_browser: bool = True) -> None: + """Obtain and store credentials. ``secret`` is the password, token or client secret, depending on method.""" + + def logout(self) -> None: + """Forget stored credentials.""" + + def bearer_token(self) -> str | None: + """The bearer token sent to Ditto, if this method uses one.""" + return None + + def status(self) -> dict[str, Any]: + return {"context": self.context.name, "method": self.method, "authenticated": True} + + +class NoAuth(AuthProvider): + method = "none" + + +class PreAuthenticated(AuthProvider): + """Ditto's pre-authenticated mode: a trusted proxy in front of Ditto sets the subject header.""" + + method = "preauth" + + def headers(self) -> dict[str, str]: + assert self.context.auth.subject + return {PRE_AUTHENTICATED_HEADER: self.context.auth.subject} + + def status(self) -> dict[str, Any]: + return {**super().status(), "subject": self.context.auth.subject} + + +class BasicAuth(AuthProvider): + method = "basic" + + def _password(self) -> str | None: + return os.environ.get("DITTOCTL_PASSWORD") or self.store.get(self.secret_key("password")) + + def headers(self) -> dict[str, str]: + password = self._password() + if password is None: + raise AuthError( + f"no password for context '{self.context.name}'. Run 'dittoctl auth login' or set DITTOCTL_PASSWORD" + ) + raw = f"{self.context.auth.username}:{password}".encode() + return {"Authorization": "Basic " + base64.b64encode(raw).decode("ascii")} + + def login(self, *, secret: str | None = None, open_browser: bool = True) -> None: + if not secret: + raise AuthError("a password is required for basic auth") + self.store.set(self.secret_key("password"), secret) + + def logout(self) -> None: + self.store.delete(self.secret_key("password")) + + def status(self) -> dict[str, Any]: + return { + **super().status(), + "username": self.context.auth.username, + "authenticated": self._password() is not None, + } + + +class StaticToken(AuthProvider): + """A bearer token obtained elsewhere, e.g. from a CI secret.""" + + method = "token" + + def bearer_token(self) -> str | None: + return os.environ.get("DITTOCTL_TOKEN") or self.store.get(self.secret_key("token")) + + def headers(self) -> dict[str, str]: + token = self.bearer_token() + if not token: + raise AuthError( + f"no token for context '{self.context.name}'. " + "Run 'dittoctl auth login --token-stdin' or set DITTOCTL_TOKEN" + ) + return {"Authorization": f"Bearer {token}"} + + def login(self, *, secret: str | None = None, open_browser: bool = True) -> None: + if not secret: + raise AuthError("a token is required for token auth") + self.store.set(self.secret_key("token"), secret) + + def logout(self) -> None: + self.store.delete(self.secret_key("token")) + + def status(self) -> dict[str, Any]: + token = self.bearer_token() + result = {**super().status(), "authenticated": token is not None} + if token and (claims := decode_jwt_claims(token)): + result["claims"] = claims + return result diff --git a/src/dittoctl/auth/oidc.py b/src/dittoctl/auth/oidc.py new file mode 100644 index 0000000..cabde54 --- /dev/null +++ b/src/dittoctl/auth/oidc.py @@ -0,0 +1,404 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +"""OpenID Connect login. + +Supported flows: + +* ``pkce``: authorization code with PKCE (RFC 7636) and a loopback redirect (RFC 8252) +* ``device``: device authorization grant (RFC 8628) +* ``client-credentials``: for machine accounts, the client secret is kept in the secret store + +Endpoints are found via OIDC discovery (``/.well-known/openid-configuration``). +Tokens are kept in the secret store and refreshed with the refresh token when they expire. +""" + +from __future__ import annotations + +import base64 +import hashlib +import html +import json +import secrets +import threading +import time +import webbrowser +from collections.abc import Callable +from dataclasses import asdict, dataclass +from http.server import BaseHTTPRequestHandler, HTTPServer +from typing import Any +from urllib.parse import parse_qs, urlencode, urlparse + +import httpx + +from dittoctl.auth.base import AuthProvider, Notify, decode_jwt_claims +from dittoctl.auth.store import SecretStore +from dittoctl.config import Context +from dittoctl.errors import AuthError + +CALLBACK_PATH = "/callback" +LOGIN_TIMEOUT_SECONDS = 300 +EXPIRY_LEEWAY_SECONDS = 30 +DEVICE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code" + + +def generate_code_verifier() -> str: + # 64 random bytes -> 86 characters of the unreserved alphabet, within the 43..128 range of RFC 7636 + return secrets.token_urlsafe(64) + + +def code_challenge(verifier: str) -> str: + digest = hashlib.sha256(verifier.encode("ascii")).digest() + return base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii") + + +@dataclass +class TokenSet: + access_token: str + issuer: str + client_id: str + id_token: str | None = None + refresh_token: str | None = None + expires_at: float | None = None + + def expired(self, now: float | None = None) -> bool: + if self.expires_at is None: + return False + return (now or time.time()) >= self.expires_at - EXPIRY_LEEWAY_SECONDS + + def to_json(self) -> str: + return json.dumps(asdict(self)) + + @classmethod + def from_json(cls, raw: str) -> TokenSet: + return cls(**json.loads(raw)) + + +class _CallbackServer: + """Loopback HTTP server receiving the authorization response.""" + + def __init__(self, port: int) -> None: + self.result: dict[str, str] | None = None + server = self + + class Handler(BaseHTTPRequestHandler): + def log_message(self, format: str, *args: Any) -> None: + pass + + def do_GET(self) -> None: + url = urlparse(self.path) + if url.path != CALLBACK_PATH: + self.send_error(404) + return + params = {k: v[0] for k, v in parse_qs(url.query).items()} + server.result = params + if "error" in params: + text = f"Login failed: {html.escape(params.get('error_description') or params['error'])}" + else: + text = "Login complete. You can close this window and return to dittoctl." + body = f"dittoctl

{text}

".encode() + self.send_response(200) + self.send_header("Content-Type", "text/html; charset=utf-8") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + self.httpd = HTTPServer(("127.0.0.1", port), Handler) + self.httpd.timeout = 0.5 + self.port = self.httpd.server_address[1] + + @property + def redirect_uri(self) -> str: + return f"http://localhost:{self.port}{CALLBACK_PATH}" + + def wait(self, timeout: float) -> dict[str, str]: + deadline = time.monotonic() + timeout + while self.result is None and time.monotonic() < deadline: + self.httpd.handle_request() + if self.result is None: + raise AuthError(f"no login response received within {int(timeout)} seconds") + return self.result + + def close(self) -> None: + self.httpd.server_close() + + +class OidcAuth(AuthProvider): + method = "oidc" + + def __init__( + self, + context: Context, + store: SecretStore, + *, + notify: Notify | None = None, + http: httpx.Client | None = None, + sleep: Callable[[float], None] = time.sleep, + open_browser: Callable[[str], Any] = webbrowser.open, + ) -> None: + super().__init__(context, store, notify=notify) + self.config = context.auth + assert self.config.issuer + assert self.config.client_id + self.issuer = self.config.issuer.rstrip("/") + self.client_id = self.config.client_id + self.http = http or httpx.Client(timeout=context.timeout, verify=context.verify) + self.sleep = sleep + self.open_browser = open_browser + self._discovery: dict[str, Any] | None = None + self._lock = threading.Lock() + + # --- discovery and token endpoint ------------------------------------------------------- + + def discovery(self) -> dict[str, Any]: + if self._discovery is None: + url = f"{self.issuer}/.well-known/openid-configuration" + try: + response = self.http.get(url) + response.raise_for_status() + self._discovery = response.json() + except (httpx.HTTPError, ValueError) as e: + raise AuthError(f"OIDC discovery failed for {url}: {e}") from e + return self._discovery + + def _endpoint(self, name: str) -> str: + endpoint = self.discovery().get(name) + if not endpoint: + raise AuthError(f"the OIDC provider {self.issuer} does not announce a {name}") + return endpoint + + def _client_secret(self) -> str | None: + return self.store.get(self.secret_key("client-secret")) + + def _client_params(self) -> dict[str, str]: + params = {"client_id": self.client_id} + if secret := self._client_secret(): + params["client_secret"] = secret + return params + + def _token_request(self, data: dict[str, str], previous: TokenSet | None = None) -> TokenSet: + response = self.http.post(self._endpoint("token_endpoint"), data={**data, **self._client_params()}) + try: + body = response.json() + except ValueError: + body = {} + if response.status_code >= 400 or "access_token" not in body: + error = body.get("error_description") or body.get("error") or f"HTTP {response.status_code}" + raise AuthError(f"token request to {self.issuer} failed: {error}") + return self._token_set(body, previous) + + def _token_set(self, body: dict[str, Any], previous: TokenSet | None) -> TokenSet: + expires_at = None + if "expires_in" in body: + expires_at = time.time() + float(body["expires_in"]) + elif claims := decode_jwt_claims(body["access_token"]): + expires_at = claims.get("exp") + return TokenSet( + access_token=body["access_token"], + issuer=self.issuer, + client_id=self.client_id, + id_token=body.get("id_token") or (previous.id_token if previous else None), + # providers that don't rotate refresh tokens omit them from refresh responses + refresh_token=body.get("refresh_token") or (previous.refresh_token if previous else None), + expires_at=expires_at, + ) + + # --- token storage ---------------------------------------------------------------------- + + def _load(self) -> TokenSet | None: + raw = self.store.get(self.secret_key("oidc-tokens")) + if not raw: + return None + try: + tokens = TokenSet.from_json(raw) + except (ValueError, TypeError): + return None + # tokens from a different issuer or client (the context was edited) are not reused + if tokens.issuer != self.issuer or tokens.client_id != self.client_id: + return None + return tokens + + def _save(self, tokens: TokenSet) -> None: + self.store.set(self.secret_key("oidc-tokens"), tokens.to_json()) + + # --- AuthProvider ----------------------------------------------------------------------- + + def _valid_tokens(self, force_refresh: bool = False) -> TokenSet: + with self._lock: + tokens = self._load() + if tokens and not force_refresh and not tokens.expired(): + return tokens + refresh_error = None + if tokens and tokens.refresh_token: + try: + tokens = self._token_request( + {"grant_type": "refresh_token", "refresh_token": tokens.refresh_token}, tokens + ) + self._save(tokens) + return tokens + except AuthError as e: + refresh_error = e # the refresh token may have expired as well + if self.config.flow == "client-credentials" and self._client_secret(): + tokens = self._client_credentials() + self._save(tokens) + return tokens + reason = f" (refreshing the token failed: {refresh_error})" if refresh_error else "" + raise AuthError( + f"not logged in to context '{self.context.name}' or the session expired{reason}. " + f"Run 'dittoctl -c {self.context.name} auth login'" + ) + + def bearer_token(self) -> str | None: + tokens = self._valid_tokens() + if self.config.use_token == "id": + if not tokens.id_token: + raise AuthError("use-token is 'id' but the OIDC provider returned no id token (is 'openid' in scopes?)") + return tokens.id_token + return tokens.access_token + + def headers(self) -> dict[str, str]: + return {"Authorization": f"Bearer {self.bearer_token()}"} + + def refresh(self) -> bool: + try: + self._valid_tokens(force_refresh=True) + return True + except AuthError: + return False + + def login(self, *, secret: str | None = None, open_browser: bool = True) -> None: + if secret: + self.store.set(self.secret_key("client-secret"), secret) + flow = self.config.flow + if flow == "pkce": + tokens = self._pkce_login(open_browser) + elif flow == "device": + tokens = self._device_login() + else: + if not self._client_secret(): + raise AuthError("the client-credentials flow requires a client secret (--secret-stdin)") + tokens = self._client_credentials() + self._save(tokens) + + def logout(self) -> None: + self.store.delete(self.secret_key("oidc-tokens")) + self.store.delete(self.secret_key("client-secret")) + + def status(self) -> dict[str, Any]: + result: dict[str, Any] = { + **super().status(), + "issuer": self.issuer, + "client_id": self.client_id, + "flow": self.config.flow, + } + tokens = self._load() + # without a request to the OIDC provider, a refresh token only promises a new access token + result["authenticated"] = tokens is not None and (not tokens.expired() or tokens.refresh_token is not None) + if tokens: + result["expired"] = tokens.expired() + result["expires_at"] = tokens.expires_at + result["refreshable"] = tokens.refresh_token is not None + token = tokens.id_token if self.config.use_token == "id" else tokens.access_token + if token and (claims := decode_jwt_claims(token)): + result["claims"] = claims + return result + + # --- flows ------------------------------------------------------------------------------ + + def _scope(self) -> str: + return " ".join(self.config.scopes) + + def _pkce_login(self, open_browser: bool) -> TokenSet: + verifier = generate_code_verifier() + state = secrets.token_urlsafe(24) + server = _CallbackServer(self.config.redirect_port) + try: + query = { + "response_type": "code", + "client_id": self.client_id, + "redirect_uri": server.redirect_uri, + "scope": self._scope(), + "state": state, + "nonce": secrets.token_urlsafe(24), + "code_challenge": code_challenge(verifier), + "code_challenge_method": "S256", + **self.config.extra_params, + } + url = f"{self._endpoint('authorization_endpoint')}?{urlencode(query)}" + self.notify(f"Opening the browser to log in. If it doesn't open, visit:\n{url}") + if open_browser: + self.open_browser(url) + result = server.wait(LOGIN_TIMEOUT_SECONDS) + finally: + server.close() + if "error" in result: + raise AuthError(f"login failed: {result.get('error_description') or result['error']}") + if result.get("state") != state: + raise AuthError("login failed: the state parameter of the response does not match") + if "code" not in result: + raise AuthError("login failed: the response contains no authorization code") + return self._token_request( + { + "grant_type": "authorization_code", + "code": result["code"], + "redirect_uri": server.redirect_uri, + "code_verifier": verifier, + } + ) + + def _device_login(self) -> TokenSet: + response = self.http.post( + self._endpoint("device_authorization_endpoint"), + data={**self._client_params(), "scope": self._scope(), **self.config.extra_params}, + ) + try: + body = response.json() + except ValueError: + body = {} + if response.status_code >= 400 or "device_code" not in body: + error = body.get("error_description") or body.get("error") or f"HTTP {response.status_code}" + raise AuthError(f"device authorization request failed: {error}") + if complete := body.get("verification_uri_complete"): + self.notify(f"To log in, visit {complete}\n(code: {body.get('user_code')})") + else: + self.notify(f"To log in, visit {body.get('verification_uri')} and enter the code {body.get('user_code')}") + + interval = float(body.get("interval", 5)) + deadline = time.monotonic() + float(body.get("expires_in", LOGIN_TIMEOUT_SECONDS)) + data = {"grant_type": DEVICE_GRANT_TYPE, "device_code": body["device_code"]} + while time.monotonic() < deadline: + self.sleep(interval) + response = self.http.post(self._endpoint("token_endpoint"), data={**data, **self._client_params()}) + try: + token_body = response.json() + except ValueError: + token_body = {} + if response.status_code < 400 and "access_token" in token_body: + return self._token_set(token_body, None) + error = token_body.get("error") + if error == "authorization_pending": + continue + if error == "slow_down": + interval += 5 + continue + reason = token_body.get("error_description") or error or response.status_code + raise AuthError(f"device login failed: {reason}") + raise AuthError("device login timed out") + + def _client_credentials(self) -> TokenSet: + return self._token_request( + {"grant_type": "client_credentials", "scope": self._scope(), **self.config.extra_params} + ) diff --git a/src/dittoctl/auth/store.py b/src/dittoctl/auth/store.py new file mode 100644 index 0000000..5f6f6dc --- /dev/null +++ b/src/dittoctl/auth/store.py @@ -0,0 +1,118 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +"""Secret storage: the OS keyring, with a 0600 file in the state directory as fallback. + +Select the backend with ``DITTOCTL_SECRET_STORE=keyring|file|auto`` (default ``auto``). +""" + +from __future__ import annotations + +import contextlib +import json +import os +from pathlib import Path +from typing import Protocol + +from dittoctl.config import state_dir +from dittoctl.errors import ConfigError + +KEYRING_SERVICE = "dittoctl" + + +class SecretStore(Protocol): + def get(self, key: str) -> str | None: ... + + def set(self, key: str, value: str) -> None: ... + + def delete(self, key: str) -> None: ... + + +class KeyringStore: + def __init__(self, service: str = KEYRING_SERVICE) -> None: + self.service = service + + def get(self, key: str) -> str | None: + import keyring + + return keyring.get_password(self.service, key) + + def set(self, key: str, value: str) -> None: + import keyring + + keyring.set_password(self.service, key, value) + + def delete(self, key: str) -> None: + import keyring + from keyring.errors import PasswordDeleteError + + with contextlib.suppress(PasswordDeleteError): + keyring.delete_password(self.service, key) + + +class FileStore: + def __init__(self, path: Path | None = None) -> None: + self.path = path or state_dir() / "secrets.json" + + def _read(self) -> dict[str, str]: + if not self.path.exists(): + return {} + try: + return json.loads(self.path.read_text(encoding="utf-8")) + except (OSError, ValueError) as e: + raise ConfigError(f"cannot read secret file {self.path}: {e}") from e + + def _write(self, data: dict[str, str]) -> None: + self.path.parent.mkdir(parents=True, exist_ok=True) + tmp = self.path.with_suffix(".tmp") + fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + with os.fdopen(fd, "w", encoding="utf-8") as f: + json.dump(data, f, indent=2, sort_keys=True) + tmp.replace(self.path) + + def get(self, key: str) -> str | None: + return self._read().get(key) + + def set(self, key: str, value: str) -> None: + data = self._read() + data[key] = value + self._write(data) + + def delete(self, key: str) -> None: + data = self._read() + if data.pop(key, None) is not None: + self._write(data) + + +def _keyring_usable() -> bool: + try: + import keyring + from keyring.backends import fail + + return not isinstance(keyring.get_keyring(), fail.Keyring) + except Exception: + return False + + +def default_store() -> SecretStore: + backend = os.environ.get("DITTOCTL_SECRET_STORE", "auto") + if backend == "file": + return FileStore() + if backend == "keyring": + return KeyringStore() + if backend != "auto": + raise ConfigError(f"DITTOCTL_SECRET_STORE must be 'keyring', 'file' or 'auto', not '{backend}'") + return KeyringStore() if _keyring_usable() else FileStore() diff --git a/src/dittoctl/cli/__init__.py b/src/dittoctl/cli/__init__.py new file mode 100644 index 0000000..753916f --- /dev/null +++ b/src/dittoctl/cli/__init__.py @@ -0,0 +1,17 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +"""The command line interface: a thin layer over :mod:`dittoctl.core`.""" diff --git a/src/dittoctl/cli/api_cmd.py b/src/dittoctl/cli/api_cmd.py new file mode 100644 index 0000000..2cbd1cc --- /dev/null +++ b/src/dittoctl/cli/api_cmd.py @@ -0,0 +1,121 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +"""``dittoctl api`` (raw authenticated requests) and ``dittoctl whoami``.""" + +from __future__ import annotations + +import json +import sys +from pathlib import Path +from typing import Any + +import click + +from dittoctl.cli import output +from dittoctl.cli.options import conditional_options, output_option, parse_key_value, pop_conditions, protected_write +from dittoctl.cli.state import AppState, pass_state +from dittoctl.core.client import MERGE_PATCH + +METHODS = ("GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS") +READ_METHODS = ("GET", "HEAD", "OPTIONS") + + +def read_data(value: str) -> str: + """``@file`` reads a file, ``@-`` reads stdin, anything else is the data itself.""" + if value == "@-": + return sys.stdin.read() + if value.startswith("@"): + try: + return Path(value[1:]).read_text(encoding="utf-8") + except OSError as e: + raise click.BadParameter(str(e), param_hint="--data") from e + return value + + +def _content_type(method: str, data: str) -> str: + try: + json.loads(data) + except ValueError: + return "text/plain" + return MERGE_PATCH if method == "PATCH" else "application/json" + + +@click.command("api") +@click.argument("method", type=click.Choice(METHODS, case_sensitive=False), metavar="METHOD") +@click.argument("path") +@click.option("-d", "--data", help="Request body: inline, @file, or @- for stdin.") +@click.option("-q", "--query", "query", multiple=True, metavar="NAME=VALUE", help="Query parameter. Repeatable.") +@click.option("--content-type", help="Content type of the body (default: derived from method and body).") +@click.option("-i", "--include", is_flag=True, help="Print the response status and headers to stderr.") +@output_option(("json", "ndjson", "raw"), "json") +@conditional_options +@protected_write(lambda params: params["method"].upper() not in READ_METHODS) +@pass_state +def api( + state: AppState, + method: str, + path: str, + data: str | None, + query: tuple[str, ...], + content_type: str | None, + include: bool, + output_format: str, + **kwargs: Any, +) -> None: + """Send an authenticated request to any Ditto endpoint and print the response. + + \b + Examples: + dittoctl api GET /api/2/whoami + dittoctl api GET /api/2/things/org.example:sensor-1 -q fields=thingId,attributes + dittoctl api PATCH /api/2/things/org.example:sensor-1/attributes -d '{"location":"lab"}' --if-equal skip + dittoctl api PUT /api/2/things/org.example:sensor-2 -d @thing.json --if-none-match '*' + """ + conditions = pop_conditions(kwargs) + method = method.upper() + if not path.startswith("/"): + path = "/" + path + body = read_data(data) if data is not None else None + response = state.client().request( + method, + path, + params=parse_key_value(query, "--query"), + content=body, + content_type=content_type or (_content_type(method, body) if body is not None else None), + conditions=conditions, + ) + if include: + output.info(f"{response.status}") + for name, value in response.headers.items(): + output.info(f"{name}: {value}") + if response.body is not None: + output.emit(response.body, output_format, text="json" not in response.headers.get("content-type", "")) + + +@click.command("whoami") +@output_option(("json", "text"), "text") +@pass_state +def whoami(state: AppState, output_format: str) -> None: + """Show the subjects Ditto derives from your credentials.""" + info = state.client().whoami() + if output_format == "json" or not isinstance(info, dict): + output.emit(info) + return + default = info.get("defaultSubject") + for subject in info.get("subjects", []): + marker = " (default)" if subject == default else "" + click.echo(f"{subject}{marker}") diff --git a/src/dittoctl/cli/auth_cmd.py b/src/dittoctl/cli/auth_cmd.py new file mode 100644 index 0000000..3d2a42a --- /dev/null +++ b/src/dittoctl/cli/auth_cmd.py @@ -0,0 +1,119 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +"""``dittoctl auth``: log in and out, show the auth status, print tokens.""" + +from __future__ import annotations + +import sys +from datetime import UTC, datetime + +import click + +from dittoctl.cli import output +from dittoctl.cli.options import output_option +from dittoctl.cli.state import AppState, pass_state +from dittoctl.errors import AuthError + + +def _read_stdin_secret() -> str: + secret = sys.stdin.read().strip() + if not secret: + raise click.UsageError("no secret on stdin") + return secret + + +@click.group("auth") +def auth_group() -> None: + """Log in to the current context and manage its credentials.""" + + +@auth_group.command("login") +@click.option("--password-stdin", is_flag=True, help="[basic] Read the password from stdin.") +@click.option("--token-stdin", is_flag=True, help="[token] Read the bearer token from stdin.") +@click.option("--secret-stdin", is_flag=True, help="[oidc] Read the client secret from stdin.") +@click.option("--no-browser", is_flag=True, help="[oidc pkce] Print the login URL instead of opening a browser.") +@pass_state +def login(state: AppState, password_stdin: bool, token_stdin: bool, secret_stdin: bool, no_browser: bool) -> None: + """Obtain credentials and store them in the OS keyring. + + \b + basic prompts for the password (or reads it with --password-stdin) + token prompts for the token (or reads it with --token-stdin) + oidc runs the configured flow: browser login (pkce), device code (device), + or client credentials (with the client secret from --secret-stdin) + """ + context = state.context() + method = context.auth.method + secret = None + if method == "basic": + prompt = f"Password for {context.auth.username}" + secret = _read_stdin_secret() if password_stdin else click.prompt(prompt, hide_input=True) + elif method == "token": + secret = _read_stdin_secret() if token_stdin else click.prompt("Bearer token", hide_input=True) + elif method == "oidc": + if secret_stdin: + secret = _read_stdin_secret() + elif context.auth.flow == "client-credentials" and sys.stdin.isatty(): + secret = click.prompt("Client secret", hide_input=True) + else: + output.info(f"Context '{context.name}' uses auth method '{method}', which needs no login.") + return + state.auth(context).login(secret=secret, open_browser=not no_browser) + output.info(f"Logged in to context '{context.name}'.") + + +@auth_group.command("logout") +@pass_state +def logout(state: AppState) -> None: + """Delete the stored credentials of the current context.""" + context = state.context() + state.auth(context).logout() + output.info(f"Logged out of context '{context.name}'.") + + +@auth_group.command("status") +@output_option(("text", "json"), "text") +@pass_state +def status(state: AppState, output_format: str) -> None: + """Show how the current context authenticates and whether credentials are available.""" + context = state.context() + info = state.auth(context).status() + info["url"] = context.url + if output_format == "json": + output.emit(info) + return + for key in ("context", "url", "method", "username", "subject", "issuer", "client_id", "flow"): + if info.get(key): + click.echo(f"{key + ':':<15}{info[key]}") + click.echo(f"{'authenticated:':<15}{'yes' if info.get('authenticated') else 'no'}") + if expires_at := info.get("expires_at"): + when = datetime.fromtimestamp(expires_at, UTC).isoformat(timespec="seconds") + click.echo(f"{'expires:':<15}{when}" + (" (refreshable)" if info.get("refreshable") else "")) + if claims := info.get("claims"): + for claim in ("sub", "iss", "aud", "email"): + if claim in claims: + click.echo(f"{'token ' + claim + ':':<15}{claims[claim]}") + + +@auth_group.command("token") +@pass_state +def token(state: AppState) -> None: + """Print a valid bearer token, for example to paste into the Ditto UI or use with curl.""" + bearer = state.auth().bearer_token() + if not bearer: + raise AuthError("the current context does not authenticate with a bearer token") + click.echo(bearer) diff --git a/src/dittoctl/cli/bulk_options.py b/src/dittoctl/cli/bulk_options.py new file mode 100644 index 0000000..11b2806 --- /dev/null +++ b/src/dittoctl/cli/bulk_options.py @@ -0,0 +1,309 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +"""Options and flow shared by commands that act on many things: selection, safety checks, bulk execution.""" + +from __future__ import annotations + +import json +import sys +from collections.abc import Callable +from dataclasses import dataclass +from typing import Any, TypeVar + +import click +from rich.console import Console +from rich.progress import BarColumn, MofNCompleteColumn, Progress, TextColumn, TimeElapsedColumn + +from dittoctl.cli import output +from dittoctl.cli.api_cmd import read_data +from dittoctl.cli.options import confirm_context_option +from dittoctl.cli.state import AppState +from dittoctl.cli.things_cmd import resolve_filter, resolve_namespaces +from dittoctl.core.bulk import Category, FailureLog, Journal, Outcome, Summary, run_bulk +from dittoctl.core.selectors import Selection, resolve +from dittoctl.errors import AbortedError, DittoctlError, ExitCode, InterruptedRunError + +F = TypeVar("F", bound=Callable[..., Any]) +DRY_RUN_SAMPLES = 3 +# failed things whose error is shown directly; all of them go to --failed-out +FAILURE_SAMPLES = 3 +RESULTS = ("none", "failures", "all") + + +class BulkFailure(DittoctlError): + exit_code = ExitCode.PARTIAL_FAILURE + + +def _apply(f: F, options: list[Callable[[F], F]]) -> F: + for option in reversed(options): + f = option(f) + return f + + +def selector_options(f: F) -> F: + """--ids-file, --filter, --namespaces, --include-file, --exclude-file. Thing ids come as arguments.""" + return _apply( + f, + [ + click.option("--ids-file", metavar="FILE", help="Thing ids, one per line (first column); - reads stdin."), + click.option("-f", "--filter", "rql_filter", metavar="RQL", help="Select by RQL filter; @file reads it."), + click.option("--no-validate", is_flag=True, help="Send the filter without checking it locally first."), + click.option("-n", "--namespaces", multiple=True, metavar="NS[,NS]", help="Namespaces for --filter."), + click.option("--include-file", metavar="FILE", help="Only things whose id is also in this file."), + click.option("--exclude-file", metavar="FILE", help="Leave out things whose id is in this file."), + ], + ) + + +def write_options(f: F) -> F: + """Safety (--dry-run, --yes, --max-affected, --confirm-context) and bulk (--concurrency, --rate, ...).""" + return _apply( + f, + [ + click.option("--dry-run", is_flag=True, help="Show what would be sent, without writing anything."), + click.option("-y", "--yes", is_flag=True, help="Don't ask; required above --max-affected things."), + click.option( + "--max-affected", + type=click.IntRange(min=0), + default=100, + show_default=True, + help="Above this many things, --yes is required.", + ), + confirm_context_option, + click.option( + "--concurrency", + type=click.IntRange(1, 64), + default=8, + show_default=True, + help="Requests in flight at the same time.", + ), + click.option("--rate", type=float, metavar="N", help="At most N requests per second."), + click.option("--journal", metavar="FILE", help="Record finished things here, to --resume later."), + click.option("--resume", is_flag=True, help="Skip the things already recorded in --journal."), + click.option( + "--failed-out", metavar="FILE", help="Write failed things here (usable as --ids-file to retry them)." + ), + click.option( + "--results", + type=click.Choice(RESULTS), + help="Print a JSON line per thing on stdout: 'failures' (with Ditto's error and its description; " + "in a dry run, the first planned requests) or 'all', then a summary line. " + "Default: none; agent mode: failures.", + ), + ], + ) + + +@dataclass +class WriteOptions: + dry_run: bool + yes: bool + max_affected: int + confirm_context: str | None + concurrency: int + rate: float | None + journal: str | None + resume: bool + failed_out: str | None + results: str | None + + @classmethod + def pop(cls, kwargs: dict[str, Any]) -> WriteOptions: + options = cls(**{name: kwargs.pop(name) for name in cls.__dataclass_fields__}) + if options.resume and not options.journal: + raise click.UsageError("--resume needs --journal FILE") + if options.results is None: + options.results = "failures" if output.agent_mode() else "none" + return options + + +def pop_selection(state: AppState, thing_ids: tuple[str, ...], kwargs: dict[str, Any]) -> Selection: + rql_filter = kwargs.pop("rql_filter") + no_validate = kwargs.pop("no_validate") + namespaces = kwargs.pop("namespaces") + return Selection( + ids=list(thing_ids), + ids_file=kwargs.pop("ids_file"), + rql_filter=resolve_filter(rql_filter, not no_validate), + namespaces=resolve_namespaces(state, namespaces) if rql_filter else [], + include_file=kwargs.pop("include_file"), + exclude_file=kwargs.pop("exclude_file"), + ) + + +def select(state: AppState, selection: Selection) -> list[str]: + ids = resolve(state.client(), selection, streaming_allowed=state.context().search_streaming, warn=output.warn) + output.info(f"Selected {len(ids)} thing(s).") + return ids + + +def read_json(value: str, option: str = "--data") -> Any: + text = read_data(value) + try: + return json.loads(text) + except ValueError as e: + raise click.BadParameter(f"not valid JSON: {e}", param_hint=option) from None + + +def confirm(state: AppState, count: int, options: WriteOptions, action: str, *, destructive: bool = False) -> None: + """Ask for the confirmations the safety rules require; raises AbortedError if they aren't given.""" + if options.dry_run or count == 0: + return + interactive = sys.stdin.isatty() + if count > options.max_affected and not options.yes: + raise AbortedError( + f"this would {action} {count} things, more than --max-affected {options.max_affected}. " + "Check the selection with --dry-run, then pass --yes (or raise --max-affected)" + ) + if destructive and not options.yes: + if not interactive: + raise AbortedError(f"refusing to {action} {count} thing(s) without --yes when not interactive") + if not click.confirm(f"{action.capitalize()} {count} thing(s)? This cannot be undone", default=False): + raise AbortedError("not confirmed") + state.confirm_protected(f"{action} {count} thing(s)", options.confirm_context) + + +def execute( + state: AppState, + ids: list[str], + operation: Callable[[str], Outcome], + options: WriteOptions, + action: str, + on_outcome: Callable[[Outcome], None] | None = None, + noun: str = "things", + reports_successes: bool = False, +) -> Summary: + """Run the operation for all ids with progress, then print the summary. + + With ``--results``, each outcome is also printed as a JSON line on stdout, then a summary line; + ``reports_successes`` means ``on_outcome`` already prints the successful ones (e.g. message responses). + Raises BulkFailure (exit code 2) if things failed and InterruptedRunError (130) if interrupted. + """ + samples: list[Outcome] = [] + + failure_samples: list[Outcome] = [] + key = "policyId" if noun == "policies" else "thingId" + + def report(outcome: Outcome, sample: bool) -> None: + if outcome.category == Category.PLANNED: + wanted = options.results == "all" or sample + elif outcome.category == Category.OK and reports_successes: + wanted = False + else: + wanted = options.results == "all" or outcome.failed + if wanted: + output.line(result_line(outcome, key)) + + def collect(outcome: Outcome) -> None: + sample = outcome.category == Category.PLANNED and len(samples) < DRY_RUN_SAMPLES + if sample: + samples.append(outcome) + if outcome.failed and len(failure_samples) < FAILURE_SAMPLES: + failure_samples.append(outcome) + if options.results != "none": + report(outcome, sample) + if on_outcome: + on_outcome(outcome) + + journal = Journal(options.journal) if options.journal and not options.dry_run else None + failure_log = FailureLog(options.failed_out) if options.failed_out and not options.dry_run else None + + def run(callback: Callable[[Outcome], None]) -> Summary: + return run_bulk( + ids, + operation, + concurrency=options.concurrency, + rate=options.rate, + journal=journal, + resume=options.resume, + failure_log=failure_log, + on_outcome=callback, + ) + + if sys.stderr.isatty() and len(ids) > 1: + progress = Progress( + TextColumn(action.capitalize()), + BarColumn(), + MofNCompleteColumn(), + TimeElapsedColumn(), + console=Console(emoji=False, file=sys.stderr), + transient=True, + ) + with progress: + task = progress.add_task(action, total=len(ids)) + + def advance(outcome: Outcome) -> None: + progress.advance(task) + collect(outcome) + + summary = run(advance) + else: + summary = run(collect) + + if options.results != "none": + output.line({"summary": summary_line(summary, action, options.dry_run)}) + if options.dry_run: + if options.results == "none": + for sample in samples: + output.info(f"would send for {sample.thing_id}:") + output.emit(sample.detail) + output.info(f"Dry run, nothing written. {summary.describe(noun)}") + else: + output.info(f"{action.capitalize()}: {summary.describe(noun)}") + if summary.interrupted: + hint = f"; resume with --journal {options.journal} --resume" if options.journal else "" + raise InterruptedRunError(f"interrupted after {summary.processed} of {summary.total} {noun}{hint}") + if summary.failures: + for failure in failure_samples if options.results == "none" else []: + reason = " ".join(p for p in (str(failure.status or ""), failure.error or "") if p) + output.warn(f"{failure.thing_id}: {reason}: {failure.message or ''}".rstrip(": ")) + if failure.description: + output.info(f" {failure.description}") + if summary.failures > len(failure_samples): + output.info(f"... and {summary.failures - len(failure_samples)} more") + where = f"; all failed {noun} are listed in {options.failed_out}" if options.failed_out else "" + raise BulkFailure(f"{summary.failures} of {summary.total} {noun} failed{where}") + return summary + + +def result_line(outcome: Outcome, key: str = "thingId") -> dict[str, Any]: + """The JSON line of one thing's outcome for --results.""" + line: dict[str, Any] = {key: outcome.thing_id, "result": str(outcome.category)} + for name in ("status", "error", "message", "description"): + value = getattr(outcome, name) + if value is not None: + line[name] = value + if outcome.category == Category.PLANNED: + line["plan"] = outcome.detail + return line + + +def summary_line(summary: Summary, action: str, dry_run: bool) -> dict[str, Any]: + line: dict[str, Any] = { + "action": action, + "dryRun": dry_run, + "total": summary.total, + "processed": summary.processed, + "counts": {str(category): n for category, n in summary.counts.most_common()}, + "failures": summary.failures, + "elapsedSeconds": round(summary.elapsed, 3), + } + if summary.skipped_by_journal: + line["skippedByJournal"] = summary.skipped_by_journal + if summary.interrupted: + line["interrupted"] = True + return line diff --git a/src/dittoctl/cli/config_cmd.py b/src/dittoctl/cli/config_cmd.py new file mode 100644 index 0000000..20f030b --- /dev/null +++ b/src/dittoctl/cli/config_cmd.py @@ -0,0 +1,203 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +"""``dittoctl config``: manage contexts.""" + +from __future__ import annotations + +import sys +from typing import Any + +import click +import tomli_w +from rich.console import Console +from rich.table import Table + +from dittoctl.auth import provider_for +from dittoctl.cli import output +from dittoctl.cli.options import parse_key_value +from dittoctl.cli.state import AppState, pass_state +from dittoctl.config import AUTH_METHODS, OIDC_FLOWS, AuthConfig, Context +from dittoctl.errors import ConfigError + + +def complete_context_names(ctx: click.Context, param: click.Parameter, incomplete: str) -> list[str]: + from dittoctl.config import Config + + try: + names = Config.load(ctx.find_root().params.get("config_path")).contexts + except Exception: + return [] + return [name for name in sorted(names) if name.startswith(incomplete)] + + +@click.group("config") +def config_group() -> None: + """Manage contexts: named Ditto endpoints with their authentication settings.""" + + +@config_group.command("add-context") +@click.argument("name") +@click.option("--url", required=True, help="Base URL of Ditto, e.g. https://ditto.example.com") +@click.option( + "--auth", + "method", + type=click.Choice(AUTH_METHODS), + default="none", + show_default=True, + help="How to authenticate; the options below marked [method] configure it.", +) +@click.option("--username", help="[basic] User name.") +@click.option("--subject", help="[preauth] Value of the x-ditto-pre-authenticated header, e.g. nginx:ditto.") +@click.option("--issuer", help="[oidc] Issuer URL used for discovery.") +@click.option("--client-id", help="[oidc] OAuth2 client id.") +@click.option("--flow", type=click.Choice(OIDC_FLOWS), default="pkce", show_default=True, help="[oidc] Login flow.") +@click.option("--scope", "scopes", multiple=True, help="[oidc] Scope to request; repeatable. Default: openid.") +@click.option( + "--auth-param", + "auth_params", + multiple=True, + metavar="NAME=VALUE", + help="[oidc] Extra parameter for the authorization request, e.g. audience=ditto. Repeatable.", +) +@click.option( + "--redirect-port", type=int, default=0, help="[oidc] Fixed loopback port for the PKCE redirect (default: random)." +) +@click.option("--use-id-token", is_flag=True, help="[oidc] Send the id token to Ditto instead of the access token.") +@click.option("--namespace", "namespaces", multiple=True, help="Default namespace for searches. Repeatable.") +@click.option("--header", "headers", multiple=True, metavar="NAME=VALUE", help="Header sent with every request.") +@click.option("--protected", is_flag=True, help="Require typing the context name to confirm writes (e.g. production).") +@click.option("--timeout", type=float, default=30.0, show_default=True, help="Request timeout in seconds.") +@click.option("--ca-cert", type=click.Path(exists=True, dir_okay=False), help="CA bundle to verify TLS with.") +@click.option("--insecure", is_flag=True, help="Don't verify TLS certificates.") +@click.option( + "--no-search-streaming", + is_flag=True, + help="Never stream searches via SSE automatically, e.g. if the Ditto gateway throttles SSE search.", +) +@click.option("--use/--no-use", "use", default=None, help="Make it the current context (default: if it's the first).") +@click.option("--overwrite", is_flag=True, help="Replace an existing context with the same name.") +@pass_state +def add_context(state: AppState, name: str, **opts: Any) -> None: + """Add a context.""" + config = state.config() + if name in config.contexts and not opts["overwrite"]: + raise ConfigError(f"context '{name}' already exists; pass --overwrite to replace it") + if opts["ca_cert"] and opts["insecure"]: + raise click.UsageError("--ca-cert and --insecure are mutually exclusive") + auth = AuthConfig( + method=opts["method"], + username=opts["username"], + subject=opts["subject"], + issuer=opts["issuer"], + client_id=opts["client_id"], + flow=opts["flow"], + scopes=list(opts["scopes"]) or ["openid"], + extra_params=parse_key_value(opts["auth_params"], "--auth-param"), + redirect_port=opts["redirect_port"], + use_token="id" if opts["use_id_token"] else "access", + ) + context = Context( + name=name, + url=opts["url"].rstrip("/"), + auth=auth, + namespaces=list(opts["namespaces"]), + headers=parse_key_value(opts["headers"], "--header", "=:"), + protected=opts["protected"], + timeout=opts["timeout"], + verify=opts["ca_cert"] or not opts["insecure"], + search_streaming=not opts["no_search_streaming"], + ) + config.set_context(context) + use = opts["use"] if opts["use"] is not None else config.current_context is None + if use: + config.current_context = name + config.save() + output.info(f"Context '{name}' saved to {config.path}" + (" and selected." if use else ".")) + if auth.method in ("basic", "token", "oidc"): + output.info("Run 'dittoctl auth login' to store credentials.") + + +@config_group.command("use-context") +@click.argument("name", shell_complete=complete_context_names) +@pass_state +def use_context(state: AppState, name: str) -> None: + """Select the context used when --context is not given.""" + config = state.config() + config.get_context(name) + config.current_context = name + config.save() + output.info(f"Switched to context '{name}'.") + + +@config_group.command("current-context") +@pass_state +def current_context(state: AppState) -> None: + """Print the name of the current context.""" + current = state.config().current_context + if not current: + raise ConfigError("no current context") + click.echo(current) + + +@config_group.command("get-contexts") +@pass_state +def get_contexts(state: AppState) -> None: + """List all contexts.""" + config = state.config() + table = Table(box=None, pad_edge=False) + for column in ("CURRENT", "NAME", "URL", "AUTH", "PROTECTED"): + table.add_column(column) + for name, ctx in sorted(config.contexts.items()): + auth = ctx.auth.method + (f" ({ctx.auth.flow})" if ctx.auth.method == "oidc" else "") + current = "*" if name == config.current_context else "" + table.add_row(current, name, ctx.url, auth, "yes" if ctx.protected else "") + Console(emoji=False, markup=False, file=sys.stdout).print(table) + + +@config_group.command("view") +@click.argument("name", required=False, shell_complete=complete_context_names) +@pass_state +def view(state: AppState, name: str | None) -> None: + """Print the configuration, or a single context, as TOML.""" + config = state.config() + if name: + click.echo(tomli_w.dumps({"contexts": {name: config.get_context(name).to_toml()}}), nl=False) + return + data: dict[str, Any] = {} + if config.current_context: + data["current-context"] = config.current_context + data["contexts"] = {n: c.to_toml() for n, c in sorted(config.contexts.items())} + click.echo(tomli_w.dumps(data), nl=False) + + +@config_group.command("delete-context") +@click.argument("name", shell_complete=complete_context_names) +@pass_state +def delete_context(state: AppState, name: str) -> None: + """Delete a context and its stored credentials.""" + config = state.config() + context = config.delete_context(name) + provider_for(context, state.store()).logout() + config.save() + output.info(f"Deleted context '{name}'.") + + +@config_group.command("path") +@pass_state +def path(state: AppState) -> None: + """Print the path of the config file.""" + click.echo(str(state.config().path)) diff --git a/src/dittoctl/cli/connections_cmd.py b/src/dittoctl/cli/connections_cmd.py new file mode 100644 index 0000000..42e3dbe --- /dev/null +++ b/src/dittoctl/cli/connections_cmd.py @@ -0,0 +1,302 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +"""``dittoctl connections``: manage Ditto connections to message brokers and HTTP endpoints. + +The connections API usually requires Ditto's DevOps credentials, so a separate context is common, e.g. +``dittoctl config add-context prod-devops --url ... --auth basic --username devops``. +""" + +from __future__ import annotations + +import sys +import time +from typing import Any + +import click +from rich.console import Console +from rich.table import Table + +from dittoctl.cli import output +from dittoctl.cli.bulk_options import read_json +from dittoctl.cli.options import duration_option, output_option, protected_write +from dittoctl.cli.state import AppState, pass_state +from dittoctl.core.connections import ( + CONNECTIONS_PATH, + connection_path, + log_key, + redact_secrets, + redact_uri, + send_command, +) +from dittoctl.errors import AbortedError, DittoctlError, DittoError +from dittoctl.formats import write_ndjson + +MAX_TABLE_MESSAGE = 200 + + +def _print_table(columns: tuple[str, ...], rows: list[tuple[str, ...]]) -> None: + table = Table(box=None, pad_edge=False, header_style="bold") + for column in columns: + table.add_column(column, overflow="fold") + for row in rows: + table.add_row(*row) + Console(emoji=False, markup=False, file=sys.stdout, width=None if sys.stdout.isatty() else 300).print(table) + + +@click.group("connections") +def connections_group() -> None: + """Manage connections (usually needs Ditto's DevOps login: use a separate context).""" + + +@connections_group.command("list") +@output_option(("table", "json", "ids"), "table") +@pass_state +def list_(state: AppState, output_format: str) -> None: + """List all connections. URIs are shown without passwords.""" + connections = state.client().get(CONNECTIONS_PATH).body or [] + if output_format == "json": + output.emit(connections) + elif output_format == "ids": + for connection in connections: + click.echo(connection.get("id")) + else: + _print_table( + ("ID", "NAME", "TYPE", "STATUS", "URI"), + [ + ( + c.get("id", ""), + c.get("name", ""), + c.get("connectionType", ""), + c.get("connectionStatus", ""), + redact_uri(c.get("uri", "")), + ) + for c in connections + ], + ) + + +@connections_group.command("get") +@click.argument("connection_id") +@pass_state +def get(state: AppState, connection_id: str) -> None: + """Retrieve a connection's configuration.""" + output.emit(state.client().get(connection_path(connection_id)).body) + + +@connections_group.command("create") +@click.option("-d", "--data", required=True, metavar="JSON|@FILE|@-", help="The connection JSON.") +@protected_write() +@pass_state +def create(state: AppState, data: str) -> None: + """Create a connection; fails if it exists. Without an "id" in the JSON, Ditto generates one. + + See 'connections test' to check a connection without creating it. + """ + connection = read_json(data) + client = state.client() + connection_id = connection.get("id") if isinstance(connection, dict) else None + if not connection_id: + output.emit(client.post(CONNECTIONS_PATH, json=connection).body) + return + # Ditto refuses an id on POST (connectivity:id.notsettable); a PUT creates, but would also replace + try: + client.get(connection_path(connection_id)) + except DittoError as e: + if e.status != 404: + raise + else: + raise DittoctlError(f"connection {connection_id} already exists; use 'connections put' to replace it") + response = client.put(connection_path(connection_id), json=connection) + output.emit(response.body if response.body is not None else client.get(connection_path(connection_id)).body) + + +@connections_group.command("put") +@click.argument("connection_id") +@click.option("-d", "--data", required=True, metavar="JSON|@FILE|@-", help="The connection JSON.") +@protected_write() +@pass_state +def put(state: AppState, connection_id: str, data: str) -> None: + """Create or replace a connection with the given id.""" + response = state.client().put(connection_path(connection_id), json=read_json(data)) + output.info(f"{'Created' if response.status == 201 else 'Updated'} connection {connection_id}.") + + +@connections_group.command("delete") +@click.argument("connection_id") +@click.option("-y", "--yes", is_flag=True, help="Don't ask for confirmation.") +@protected_write() +@pass_state +def delete(state: AppState, connection_id: str, yes: bool) -> None: + """Delete a connection.""" + if not yes: + if not sys.stdin.isatty(): + raise AbortedError("refusing to delete a connection without --yes when not interactive") + if not click.confirm(f"Delete connection {connection_id}?", default=False): + raise AbortedError("not confirmed") + state.client().delete(connection_path(connection_id)) + output.info(f"Deleted connection {connection_id}.") + + +@connections_group.command("test") +@click.option("-d", "--data", required=True, metavar="JSON|@FILE|@-", help="The connection JSON to test.") +@pass_state +def test(state: AppState, data: str) -> None: + """Check a connection configuration (Ditto connects once, then discards it; nothing is created).""" + response = state.client().post(CONNECTIONS_PATH, json=read_json(data), params={"dry-run": "true"}) + if response.body is None: + output.info(f"Connection test succeeded ({response.status}).") + else: + output.emit(response.body) + + +def _command(name: str, description: str) -> None: + @connections_group.command(name, help=description) + @click.argument("connection_id") + @protected_write() + @pass_state + def command(state: AppState, connection_id: str) -> None: + send_command(state.client(), connection_id, name) + output.info(f"{name}: sent to {connection_id}.") + + +_command("open", "Open a connection.") +_command("close", "Close a connection.") +_command("reset-metrics", "Reset a connection's metrics.") + + +@connections_group.command("status") +@click.argument("connection_id") +@output_option(("table", "json"), "table") +@pass_state +def status(state: AppState, connection_id: str, output_format: str) -> None: + """Show the live status of a connection, its clients, sources and targets.""" + body = state.client().get(connection_path(connection_id, "status")).body or {} + if output_format == "json": + output.emit(body) + return + click.echo( + f"connection: {body.get('connectionStatus')} (live: {body.get('liveStatus')})" + f"{', since ' + body['connectedSince'] if body.get('connectedSince') else ''}" + ) + rows = [] + for kind in ("clientStatus", "sourceStatus", "targetStatus", "sshTunnelStatus"): + for entry in body.get(kind, []): + rows.append( + ( + kind.removesuffix("Status"), + entry.get("addresses", entry.get("client", "")) or "", + entry.get("status", ""), + entry.get("statusDetails", ""), + entry.get("inStateSince", ""), + ) + ) + if rows: + _print_table(("KIND", "ADDRESS/CLIENT", "STATUS", "DETAILS", "SINCE"), [tuple(map(str, r)) for r in rows]) + + +@connections_group.command("metrics") +@click.argument("connection_id") +@pass_state +def metrics(state: AppState, connection_id: str) -> None: + """Show a connection's message metrics.""" + output.emit(state.client().get(connection_path(connection_id, "metrics")).body) + + +@connections_group.command("logs") +@click.argument("connection_id") +@click.option("--enable", is_flag=True, help="Enable logging first (Ditto keeps it on for a limited time).") +@click.option("--reset", is_flag=True, help="Clear the logs first.") +@click.option( + "--follow", is_flag=True, help="Keep polling and print new entries as they appear, until Ctrl+C or --duration." +) +@click.option("--interval", type=float, default=2.0, show_default=True, help="Seconds between polls with --follow.") +@duration_option("following") +@click.option("--no-redact", is_flag=True, help="Show Authorization headers and URI passwords in log messages.") +@output_option(("table", "ndjson"), "table") +@protected_write(lambda params: params["enable"] or params["reset"]) +@pass_state +def logs( + state: AppState, + connection_id: str, + enable: bool, + reset: bool, + follow: bool, + interval: float, + no_redact: bool, + output_format: str, + duration: float | None, +) -> None: + """Show a connection's logs: successful and failed messages per source/target address. + + Ditto's log messages contain the headers of the request that caused a message, including Authorization + headers; dittoctl masks them unless --no-redact is given. The table shortens long messages; -o ndjson + shows them completely. + + \b + Example: + dittoctl connections logs my-connection --enable --follow -o ndjson + """ + client = state.client() + if reset: + send_command(client, connection_id, "reset-logs") + if enable: + send_command(client, connection_id, "enable-logs") + seen: set[tuple[Any, ...]] = set() + + def poll() -> list[dict[str, Any]]: + body = client.get(connection_path(connection_id, "logs")).body or {} + if not body.get("enabledSince") and not enable and not warned: + output.warn("logging is not enabled for this connection (or it is closed); pass --enable") + warned.append(True) + fresh = [e for e in body.get("connectionLogs", []) if log_key(e) not in seen] + seen.update(log_key(e) for e in fresh) + if not no_redact: + fresh = [{**e, "message": redact_secrets(str(e.get("message", "")))} for e in fresh] + return sorted(fresh, key=lambda e: e.get("timestamp", "")) + + def shorten(text: str) -> str: + text = " ".join(text.split()) + return text if len(text) <= MAX_TABLE_MESSAGE else text[: MAX_TABLE_MESSAGE - 1] + "…" + + def show(entries: list[dict[str, Any]]) -> None: + if output_format == "ndjson": + write_ndjson(entries, sys.stdout, flush=True) + elif entries: + _print_table( + ("TIMESTAMP", "LEVEL", "CATEGORY", "TYPE", "ADDRESS", "ENTITY", "MESSAGE"), + [ + ( + *(str(e.get(k, "")) for k in ("timestamp", "level", "category", "type", "address", "entityId")), + shorten(str(e.get("message", ""))), + ) + for e in entries + ], + ) + + warned: list[bool] = [] + show(poll()) + if not follow: + return + limit = output.agent_duration(duration) + deadline = time.monotonic() + limit if limit else None + try: + while deadline is None or time.monotonic() + interval < deadline: + time.sleep(interval) + show(poll()) + except KeyboardInterrupt: + return + output.info(f"Stopped following after {limit:g}s (--duration).") diff --git a/src/dittoctl/cli/devops_cmd.py b/src/dittoctl/cli/devops_cmd.py new file mode 100644 index 0000000..e06634c --- /dev/null +++ b/src/dittoctl/cli/devops_cmd.py @@ -0,0 +1,261 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +"""``dittoctl devops``: operate a Ditto installation (needs Ditto's DevOps login, usually a separate context).""" + +from __future__ import annotations + +import sys +from typing import Any + +import click +from rich.console import Console +from rich.table import Table + +from dittoctl.cli import output +from dittoctl.cli.bulk_options import read_json +from dittoctl.cli.options import output_option, protected_write +from dittoctl.cli.state import AppState, pass_state +from dittoctl.core.devops import ( + SEARCH_SERVICE, + block_namespace_command, + get_config, + get_logging, + health_lines, + piggyback, + piggyback_errors, + purge_namespace_command, + purge_results, + purge_succeeded, + reindex_command, + reindex_thing_command, + set_logging, + shutdown_namespace_command, + unblock_namespace_command, +) +from dittoctl.errors import AbortedError, DittoctlError, DittoError + +LEVELS = ("trace", "debug", "info", "warn", "error", "off") +SERVICES = ("gateway", "things", "things-search", "policies", "connectivity") + + +def _table(columns: tuple[str, ...], rows: list[tuple[str, ...]]) -> None: + table = Table(box=None, pad_edge=False, header_style="bold") + for column in columns: + table.add_column(column, overflow="fold") + for row in rows: + table.add_row(*row) + Console(emoji=False, markup=False, file=sys.stdout, width=None if sys.stdout.isatty() else 200).print(table) + + +@click.group("devops") +def devops_group() -> None: + """Operate Ditto: log levels, configuration, piggyback commands, reindexing, namespaces, status. + + These endpoints need Ditto's DevOps login; use a separate context, e.g. 'dittoctl -c prod-devops devops ...'. + """ + + +@devops_group.group("logging") +def logging_group() -> None: + """Show and change log levels at runtime.""" + + +@logging_group.command("get") +@click.argument("service", required=False, type=click.Choice(SERVICES)) +@output_option(("table", "json"), "table") +@pass_state +def logging_get(state: AppState, service: str | None, output_format: str) -> None: + """Show the log levels of all services, or of one.""" + body = get_logging(state.client(), service) or {} + if output_format == "json": + output.emit(body) + return + by_service = {service: body} if service else body + rows = [] + for name, instances in sorted(by_service.items()): + for instance, response in sorted((instances or {}).items()): + for config in response.get("loggerConfigs", []): + rows.append((name, str(instance), config.get("logger", ""), config.get("level", ""))) + _table(("SERVICE", "INSTANCE", "LOGGER", "LEVEL"), rows) + + +@logging_group.command("set") +@click.argument("logger") +@click.argument("level", type=click.Choice(LEVELS, case_sensitive=False)) +@click.option("--service", type=click.Choice(SERVICES), help="Only this service (default: all).") +@protected_write() +@pass_state +def logging_set(state: AppState, logger: str, level: str, service: str | None) -> None: + """Set the level of a logger, such as 'org.eclipse.ditto debug'. Takes effect immediately, until a restart.""" + set_logging(state.client(), logger, level, service) + output.info(f"Set {logger} to {level.lower()} in {service or 'all services'}.") + + +@devops_group.command("config") +@click.argument("service", required=False, type=click.Choice(SERVICES)) +@click.option("--instance", help="Only this instance of the service.") +@click.option("--path", help="Only this part of the configuration, e.g. ditto.gateway.streaming.") +@pass_state +def config(state: AppState, service: str | None, instance: str | None, path: str | None) -> None: + """Show the runtime configuration of services (large: narrow it down with --path).""" + if instance and not service: + raise click.UsageError("--instance needs a SERVICE") + output.emit(get_config(state.client(), service, instance, path)) + + +@devops_group.command("piggyback") +@click.argument("service", required=False) +@click.option( + "-d", + "--data", + "data", + required=True, + metavar="JSON|@FILE|@-", + help="The piggyback command: targetActorSelection, headers, piggybackCommand.", +) +@click.option("--instance", help="Only this instance of the service.") +@click.option("--timeout", default="10s", show_default=True, help="How long Ditto waits for responses, e.g. 30s.") +@protected_write() +@pass_state +def piggyback_cmd(state: AppState, service: str | None, data: str, instance: str | None, timeout: str) -> None: + """Send a piggyback command to actors in the Ditto cluster (SERVICE: things, search, connectivity, ...). + + See https://eclipse.dev/ditto/installation-operating.html#piggyback-commands + """ + response = piggyback(state.client(), read_json(data), service=service, instance=instance, timeout=timeout) + output.info(f"{response.status}") + if response.body is not None: + output.emit(response.body) + if response.status >= 400 and response.status != 408: + raise DittoctlError(f"piggyback command failed with {response.status}") + if errors := piggyback_errors(response.body): + first = errors[0].get("payload", errors[0]) + reason = first.get("message") or first.get("error") if isinstance(first, dict) else None + where = errors[0].get("instance") or errors[0].get("serviceName") or "Ditto" + raise DittoctlError( + f"{len(errors)} error response(s), e.g. from {where}: {errors[0].get('status')} {reason or ''}".rstrip() + ) + + +@devops_group.command("reindex") +@click.option("-n", "--namespace", "namespaces", multiple=True, help="Only things of this namespace. Repeatable.") +@click.option("--thing", "thing_ids", multiple=True, metavar="THING_ID", help="Update this thing now. Repeatable.") +@protected_write() +@pass_state +def reindex(state: AppState, namespaces: tuple[str, ...], thing_ids: tuple[str, ...]) -> None: + """Rebuild search index entries: of single things immediately, or of all things (or namespaces) in the next + background sync. Ditto doesn't report progress; follow the search service's logs.""" + if namespaces and thing_ids: + raise click.UsageError("use either --namespace or --thing") + client = state.client() + if thing_ids: + for thing_id in thing_ids: + piggyback(client, reindex_thing_command(thing_id), service=SEARCH_SERVICE, timeout="0") + output.info(f"Requested a search index update of {len(thing_ids)} thing(s).") + return + response = piggyback(client, reindex_command(namespaces), service=SEARCH_SERVICE) + if response.status >= 400 and response.status != 408: + raise DittoctlError(f"reindex request failed with {response.status}: {response.text[:200]}") + where = f"namespace(s) {', '.join(namespaces)}" if namespaces else "all things" + output.info(f"Forced a search index update of {where} in the next background sync.") + + +@devops_group.group("namespace") +def namespace_group() -> None: + """Namespace operations.""" + + +@namespace_group.command("erase") +@click.argument("namespace") +@click.option("--confirm-namespace", metavar="NAMESPACE", help="Confirm without the prompt (for scripts).") +@click.option( + "--purge-timeout", + default="10s", + show_default=True, + help="How long Ditto waits for the services to confirm the erasure.", +) +@protected_write() +@pass_state +def namespace_erase(state: AppState, namespace: str, confirm_namespace: str | None, purge_timeout: str) -> None: + """Erase ALL data of a namespace: things, policies, connections' data and search index entries. + + Runs Ditto's documented sequence: block the namespace, shut down its actors, purge its data from the + persistence, unblock it. Cannot be undone. + """ + if confirm_namespace != namespace: + if confirm_namespace is not None or not sys.stdin.isatty(): + raise AbortedError(f"confirm with --confirm-namespace {namespace}") + typed = click.prompt(f"This erases ALL data in namespace '{namespace}'. Type the namespace to confirm") + if typed != namespace: + raise AbortedError("namespace not confirmed") + client = state.client() + + def step(name: str, command: dict[str, Any], timeout: str = "10s", expect_timeout: bool = False) -> Any: + response = piggyback(client, command, timeout=timeout) + ok = response.status < 300 or (expect_timeout and response.status == 408) + output.info(f"{name}: {response.status}{'' if ok else ' FAILED'}") + if not ok: + raise DittoError(response.status, message=f"{name} failed: {response.text[:300]}") + return response.body + + step("block", block_namespace_command(namespace)) + try: + # Ditto never answers the shutdown, so a 408 is expected. The documented timeout=0 is refused by Ditto + # ("must not be zero if response or acknowledgements are requested"), hence a short timeout. + step("shutdown", shutdown_namespace_command(namespace), timeout="2s", expect_timeout=True) + body = step("purge", purge_namespace_command(namespace), timeout=purge_timeout, expect_timeout=True) + if body is not None and DittoError.is_error_body(body) and body.get("status") == 408: + # observed with Ditto 3.9.8: all services erase the data and log it, but the gateway's aggregation of + # their confirmations times out and answers 408 without any results + raise DittoctlError( + f"Ditto didn't confirm the erasure of namespace {namespace} within {purge_timeout}. The data may " + f"have been erased anyway; check, e.g. with 'things count -n {namespace}', and the services' logs " + "for 'Successfully purged namespace'" + ) + results = purge_results(body) + for result in results: + output.info(f" {result.get('resourceType')}: {'erased' if purge_succeeded(result) else 'FAILED'}") + if not results or not all(purge_succeeded(r) for r in results): + raise DittoctlError(f"the purge of namespace {namespace} was not confirmed for all resource types") + finally: + step("unblock", unblock_namespace_command(namespace)) + output.info(f"Namespace {namespace} erased.") + + +@devops_group.command("status") +@click.option("--health", "with_health", is_flag=True, help="Also show the health of all cluster members.") +@output_option(("text", "json"), "text") +@pass_state +def status(state: AppState, with_health: bool, output_format: str) -> None: + """Show the Ditto version and gateway status, optionally with the cluster health.""" + client = state.client() + info = client.get("/status").body or {} + health = client.get("/status/health").body if with_health else None + if output_format == "json": + output.emit({"status": info, **({"health": health} if health is not None else {})}) + return + for key in ("service-version", "service", "instance", "roles"): + if key in info: + value = info[key] + # /status lists roles either as names or as an object of role -> instances -> details + value = ", ".join(sorted(value)) if isinstance(value, list | dict) else value + click.echo(f"{key + ':':<17}{value}") + if isinstance(health, dict): + click.echo("") + for depth, label, state_ in health_lines(health): + marker = "" if state_ == "UP" else " <--" + click.echo(f"{' ' * depth}{label}: {state_}{marker}") diff --git a/src/dittoctl/cli/main.py b/src/dittoctl/cli/main.py new file mode 100644 index 0000000..8cca0fc --- /dev/null +++ b/src/dittoctl/cli/main.py @@ -0,0 +1,175 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +"""Entry point: the root command group, global options and error handling.""" + +from __future__ import annotations + +from collections.abc import Sequence +from pathlib import Path + +import click +from click.shell_completion import get_completion_class + +from dittoctl import __version__ +from dittoctl.cli import output +from dittoctl.cli.api_cmd import api, whoami +from dittoctl.cli.auth_cmd import auth_group +from dittoctl.cli.config_cmd import complete_context_names, config_group +from dittoctl.cli.connections_cmd import connections_group +from dittoctl.cli.devops_cmd import devops_group +from dittoctl.cli.messages_cmd import messages_group +from dittoctl.cli.options import parse_key_value +from dittoctl.cli.policies_cmd import policies_group +from dittoctl.cli.rql_cmd import rql_group +from dittoctl.cli.state import AppState +from dittoctl.cli.things_cmd import things_group +from dittoctl.cli.things_write_cmd import array_group # noqa: F401 - registers the write commands +from dittoctl.cli.wot_cmd import wot_group +from dittoctl.errors import DittoctlError, ExitCode + +COMPLETE_VAR = "_DITTOCTL_COMPLETE" + + +@click.group(context_settings={"help_option_names": ["-h", "--help"], "max_content_width": 120}) +@click.version_option(__version__, "-V", "--version", prog_name="dittoctl") +@click.option( + "-c", + "--context", + "context_name", + envvar="DITTOCTL_CONTEXT", + shell_complete=complete_context_names, + help="Context to use instead of the current one. [env: DITTOCTL_CONTEXT]", +) +@click.option( + "--url", + envvar="DITTOCTL_URL", + help="Ditto base URL. Without --context, credentials come from DITTOCTL_TOKEN or " + "DITTOCTL_USERNAME/DITTOCTL_PASSWORD. [env: DITTOCTL_URL]", +) +@click.option( + "-H", "--header", "headers", multiple=True, metavar="NAME:VALUE", help="Extra request header. Repeatable." +) +@click.option("--timeout", type=float, help="Request timeout in seconds.") +@click.option("--correlation-id", help="Prefix for the correlation-id of each request (default: random per run).") +@click.option("-v", "--verbose", count=True, help="-v prints requests as curl commands, -vv also response headers.") +@click.option( + "--config", + "config_path", + type=click.Path(dir_okay=False, path_type=Path), + envvar="DITTOCTL_CONFIG", + help="Config file. [env: DITTOCTL_CONFIG]", +) +@click.option( + "--agent/--no-agent", + default=None, + envvar="DITTOCTL_AGENT", + # applied while parsing, so that it also holds for errors before the command runs, e.g. a mistyped command + callback=lambda _ctx, _param, value: output.set_agent_mode(value), + expose_value=False, + help="Output for AI agents: single-line JSON, errors as JSON, limited result sizes, per-thing results of " + "bulk writes, no writes to protected contexts. Default: on if CLAUDECODE or AI_AGENT is set. " + "[env: DITTOCTL_AGENT]", +) +@click.pass_context +def cli( + ctx: click.Context, + context_name: str | None, + url: str | None, + headers: tuple[str, ...], + timeout: float | None, + correlation_id: str | None, + verbose: int, + config_path: Path | None, +) -> None: + """dittoctl - command line tool for Eclipse Ditto.""" + state = AppState( + context_name=context_name, + url=url, + verbose=verbose, + extra_headers=parse_key_value(headers, "--header", ":="), + timeout=timeout, + correlation_id=correlation_id, + config_path=config_path, + ) + ctx.obj = state + ctx.call_on_close(state.close) + + +@click.command("completion") +@click.argument("shell", type=click.Choice(["bash", "zsh", "fish"])) +def completion(shell: str) -> None: + """Print the shell completion script. + + \b + bash: eval "$(dittoctl completion bash)" + zsh: eval "$(dittoctl completion zsh)" + fish: dittoctl completion fish | source + """ + completion_class = get_completion_class(shell) + assert completion_class is not None + click.echo(completion_class(cli, {}, "dittoctl", COMPLETE_VAR).source()) + + +cli.add_command(config_group) +cli.add_command(auth_group) +cli.add_command(whoami) +cli.add_command(things_group) +cli.add_command(rql_group) +cli.add_command(messages_group) +cli.add_command(policies_group) +cli.add_command(connections_group) +cli.add_command(devops_group) +cli.add_command(wot_group) +cli.add_command(api) +cli.add_command(completion) + + +def _usage_error(e: click.ClickException) -> None: + if not output.agent_mode(): + e.show() + return + usage = None + if isinstance(e, click.UsageError) and e.ctx is not None: + usage = f"{e.ctx.get_usage()} (see {e.ctx.command_path} --help)" + output.error_json(ExitCode.ERROR, e.format_message(), error="usage", usage=usage) + + +def _stopped(exit_code: int, message: str) -> int: + if output.agent_mode(): + output.error_json(exit_code, message) + else: + output.info(message) + return exit_code + + +def main(argv: Sequence[str] | None = None) -> int: + # until the root command has parsed --agent/--no-agent, e.g. for errors in the global options + output.set_agent_mode(None) + try: + result = cli.main(args=argv, prog_name="dittoctl", standalone_mode=False, complete_var=COMPLETE_VAR) + except click.exceptions.Abort: + return _stopped(ExitCode.ABORTED, "Aborted.") + except click.ClickException as e: + _usage_error(e) + return ExitCode.ERROR + except DittoctlError as e: + output.error(e) + return e.exit_code + except KeyboardInterrupt: + return _stopped(ExitCode.INTERRUPTED, "Interrupted.") + # in non-standalone mode click returns the exit code for --help/--version, else the command's return value + return result if isinstance(result, int) else ExitCode.OK diff --git a/src/dittoctl/cli/messages_cmd.py b/src/dittoctl/cli/messages_cmd.py new file mode 100644 index 0000000..9b27ee3 --- /dev/null +++ b/src/dittoctl/cli/messages_cmd.py @@ -0,0 +1,178 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +"""``dittoctl messages``: send messages to things and features.""" + +from __future__ import annotations + +import json +import threading +from typing import Any + +import click + +from dittoctl.cli import output +from dittoctl.cli.api_cmd import read_data +from dittoctl.cli.bulk_options import ( + WriteOptions, + confirm, + execute, + pop_selection, + select, + selector_options, + write_options, +) +from dittoctl.cli.options import protected_write +from dittoctl.cli.state import AppState, pass_state +from dittoctl.core.bulk import Category, Outcome +from dittoctl.core.things import thing_path +from dittoctl.core.writes import message_operation + + +@click.group("messages") +def messages_group() -> None: + """Send messages to things and their features, for example commands for devices.""" + + +@messages_group.command("send") +@click.argument("subject") +@click.argument("thing_ids", nargs=-1, metavar="[THING_ID]...") +@click.option("-d", "--data", metavar="JSON|TEXT|@FILE|@-", help="Message payload; JSON if it parses, else text.") +@click.option("--content-type", help="Content type of the payload (default: application/json, or text/plain).") +@click.option("--feature", help="Send to this feature of each thing instead of the thing itself.") +@click.option("--outbox", is_flag=True, help="Send from the thing (outbox) instead of to it (inbox).") +@click.option( + "--timeout", + type=click.IntRange(0, 60), + default=10, + show_default=True, + help="Seconds to wait for each response; 0 sends without waiting (fire and forget).", +) +@click.option( + "--paginate", + metavar="RESPONSE_FIELD[:REQUEST_FIELD]", + help="Follow paged answers: re-send while the response contains RESPONSE_FIELD, passing its value as " + "REQUEST_FIELD (default: the same name) in the payload.", +) +@click.option( + "--max-pages", + type=click.IntRange(min=1), + default=100, + show_default=True, + help="Upper limit of pages per thing with --paginate.", +) +@selector_options +@write_options +@pass_state +def send( + state: AppState, + subject: str, + thing_ids: tuple[str, ...], + data: str | None, + content_type: str | None, + feature: str | None, + outbox: bool, + timeout: int, + paginate: str | None, + max_pages: int, + **kwargs: Any, +) -> None: + """Send the message SUBJECT to each selected thing and print the responses as NDJSON. + + Each response line has thingId, result, status and response; with --results, failed things get a line too. + + Messages are not retried automatically, as devices may not handle duplicates. + + \b + Examples: + dittoctl messages send reboot org.example:sensor-1 --timeout 0 + dittoctl messages send set-interval -d '{"seconds":60}' --feature config -f 'eq(attributes/model,"X1")' + """ + options = WriteOptions.pop(kwargs) + selection = pop_selection(state, thing_ids, kwargs) + if selection.ids_file == "-" and data == "@-": + raise click.UsageError("stdin can't provide both the thing ids (--ids-file -) and the data (@-)") + body: Any = None + if data is not None: + text = read_data(data) + try: + body = json.loads(text) + except ValueError: + body = text + content_type = content_type or "text/plain" + ids = select(state, selection) + confirm(state, len(ids), options, f"send '{subject}' to") + lock = threading.Lock() + + pagination = None + if paginate: + response_field, _, request_field = paginate.partition(":") + pagination = (response_field, request_field or response_field) + if timeout == 0: + raise click.UsageError("--paginate needs responses, so --timeout must not be 0") + + def print_response(outcome: Outcome) -> None: + if timeout == 0 or outcome.detail is None or outcome.category == Category.PLANNED: + return + pages = outcome.detail if pagination else [outcome.detail] + with lock: + for number, page in enumerate(pages, 1): + line: dict[str, Any] = { + "thingId": outcome.thing_id, + "result": str(outcome.category), + "status": outcome.status, + "response": page, + } + if pagination: + line["page"] = number + output.line(line) + + operation = message_operation( + state.client(), + subject, + body, + feature=feature, + outbox=outbox, + timeout=timeout, + content_type=content_type, + paginate=pagination, + max_pages=max_pages, + dry_run=options.dry_run, + ) + execute( + state, ids, operation, options, f"send '{subject}'", on_outcome=print_response, reports_successes=timeout != 0 + ) + + +@messages_group.command("claim") +@click.argument("thing_id") +@click.option( + "--timeout", + type=click.IntRange(0, 60), + default=10, + show_default=True, + help="Seconds to wait for the device's answer.", +) +@protected_write() +@pass_state +def claim(state: AppState, thing_id: str, timeout: int) -> None: + """Claim a thing: send a claim message to its inbox, which the device (or a connected service) answers, + for example by granting you access in the thing's policy.""" + response = state.client().post(thing_path(thing_id, "inbox/claim"), params={"timeout": str(timeout)}, json={}) + if response.body is not None: + output.emit(response.body) + else: + output.info(f"Claim sent to {thing_id} ({response.status}).") diff --git a/src/dittoctl/cli/options.py b/src/dittoctl/cli/options.py new file mode 100644 index 0000000..ace9a75 --- /dev/null +++ b/src/dittoctl/cli/options.py @@ -0,0 +1,181 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +"""Reusable click options.""" + +from __future__ import annotations + +import functools +from collections.abc import Callable, Mapping +from typing import Any, TypeVar + +import click + +from dittoctl.cli.state import AppState +from dittoctl.core.conditions import Conditions, IfEqual, LiveTimeoutStrategy +from dittoctl.core.devops import duration_seconds +from dittoctl.errors import DittoctlError + +F = TypeVar("F", bound=Callable[..., Any]) + +_CONDITION_KEYS = ( + "if_match", + "if_none_match", + "if_equal", + "condition", + "patch_conditions", + "live_condition", + "live_timeout_strategy", +) + + +def parse_key_value(values: tuple[str, ...], option: str, separators: str = "=") -> dict[str, str]: + """Parse repeated NAME=VALUE options. The first matching separator splits name and value.""" + result: dict[str, str] = {} + for item in values: + positions = [i for i in (item.find(s) for s in separators) if i > 0] + if not positions: + raise click.BadParameter(f"expected NAME{separators[0]}VALUE, got '{item}'", param_hint=option) + i = min(positions) + result[item[:i].strip()] = item[i + 1 :].strip() + return result + + +def conditional_options(f: F) -> F: + """Add Ditto's conditional request options (see PLAN.md 4.8) to a command.""" + options = [ + click.option( + "--if-match", + metavar="ETAG|*", + help="Only apply if the entity has this ETag (e.g. rev:5); '*' requires that it exists.", + ), + click.option( + "--if-none-match", + metavar="ETAG|*", + help="'*' only creates and never overwrites; with an ETag on reads, Ditto answers 304 if unchanged.", + ), + click.option( + "--if-equal", + type=click.Choice([v.value for v in IfEqual]), + help="What Ditto does if the new value equals the current one; 'skip' avoids no-op events.", + ), + click.option("--condition", metavar="RQL", help="Only apply if the entity matches this RQL condition."), + click.option( + "--patch-condition", + "patch_conditions", + multiple=True, + metavar="PATH=RQL", + help="Per-path condition for merge requests (Ditto 3.8+). Repeatable.", + ), + click.option("--live-condition", metavar="RQL", help="Route retrieves to the live channel if this matches."), + click.option( + "--live-timeout-strategy", + type=click.Choice([v.value for v in LiveTimeoutStrategy]), + help="What to do if the device doesn't answer a live request in time.", + ), + ] + for option in reversed(options): + f = option(f) + return f + + +def pop_conditions(kwargs: dict[str, Any]) -> Conditions: + """Remove the conditional options from a command's kwargs and build Conditions from them.""" + values = {key: kwargs.pop(key, None) for key in _CONDITION_KEYS} + return Conditions( + if_match=values["if_match"], + if_none_match=values["if_none_match"], + if_equal=IfEqual(values["if_equal"]) if values["if_equal"] else None, + condition=values["condition"], + patch_conditions=parse_key_value(values["patch_conditions"] or (), "--patch-condition"), + live_condition=values["live_condition"], + live_timeout_strategy=( + LiveTimeoutStrategy(values["live_timeout_strategy"]) if values["live_timeout_strategy"] else None + ), + ) + + +def output_option(formats: tuple[str, ...], default: str) -> Callable[[F], F]: + return click.option( + "-o", + "--output", + "output_format", + type=click.Choice(formats), + default=default, + show_default=True, + help="Output format.", + ) + + +def confirm_context_option(f: F) -> F: + return click.option( + "--confirm-context", + metavar="NAME", + help="Confirm a protected context without the prompt (for scripts).", + )(f) + + +def protected_write(when: Callable[[Mapping[str, Any]], bool] | None = None) -> Callable[[F], F]: + """Adds --confirm-context; before the command runs, a protected context has to be confirmed. + + ``when`` decides from the command's arguments whether this invocation writes at all (e.g. ``api GET`` + doesn't). Put the decorator directly above ``@pass_state``. + """ + + def decorator(f: F) -> F: + @functools.wraps(f) + def wrapper(*args: Any, confirm_context: str | None = None, **kwargs: Any) -> Any: + ctx = click.get_current_context() + if when is None or when(ctx.params): + state = ctx.find_object(AppState) + assert state is not None + state.confirm_protected(f"run '{ctx.command_path}'", confirm_context) + return f(*args, **kwargs) + + return confirm_context_option(wrapper) # type: ignore[return-value] + + return decorator + + +class Duration(click.ParamType): + """``30s``, ``2m``, ``500ms``, or plain seconds; converted to seconds.""" + + name = "DURATION" + + def convert(self, value: Any, param: click.Parameter | None, ctx: click.Context | None) -> float: + if isinstance(value, float | int): + return float(value) + try: + return duration_seconds(value) + except DittoctlError as e: + self.fail(str(e), param, ctx) + + +def all_option(f: F) -> F: + return click.option( + "--all", + "all_items", + is_flag=True, + help="Don't limit the output (agent mode shows the first 50 by default).", + )(f) + + +def duration_option(what: str) -> Callable[[F], F]: + return click.option( + "--duration", + type=Duration(), + help=f"Stop {what} after this long, e.g. 30s or 5m; 0 never stops (default; agent mode: 30s).", + ) diff --git a/src/dittoctl/cli/output.py b/src/dittoctl/cli/output.py new file mode 100644 index 0000000..d5fbb94 --- /dev/null +++ b/src/dittoctl/cli/output.py @@ -0,0 +1,156 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +"""Terminal output. Data goes to stdout, everything else (progress, hints, errors) to stderr.""" + +from __future__ import annotations + +import json +import os +import sys +from typing import Any + +import click +from rich.console import Console +from rich.markup import escape + +from dittoctl.errors import DittoctlError, DittoError +from dittoctl.formats import json_writer + +DATA_FORMATS = ("json", "ndjson", "raw") +# set by AI coding agents in the environment of the commands they run (Claude Code sets both) +AGENT_ENV_VARS = ("CLAUDECODE", "AI_AGENT") +COMPACT = (",", ":") +# in agent mode, results on stdout are limited to this many items unless --limit or --all is given +AGENT_LIMIT = 50 +# and streams (watch, follow) stop after this many seconds unless --duration is given +AGENT_DURATION = 30.0 + +_agent = False + + +def detect_agent() -> bool: + """Whether dittoctl runs under an AI agent, judging by the environment.""" + return any(os.environ.get(name, "") not in ("", "0", "false") for name in AGENT_ENV_VARS) + + +def set_agent_mode(enabled: bool | None) -> None: + """Agent mode: compact JSON, errors as JSON, bounded output. ``None`` detects it from the environment.""" + global _agent + _agent = detect_agent() if enabled is None else enabled + + +def agent_mode() -> bool: + return _agent + + +def agent_limit(limit: int | None, all_items: bool, *, to_file: bool = False) -> int | None: + """The limit agents get when they set none, so that a result doesn't flood their context.""" + return AGENT_LIMIT if _agent and limit is None and not all_items and not to_file else None + + +def agent_duration(duration: float | None, max_items: int | None = None) -> float | None: + """The duration of a stream: --duration (0 = unlimited), else in agent mode a default.""" + if duration is not None: + return duration or None + return AGENT_DURATION if _agent and max_items is None else None + + +def more_results(what: str, limit: int, hint: str) -> None: + info(f"Showing the first {limit} {what}; there are more (agent mode limits output). {hint}") + + +def dumps(data: Any) -> str: + """One line of JSON, as written to NDJSON output.""" + return json.dumps(data, ensure_ascii=False, separators=COMPACT) + + +def line(data: Any) -> None: + """Write one NDJSON line to stdout (highlighted on a terminal).""" + json_writer(sys.stdout)(dumps(data) + "\n") + sys.stdout.flush() + + +def _stdout() -> Console: + # created per call so that click's CliRunner (which swaps sys.stdout) captures the output + return Console(emoji=False, file=sys.stdout, soft_wrap=True) + + +def _stderr() -> Console: + return Console(emoji=False, file=sys.stderr, soft_wrap=True) + + +def info(message: str) -> None: + _stderr().print(escape(message), highlight=False) + + +def debug(message: str) -> None: + _stderr().print(escape(message), style="dim", highlight=False) + + +def warn(message: str) -> None: + _stderr().print(f"[yellow]Warning:[/] {escape(message)}", highlight=False) + + +def emit(data: Any, fmt: str = "json", *, text: bool = False) -> None: + """Write data to stdout: pretty JSON on a terminal, indented JSON when piped (single-line for agents). + + ``text`` marks data that is plain text (a non-JSON response body), which is written as is. + """ + if text or fmt == "raw": + click.echo(data if isinstance(data, str) else json.dumps(data, ensure_ascii=False)) + elif fmt == "ndjson": + items = data if isinstance(data, list) else [data] + for item in items: + line(item) + elif sys.stdout.isatty(): + _stdout().print_json(data=data) + elif _agent: + click.echo(dumps(data)) + else: + click.echo(json.dumps(data, indent=2, ensure_ascii=False)) + + +def error_json(exit_code: int, message: str, **fields: Any) -> None: + """An error as one line of JSON on stderr, for agents: ``{"exitCode": 4, "message": ..., ...}``.""" + body = {"exitCode": int(exit_code), "message": message, **{k: v for k, v in fields.items() if v is not None}} + click.echo(dumps(body), err=True) + + +def error(exc: DittoctlError) -> None: + if _agent: + if isinstance(exc, DittoError): + error_json( + exc.exit_code, + exc.message or str(exc), + status=exc.status, + error=exc.error, + description=exc.description, + href=exc.href, + correlationId=exc.correlation_id, + ) + else: + error_json(exc.exit_code, str(exc)) + return + console = _stderr() + console.print(f"[bold red]Error:[/] {escape(str(exc))}", highlight=False) + if isinstance(exc, DittoError): + if exc.description: + console.print(f" {escape(exc.description)}", highlight=False) + if exc.href: + console.print(f" See {escape(exc.href)}", style="dim", highlight=False) + if exc.correlation_id: + console.print(f" correlation-id: {escape(exc.correlation_id)}", style="dim", highlight=False) diff --git a/src/dittoctl/cli/policies_cmd.py b/src/dittoctl/cli/policies_cmd.py new file mode 100644 index 0000000..5ecade3 --- /dev/null +++ b/src/dittoctl/cli/policies_cmd.py @@ -0,0 +1,452 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +"""``dittoctl policies``: policies, entries, subjects, imports, permission checks and actions.""" + +from __future__ import annotations + +import re +import sys +from typing import Any + +import click +from rich.console import Console +from rich.table import Table + +from dittoctl.cli import output +from dittoctl.cli.bulk_options import WriteOptions, confirm, execute, read_json, write_options +from dittoctl.cli.options import all_option, conditional_options, output_option, pop_conditions, protected_write +from dittoctl.cli.state import AppState, pass_state +from dittoctl.cli.things_cmd import resolve_filter, resolve_namespaces +from dittoctl.core.policies import ( + check_permissions, + lockout_params, + policy_ids_of_things, + policy_path, + subject_migration_operation, +) +from dittoctl.core.selectors import read_ids_file, unique +from dittoctl.errors import AbortedError, CheckFailedError + +allow_lockout_option = click.option( + "--allow-lockout", + is_flag=True, + help="Allow a change that removes your own WRITE permission on the policy (Ditto refuses it otherwise).", +) + + +@click.group("policies") +def policies_group() -> None: + """Read and change policies: entries, subjects, imports; check permissions; migrate subjects in bulk.""" + + +@policies_group.command("get") +@click.argument("policy_id") +@click.option("--resolved", is_flag=True, help="Show the effective policy with imports resolved (Ditto 3.9+).") +@click.option("--path", help="Only this part, e.g. entries/owner or imports.") +@output_option(("json", "ndjson"), "json") +@conditional_options +@pass_state +def get(state: AppState, policy_id: str, resolved: bool, path: str | None, output_format: str, **kwargs: Any) -> None: + """Retrieve a policy.""" + conditions = pop_conditions(kwargs) + params = {"policy-view": "resolved"} if resolved else None + segments = [s for s in (path or "").split("/") if s] + response = state.client().get(policy_path(policy_id, *segments), params=params, conditions=conditions) + if response.status == 304: + output.info("Not modified (the ETag matches).") + return + output.emit(response.body, output_format) + + +@policies_group.command("put") +@click.argument("policy_id") +@click.option("-d", "--data", required=True, metavar="JSON|@FILE|@-", help="The complete policy JSON.") +@allow_lockout_option +@conditional_options +@protected_write() +@pass_state +def put(state: AppState, policy_id: str, data: str, allow_lockout: bool, **kwargs: Any) -> None: + """Create or completely replace a policy.""" + conditions = pop_conditions(kwargs) + response = state.client().put( + policy_path(policy_id), json=read_json(data), conditions=conditions, params=lockout_params(allow_lockout) + ) + output.info(f"{'Created' if response.status == 201 else 'Replaced'} policy {policy_id}.") + + +@policies_group.command("delete") +@click.argument("policy_id") +@click.option("-y", "--yes", is_flag=True, help="Don't ask for confirmation.") +@protected_write() +@pass_state +def delete(state: AppState, policy_id: str, yes: bool) -> None: + """Delete a policy. Things that still use it become inaccessible.""" + if not yes: + if not sys.stdin.isatty(): + raise AbortedError("refusing to delete a policy without --yes when not interactive") + if not click.confirm(f"Delete policy {policy_id}? Things using it become inaccessible", default=False): + raise AbortedError("not confirmed") + state.client().delete(policy_path(policy_id)) + output.info(f"Deleted policy {policy_id}.") + + +@policies_group.command("list") +@click.option("-f", "--filter", "rql_filter", metavar="RQL", help="Filter on things; @file reads it.") +@click.option("--no-validate", is_flag=True, help="Send the filter without checking it locally first.") +@click.option("-n", "--namespaces", multiple=True, metavar="NS[,NS]", help="Namespaces of the things.") +@all_option +@pass_state +def list_( + state: AppState, rql_filter: str | None, no_validate: bool, namespaces: tuple[str, ...], all_items: bool +) -> None: + """List the distinct policy ids of the things matching a filter. + + Ditto can't search policies directly, so they are found via the things using them. + + \b + Example: + dittoctl policies list -f 'like(policyId,"org.example:customer-*")' > policies.txt + """ + ids = policy_ids_of_things( + state.client(), + rql_filter=resolve_filter(rql_filter, not no_validate), + namespaces=resolve_namespaces(state, namespaces), + ) + shown = output.agent_limit(None, all_items) or len(ids) + for policy_id in ids[:shown]: + click.echo(policy_id) + output.info(f"{len(ids)} policies.") + if len(ids) > shown: + output.more_results("policies", shown, "Narrow the filter or use --all.") + + +# --- entries ---------------------------------------------------------------------------------- + + +@policies_group.group("entries") +def entries_group() -> None: + """Policy entries: who (subjects) may do what (resources).""" + + +@entries_group.command("list") +@click.argument("policy_id") +@pass_state +def entries_list(state: AppState, policy_id: str) -> None: + """Show the entries of a policy as a table.""" + entries = state.client().get(policy_path(policy_id, "entries")).body or {} + table = Table(box=None, pad_edge=False, header_style="bold") + for column in ("LABEL", "SUBJECTS", "RESOURCES"): + table.add_column(column, overflow="fold") + for label, entry in entries.items(): + resources = [ + f"{resource} {'+' + ','.join(grants['grant']) if grants.get('grant') else ''}" + f"{' -' + ','.join(grants['revoke']) if grants.get('revoke') else ''}".strip() + for resource, grants in entry.get("resources", {}).items() + ] + table.add_row(label, "\n".join(entry.get("subjects", {})), "\n".join(resources)) + Console(emoji=False, markup=False, file=sys.stdout, width=None if sys.stdout.isatty() else 200).print(table) + + +@entries_group.command("get") +@click.argument("policy_id") +@click.argument("label") +@pass_state +def entries_get(state: AppState, policy_id: str, label: str) -> None: + """Retrieve one entry.""" + output.emit(state.client().get(policy_path(policy_id, "entries", label)).body) + + +@entries_group.command("put") +@click.argument("policy_id") +@click.argument("label") +@click.option("-d", "--data", required=True, metavar="JSON|@FILE|@-", help="The entry: subjects and resources.") +@allow_lockout_option +@conditional_options +@protected_write() +@pass_state +def entries_put(state: AppState, policy_id: str, label: str, data: str, allow_lockout: bool, **kwargs: Any) -> None: + """Create or replace one entry.""" + conditions = pop_conditions(kwargs) + state.client().put( + policy_path(policy_id, "entries", label), + json=read_json(data), + conditions=conditions, + params=lockout_params(allow_lockout), + ) + output.info(f"Entry {label} of {policy_id} saved.") + + +@entries_group.command("delete") +@click.argument("policy_id") +@click.argument("label") +@allow_lockout_option +@protected_write() +@pass_state +def entries_delete(state: AppState, policy_id: str, label: str, allow_lockout: bool) -> None: + """Delete one entry.""" + state.client().delete(policy_path(policy_id, "entries", label), params=lockout_params(allow_lockout)) + output.info(f"Entry {label} of {policy_id} deleted.") + + +# --- subjects --------------------------------------------------------------------------------- + + +@policies_group.group("subjects") +def subjects_group() -> None: + """Subjects of policy entries: add, remove, and migrate them across many policies.""" + + +@subjects_group.command("add") +@click.argument("policy_id") +@click.argument("label") +@click.argument("subject_id") +@click.option("--type", "subject_type", default="added by dittoctl", show_default=True, help="Subject type.") +@click.option("--expiring-at", metavar="TIMESTAMP", help="ISO-8601 time after which Ditto removes the subject.") +@protected_write() +@pass_state +def subjects_add( + state: AppState, policy_id: str, label: str, subject_id: str, subject_type: str, expiring_at: str | None +) -> None: + """Add (or update) a subject of an entry, such as 'integration:my-app' or 'nginx:alice'.""" + body: dict[str, Any] = {"type": subject_type} + if expiring_at: + body["expiry"] = expiring_at + state.client().put(policy_path(policy_id, "entries", label, "subjects", subject_id), json=body) + output.info(f"Subject {subject_id} saved in {policy_id}/{label}.") + + +@subjects_group.command("remove") +@click.argument("policy_id") +@click.argument("label") +@click.argument("subject_id") +@allow_lockout_option +@protected_write() +@pass_state +def subjects_remove(state: AppState, policy_id: str, label: str, subject_id: str, allow_lockout: bool) -> None: + """Remove a subject from an entry.""" + state.client().delete( + policy_path(policy_id, "entries", label, "subjects", subject_id), params=lockout_params(allow_lockout) + ) + output.info(f"Subject {subject_id} removed from {policy_id}/{label}.") + + +@subjects_group.command("migrate") +@click.argument("policy_ids", nargs=-1, metavar="[POLICY_ID]...") +@click.option("--ids-file", metavar="FILE", help="Policy ids, one per line; - reads stdin.") +@click.option("-f", "--filter", "rql_filter", metavar="RQL", help="Migrate the policies of the things matching this.") +@click.option("--no-validate", is_flag=True, help="Send the filter without checking it locally first.") +@click.option("-n", "--namespaces", multiple=True, metavar="NS[,NS]", help="Namespaces of the things for --filter.") +@click.option("--match", "match", required=True, metavar="REGEX", help="Subject ids to migrate (full match).") +@click.option( + "--template", + required=True, + metavar="TEMPLATE", + help=r"The new subject id; \1 or \g insert groups of --match.", +) +@click.option("--label", "labels", multiple=True, help="Only in entries with this label. Repeatable.") +@click.option("--remove-old", is_flag=True, help="Replace the matching subjects instead of adding next to them.") +@click.option( + "--conflict-retries", + type=click.IntRange(min=0), + default=3, + show_default=True, + help="How often to re-read and retry when a policy was changed concurrently.", +) +@allow_lockout_option +@write_options +@pass_state +def subjects_migrate( + state: AppState, + policy_ids: tuple[str, ...], + ids_file: str | None, + rql_filter: str | None, + no_validate: bool, + namespaces: tuple[str, ...], + match: str, + template: str, + labels: tuple[str, ...], + remove_old: bool, + conflict_retries: int, + allow_lockout: bool, + **kwargs: Any, +) -> None: + """Add a new subject next to (or instead of) every subject matching --match, with the same permissions. + + Typical when switching identity providers: users keep their permissions under their new subject ids. Each + policy is written atomically with If-Match; running the migration again changes nothing. + + \b + Example (add a twin subject for every user of an old IdP, keep the old one for now): + dittoctl policies subjects migrate -f 'like(policyId,"org.example:customer-*")' \\ + --match 'oldidp:(?P[0-9a-f-]{36})' --template 'newidp:fed-sub:\\g' --dry-run + """ + options = WriteOptions.pop(kwargs) + try: + pattern = re.compile(match) + except re.error as e: + raise click.BadParameter(str(e), param_hint="--match") from None + if bool(policy_ids or ids_file) == bool(rql_filter): + raise click.UsageError("select policies either by id (arguments, --ids-file) or by --filter on things") + if rql_filter: + ids = policy_ids_of_things( + state.client(), + rql_filter=resolve_filter(rql_filter, not no_validate), + namespaces=resolve_namespaces(state, namespaces), + ) + else: + ids = unique([*policy_ids, *(read_ids_file(ids_file) if ids_file else [])]) + output.info(f"Selected {len(ids)} policies.") + confirm(state, len(ids), options, "migrate subjects of") + + def show(outcome: Any) -> None: + if outcome.detail and not options.dry_run: + for change in outcome.detail: + output.debug(f"{outcome.thing_id}: {change}") + + operation = subject_migration_operation( + state.client(), + pattern, + template, + labels=set(labels) or None, + remove_old=remove_old, + allow_lockout=allow_lockout, + conflict_retries=conflict_retries, + dry_run=options.dry_run, + ) + execute( + state, ids, operation, options, "migrate subjects", on_outcome=show if state.verbose else None, noun="policies" + ) + + +# --- imports ---------------------------------------------------------------------------------- + + +@policies_group.group("imports") +def imports_group() -> None: + """Policy imports: reuse entries of other policies.""" + + +@imports_group.command("list") +@click.argument("policy_id") +@pass_state +def imports_list(state: AppState, policy_id: str) -> None: + """Show the imports of a policy.""" + output.emit(state.client().get(policy_path(policy_id, "imports")).body or {}) + + +@imports_group.command("add") +@click.argument("policy_id") +@click.argument("imported_policy_id") +@click.option( + "--entry", + "entries", + multiple=True, + metavar="LABEL", + help="Import only this entry (it must be importable). Repeatable; default: all implicit ones.", +) +@protected_write() +@pass_state +def imports_add(state: AppState, policy_id: str, imported_policy_id: str, entries: tuple[str, ...]) -> None: + """Import the entries of another policy.""" + body = {"entries": list(entries)} if entries else {} + state.client().put(policy_path(policy_id, "imports", imported_policy_id), json=body) + output.info(f"{policy_id} imports {imported_policy_id}.") + + +@imports_group.command("remove") +@click.argument("policy_id") +@click.argument("imported_policy_id") +@protected_write() +@pass_state +def imports_remove(state: AppState, policy_id: str, imported_policy_id: str) -> None: + """Remove an import.""" + state.client().delete(policy_path(policy_id, "imports", imported_policy_id)) + output.info(f"{policy_id} no longer imports {imported_policy_id}.") + + +# --- permissions and actions ------------------------------------------------------------------ + + +@policies_group.command("check") +@click.argument("entity_id") +@click.option( + "--resource", + "resources", + multiple=True, + required=True, + metavar="RESOURCE", + help="E.g. thing:/attributes/location, thing:/features/temp, policy:/, message:/. Repeatable.", +) +@click.option( + "--permission", + "permissions", + multiple=True, + type=click.Choice(["READ", "WRITE"]), + default=("READ",), + show_default=True, + help="Permissions to check. Repeatable.", +) +@click.pass_context +def check(ctx: click.Context, entity_id: str, resources: tuple[str, ...], permissions: tuple[str, ...]) -> None: + """Check which of the given resources of a thing or policy you may access (Ditto 3.7+). + + Exit code 6 if any check is denied. + + \b + Example: + dittoctl policies check org.example:sensor-1 --resource thing:/attributes --resource thing:/features/temp \\ + --permission READ --permission WRITE + """ + state = ctx.find_object(AppState) + assert state is not None + checks = { + resource: {"resource": resource, "entityId": entity_id, "hasPermissions": list(permissions)} + for resource in resources + } + results = check_permissions(state.client(), checks) + for resource in resources: + allowed = results.get(resource) + click.echo(f"{'allowed' if allowed else 'denied ':8} {resource} ({'+'.join(permissions)})") + denied = [r for r in resources if not results.get(r)] + if denied: + raise CheckFailedError(f"{len(denied)} of {len(resources)} resource(s) denied") + + +def _token_integration(activate: bool) -> Any: + action = "activateTokenIntegration" if activate else "deactivateTokenIntegration" + name = "activate-token-integration" if activate else "deactivate-token-integration" + + @policies_group.command(name) + @click.argument("policy_id") + @click.option("--label", help="Only this entry (default: all entries you may execute it on).") + @protected_write() + @pass_state + def command(state: AppState, policy_id: str, label: str | None) -> None: + segments = ("entries", label, "actions", action) if label else ("actions", action) + state.client().post(policy_path(policy_id, *segments)) + output.info(f"{action} done for {policy_id}{'/' + label if label else ''}.") + + command.help = ( + f"{'Add' if activate else 'Remove'} the subject derived from your token " + f"{'to' if activate else 'from'} the policy's entries (needs EXECUTE permission on the action and a " + "token-based login; the subject expires with the token)." + ) + return command + + +_token_integration(activate=True) +_token_integration(activate=False) diff --git a/src/dittoctl/cli/rql_cmd.py b/src/dittoctl/cli/rql_cmd.py new file mode 100644 index 0000000..be85a02 --- /dev/null +++ b/src/dittoctl/cli/rql_cmd.py @@ -0,0 +1,57 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +"""``dittoctl rql``: check and format RQL filters offline.""" + +from __future__ import annotations + +import click + +from dittoctl.cli import output +from dittoctl.cli.api_cmd import read_data +from dittoctl.core import rql +from dittoctl.errors import CheckFailedError, DittoctlError + + +def _parse(expression: str, error: type[DittoctlError] = DittoctlError) -> rql.Node: + try: + return rql.parse(read_data(expression)) + except rql.RqlError as e: + raise error("invalid RQL: " + e.render()) from None + + +@click.group("rql") +def rql_group() -> None: + """Check and format RQL filter expressions, without contacting Ditto.""" + + +@rql_group.command("lint") +@click.argument("expression", metavar="EXPRESSION|@FILE|@-") +def lint(expression: str) -> None: + """Check an RQL filter; on error, show where it is. Exit code 6 if invalid.""" + node = _parse(expression, CheckFailedError) + for warning in rql.warnings(node): + output.warn(warning) + output.info("valid") + + +@rql_group.command("fmt") +@click.argument("expression", metavar="EXPRESSION|@FILE|@-") +@click.option("--compact", is_flag=True, help="Single line without whitespace (the form sent to Ditto).") +def fmt(expression: str, compact: bool) -> None: + """Pretty-print an RQL filter, one condition per line.""" + node = _parse(expression) + click.echo(rql.compact(node) if compact else rql.pretty(node)) diff --git a/src/dittoctl/cli/state.py b/src/dittoctl/cli/state.py new file mode 100644 index 0000000..f8b09f1 --- /dev/null +++ b/src/dittoctl/cli/state.py @@ -0,0 +1,134 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +"""Per-invocation state shared by all commands: global options, config, context and client.""" + +from __future__ import annotations + +import os +import sys +from dataclasses import dataclass, field +from pathlib import Path + +import click +import httpx + +from dittoctl.auth import AuthProvider, provider_for +from dittoctl.auth.store import SecretStore, default_store +from dittoctl.cli import output +from dittoctl.config import AuthConfig, Config, Context +from dittoctl.core.client import DittoClient +from dittoctl.core.curl import redact, to_curl +from dittoctl.errors import AbortedError + +ADHOC_CONTEXT = "(url)" + + +@dataclass +class AppState: + context_name: str | None = None + url: str | None = None + verbose: int = 0 + extra_headers: dict[str, str] = field(default_factory=dict) + timeout: float | None = None + correlation_id: str | None = None + config_path: Path | None = None + + _config: Config | None = None + _store: SecretStore | None = None + _client: DittoClient | None = None + _protected_confirmed: bool = False + + def config(self) -> Config: + if self._config is None: + self._config = Config.load(self.config_path) + return self._config + + def store(self) -> SecretStore: + if self._store is None: + self._store = default_store() + return self._store + + def context(self) -> Context: + """The selected context. ``--url`` without a context gives an ad-hoc context authenticated from env vars.""" + if self.url and not self.context_name: + return Context(name=ADHOC_CONTEXT, url=self.url.rstrip("/"), auth=_auth_from_env()) + context = self.config().get_context(self.context_name) + if self.url: + context.url = self.url.rstrip("/") + return context + + def auth(self, context: Context | None = None) -> AuthProvider: + return provider_for(context or self.context(), self.store(), notify=output.info) + + def client(self) -> DittoClient: + if self._client is None: + context = self.context() + self._client = DittoClient( + context.url, + self.auth(context), + headers={**context.headers, **self.extra_headers}, + timeout=self.timeout or context.timeout, + verify=context.verify, + correlation_id=self.correlation_id, + on_request=self._log_request if self.verbose else None, + on_response=self._log_response if self.verbose > 1 else None, + ) + return self._client + + def confirm_protected(self, action: str, confirm_context: str | None = None) -> None: + """Writes to a protected context need its name confirmed: typed at the prompt, or as --confirm-context. + + Under an AI agent (agent mode) they are refused: a person should run such commands. Raises AbortedError. + """ + context = self.context() + if not context.protected or self._protected_confirmed: + return + name = context.name + if output.agent_mode(): + raise AbortedError( + f"context '{name}' is protected, and dittoctl doesn't write to protected contexts in agent mode. " + "Ask the user to run this command; --dry-run shows what it would do" + ) + if confirm_context != name: + if confirm_context is not None or not sys.stdin.isatty(): + raise AbortedError(f"context '{name}' is protected: confirm with --confirm-context {name}") + if click.prompt(f"Context '{name}' is protected. Type its name to {action}") != name: + raise AbortedError("context name not confirmed") + self._protected_confirmed = True + + def close(self) -> None: + if self._client is not None: + self._client.close() + + def _log_request(self, request: httpx.Request) -> None: + output.debug(to_curl(request)) + + def _log_response(self, response: httpx.Response) -> None: + lines = [f"< {response.status_code} {response.reason_phrase}"] + lines += [f"< {name}: {redact(name, value)}" for name, value in response.headers.items()] + output.debug("\n".join(lines)) + + +def _auth_from_env() -> AuthConfig: + if os.environ.get("DITTOCTL_TOKEN"): + return AuthConfig(method="token") + if username := os.environ.get("DITTOCTL_USERNAME"): + return AuthConfig(method="basic", username=username) + return AuthConfig(method="none") + + +pass_state = click.make_pass_decorator(AppState) diff --git a/src/dittoctl/cli/things_cmd.py b/src/dittoctl/cli/things_cmd.py new file mode 100644 index 0000000..ac17252 --- /dev/null +++ b/src/dittoctl/cli/things_cmd.py @@ -0,0 +1,645 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +"""``dittoctl things``: read, search, count, export and watch things.""" + +from __future__ import annotations + +import sys +from collections.abc import Callable, Iterable, Iterator +from contextlib import contextmanager, suppress +from typing import Any, TextIO, TypeVar + +import click +from rich.console import Console +from rich.progress import BarColumn, MofNCompleteColumn, Progress, TextColumn, TimeElapsedColumn + +from dittoctl.cli import output +from dittoctl.cli.api_cmd import read_data +from dittoctl.cli.options import all_option, conditional_options, duration_option, pop_conditions +from dittoctl.cli.state import AppState, pass_state +from dittoctl.core import rql +from dittoctl.core.fields import field_stats +from dittoctl.core.search import MAX_PAGE_SIZE, Transport, count_things, find_things +from dittoctl.core.streams import Limited, Timeboxed +from dittoctl.core.things import get_thing, get_things, thing_description, thing_history, watch_things +from dittoctl.core.wot import compact_thing_description, thing_description_with_features +from dittoctl.formats import ITEM_FORMATS, Columns, write_items, write_ndjson + +F = TypeVar("F", bound=Callable[..., Any]) + + +# --- shared options --------------------------------------------------------------------------- + + +def filter_options(f: F) -> F: + f = click.option("--no-validate", is_flag=True, help="Send the filter as is, without checking it locally first.")(f) + f = click.option("-f", "--filter", "rql_filter", metavar="RQL", help="RQL filter; @file reads it from a file.")(f) + return f + + +def namespaces_option(f: F) -> F: + return click.option( + "-n", + "--namespaces", + multiple=True, + metavar="NS[,NS]", + help="Namespaces to search in (default: the context's namespaces, else all). Repeatable.", + )(f) + + +def resolve_filter(value: str | None, validate: bool) -> str | None: + if not value: + return None + text = read_data(value).strip() + if not validate: + return text + try: + node = rql.parse(text) + except rql.RqlError as e: + raise click.BadParameter("\n" + e.render(), param_hint="--filter") from None + for warning in rql.warnings(node): + output.warn(warning) + return rql.compact(node) + + +def resolve_namespaces(state: AppState, values: tuple[str, ...]) -> list[str]: + namespaces = [ns.strip() for value in values for ns in value.split(",") if ns.strip()] + return namespaces or state.context().namespaces + + +def transport_option(f: F) -> F: + return click.option( + "--transport", + type=click.Choice([t.value for t in Transport]), + default=Transport.AUTO.value, + show_default=True, + help="How results are fetched: 'paging' through the search cursor, or Ditto's SSE search 'sse' stream. " + "'auto' streams when only thing ids are needed (-o ids) and the context allows it, else it pages.", + )(f) + + +def effective_fields(fields: str | None, output_format: str | None) -> str | None: + """With ``-o ids`` and no explicit fields, only the thing id is fetched.""" + return "thingId" if fields is None and output_format == "ids" else fields + + +def tabular_options(f: F) -> F: + options = [ + click.option("--columns", metavar="PATH[,PATH]", help="Fixed columns (paths like attributes/location)."), + click.option( + "--discover-rows", + type=int, + default=100, + show_default=True, + help="Rows to inspect for column discovery; 0 inspects all (buffers the whole result).", + ), + click.option("--short-headers", is_flag=True, help="Use the shortest unambiguous path suffix as header."), + click.option("--delimiter", default=",", show_default=True, help="CSV delimiter."), + click.option("--no-header", is_flag=True, help="Leave out the CSV header row."), + click.option( + "--excel", is_flag=True, help="CSV for Excel: UTF-8 BOM, timestamps as 'YYYY-MM-DD HH:MM:SS' (UTC)." + ), + click.option( + "--out", + type=click.Path(dir_okay=False, writable=True, allow_dash=True), + help="Write to this file instead of stdout.", + ), + ] + for option in reversed(options): + f = option(f) + return f + + +@contextmanager +def open_output(path: str | None, excel: bool) -> Iterator[TextIO]: + if path and path != "-": + with open(path, "w", encoding="utf-8-sig" if excel else "utf-8", newline="") as f: + yield f + return + if excel: + sys.stdout.write("") + yield sys.stdout + + +def emit_items(items: Iterable[Any], fmt: str, opts: dict[str, Any]) -> int: + columns = Columns( + explicit=[c.strip() for c in opts["columns"].split(",") if c.strip()] if opts.get("columns") else None, + discover_rows=opts.get("discover_rows", 100), + short=opts.get("short_headers", False), + ) + with open_output(opts.get("out"), opts.get("excel", False) and fmt == "csv") as out: + return write_items( + items, + fmt, + out, + columns=columns, + delimiter=opts.get("delimiter", ","), + header=not opts.get("no_header", False), + excel=opts.get("excel", False), + compact=output.agent_mode(), + warn=output.warn, + ) + + +def _default_format(opts: dict[str, Any]) -> str: + to_terminal = not opts.get("out") or opts["out"] == "-" + return "table" if to_terminal and sys.stdout.isatty() else "ndjson" + + +# --- commands --------------------------------------------------------------------------------- + + +@click.group("things") +def things_group() -> None: + """Read, search, count, export and watch things.""" + + +@things_group.command("get") +@click.argument("thing_ids", nargs=-1, required=True, metavar="THING_ID...") +@click.option("--path", help="Only this part of the thing, e.g. attributes/location or features/temp/properties.") +@click.option("--fields", help="Field selector, e.g. thingId,attributes/location,features/temp/properties/value.") +@click.option("--at-revision", type=int, help="Read the thing as it was at this revision (needs Ditto history).") +@click.option("--at-time", metavar="TIMESTAMP", help="Read the thing as it was at this ISO-8601 time.") +@click.option( + "--live", + is_flag=True, + help="Ask the device (live channel) instead of the twin; see --live-condition, --live-timeout-strategy.", +) +@click.option( + "--live-timeout", + type=click.IntRange(1, 60), + metavar="SECONDS", + help="With --live: how long to wait for the device (Ditto's default: 10s).", +) +@click.option( + "-o", + "--output", + "output_format", + type=click.Choice(("json", "table", "ndjson", "csv")), + default="json", + show_default=True, + help="Output format.", +) +@conditional_options +@pass_state +def get( + state: AppState, + thing_ids: tuple[str, ...], + path: str | None, + fields: str | None, + at_revision: int | None, + at_time: str | None, + live: bool, + live_timeout: int | None, + output_format: str, + **kwargs: Any, +) -> None: + """Retrieve one or more things. + + \b + Examples: + dittoctl things get org.example:sensor-1 + dittoctl things get org.example:sensor-1 --path attributes/location + dittoctl things get org.example:sensor-1 --at-revision 42 + dittoctl things get org.example:sensor-1 org.example:sensor-2 --fields thingId,attributes -o table + """ + conditions = pop_conditions(kwargs) + client = state.client() + if len(thing_ids) > 1: + if path or at_revision is not None or at_time or live or not conditions.is_empty(): + raise click.UsageError("--path, --at-revision, --at-time, --live and conditions need a single thing id") + count = emit_items(get_things(client, list(thing_ids), fields=fields), output_format, {}) + if count < len(thing_ids): + output.warn(f"{len(thing_ids) - count} of {len(thing_ids)} things were not found or not visible") + return + response = get_thing( + client, + thing_ids[0], + path=path, + fields=fields, + at_revision=at_revision, + at_timestamp=at_time, + live=live, + live_timeout=live_timeout, + conditions=conditions, + ) + if response.status == 304: + output.info("Not modified (the ETag matches).") + return + if output_format == "json": + output.emit(response.body) + else: + emit_items([response.body], output_format, {}) + + +@things_group.command("search") +@filter_options +@namespaces_option +@click.option("--fields", help="Field selector, e.g. thingId,attributes/location,_modified.") +@click.option("--sort", metavar="[+-]PATH[,...]", help="Sort order, e.g. -_modified or +attributes/name.") +@click.option("--limit", type=click.IntRange(min=1), help="Stop after this many things.") +@click.option( + "--page-size", + type=click.IntRange(1, MAX_PAGE_SIZE), + default=MAX_PAGE_SIZE, + show_default=True, + help="Things per request.", +) +@click.option( + "-o", + "--output", + "output_format", + type=click.Choice(ITEM_FORMATS), + help="Output format (default: table on a terminal, ndjson otherwise).", +) +@all_option +@transport_option +@tabular_options +@pass_state +def search( + state: AppState, + rql_filter: str | None, + no_validate: bool, + namespaces: tuple[str, ...], + fields: str | None, + sort: str | None, + limit: int | None, + page_size: int, + output_format: str | None, + all_items: bool, + transport: str, + **opts: Any, +) -> None: + """Search things with RQL, following the result cursor through all pages. + + \b + Examples: + dittoctl things search -f 'eq(attributes/manufacturer,"ACME")' --fields thingId,attributes + dittoctl things search -f 'gt(_modified,"2026-11-01T00:00:00Z")' --sort -_modified --limit 20 + dittoctl things search -n org.example -o ids > ids.txt + """ + output_format = output_format or _default_format(opts) + default_limit = output.agent_limit(limit, all_items, to_file=_to_file(opts)) + items: Iterable[Any] = find_things( + state.client(), + rql_filter=resolve_filter(rql_filter, not no_validate), + namespaces=resolve_namespaces(state, namespaces), + fields=effective_fields(fields, output_format), + sort=sort, + limit=default_limit + 1 if default_limit else limit, + page_size=page_size, + transport=Transport(transport), + streaming_allowed=state.context().search_streaming, + ) + if default_limit: + items = Limited(items, default_limit) + emit_items(items, output_format, opts) + if isinstance(items, Limited) and items.more: + output.more_results("things", items.limit, "Narrow the filter, use --limit N or --all, or 'things count'.") + + +def _to_file(opts: dict[str, Any]) -> bool: + return opts.get("out") not in (None, "-") + + +@things_group.command("export") +@filter_options +@namespaces_option +@click.option("--fields", help="Field selector, e.g. thingId,attributes,features/temp/properties.") +@click.option("--sort", metavar="[+-]PATH[,...]", help="Sort order, e.g. +thingId.") +@click.option("--limit", type=click.IntRange(min=1), help="Stop after this many things.") +@click.option( + "-o", + "--output", + "output_format", + type=click.Choice(("csv", "ndjson", "json", "ids")), + default="csv", + show_default=True, + help="Output format.", +) +@click.option("--no-progress", is_flag=True, help="Don't count the things first or show progress.") +@all_option +@transport_option +@tabular_options +@pass_state +def export( + state: AppState, + rql_filter: str | None, + no_validate: bool, + namespaces: tuple[str, ...], + fields: str | None, + sort: str | None, + limit: int | None, + output_format: str, + no_progress: bool, + all_items: bool, + transport: str, + **opts: Any, +) -> None: + """Export search results to a file, streaming: memory use stays flat regardless of the number of things. + + \b + Examples: + dittoctl things export -f 'exists(features/temp)' --fields thingId,features/temp/properties --out temp.csv + dittoctl things export -n org.example -o ndjson --out backup.ndjson + """ + client = state.client() + rql_filter = resolve_filter(rql_filter, not no_validate) + ns = resolve_namespaces(state, namespaces) + default_limit = output.agent_limit(limit, all_items, to_file=_to_file(opts)) + items: Iterable[Any] = find_things( + client, + rql_filter=rql_filter, + namespaces=ns, + fields=effective_fields(fields, output_format), + sort=sort, + limit=default_limit + 1 if default_limit else limit, + transport=Transport(transport), + streaming_allowed=state.context().search_streaming, + ) + if default_limit: + items = Limited(items, default_limit) + show_progress = not no_progress and sys.stderr.isatty() + if not show_progress: + count = emit_items(items, output_format, opts) + else: + total = count_things(client, rql_filter=rql_filter, namespaces=ns) + total = min(total, limit) if limit else total + progress = Progress( + TextColumn("Exporting"), + BarColumn(), + MofNCompleteColumn(), + TimeElapsedColumn(), + console=Console(emoji=False, file=sys.stderr), + transient=True, + ) + with progress: + task = progress.add_task("export", total=total) + + def tracked(source: Iterable[Any]) -> Iterator[Any]: + for item in source: + yield item + progress.advance(task) + + count = emit_items(tracked(items), output_format, opts) + target = opts.get("out") if _to_file(opts) else "stdout" + output.info(f"Exported {count} things to {target}.") + if isinstance(items, Limited) and items.more: + output.more_results("things", items.limit, "Export to a file with --out, or use --limit N or --all.") + + +@things_group.command("count") +@filter_options +@namespaces_option +@pass_state +def count(state: AppState, rql_filter: str | None, no_validate: bool, namespaces: tuple[str, ...]) -> None: + """Count the things matching an RQL filter.""" + total = count_things( + state.client(), + rql_filter=resolve_filter(rql_filter, not no_validate), + namespaces=resolve_namespaces(state, namespaces), + ) + click.echo(total) + + +@things_group.command("fields") +@filter_options +@namespaces_option +@click.option( + "--sample", + type=click.IntRange(1, 10_000), + default=100, + show_default=True, + help="How many matching things to inspect: the first ones Ditto returns, not a random sample.", +) +@click.option("--path", metavar="PATH", help="Only paths below this one, e.g. attributes or features/temp.") +@click.option( + "--examples", type=click.IntRange(0, 20), default=3, show_default=True, help="Distinct example values per path." +) +@click.option( + "-o", + "--output", + "output_format", + type=click.Choice(("table", "json", "ndjson", "csv")), + help="Output format (default: table on a terminal, ndjson otherwise).", +) +@pass_state +def fields( + state: AppState, + rql_filter: str | None, + no_validate: bool, + namespaces: tuple[str, ...], + sample: int, + path: str | None, + examples: int, + output_format: str | None, +) -> None: + """Show which paths the matching things have, with JSON types, frequency and example values. + + Ditto things are schemaless: this shows what to filter on (RQL) and which fields to select, also for + things without a WoT model (for those, see 'things td'). Each line has path, types, count, share (of the + inspected things) and examples. + + \b + Examples: + dittoctl things fields -n org.example + dittoctl things fields -f 'eq(attributes/model,"X1")' --path features --sample 500 + """ + things = find_things( + state.client(), + rql_filter=resolve_filter(rql_filter, not no_validate), + namespaces=resolve_namespaces(state, namespaces), + fields=path.strip("/") if path else None, + limit=sample, + ) + stats, total = field_stats(things, max_examples=examples) + output.info(f"Inspected {total} thing(s).") + rows = [s.to_json(total) for s in stats] + fmt = output_format or _default_format({}) + if fmt == "json": + output.emit(rows) + else: + emit_items(rows, fmt, {"columns": "path,types,count,share,examples"} if fmt in ("table", "csv") else {}) + + +@things_group.command("watch") +@filter_options +@namespaces_option +@click.option("--ids", metavar="ID[,ID]", help="Only these things.") +@click.option("--fields", help="Fields of each change to show (default: the changed parts).") +@click.option("--extra-fields", help="Unchanged fields to add to each change, e.g. attributes/location.") +@duration_option("watching") +@click.option("--max-events", type=click.IntRange(min=1), help="Stop after this many changes.") +@pass_state +def watch( + state: AppState, + rql_filter: str | None, + no_validate: bool, + namespaces: tuple[str, ...], + ids: str | None, + fields: str | None, + extra_fields: str | None, + duration: float | None, + max_events: int | None, +) -> None: + """Follow thing changes as they happen, one JSON object per line. Stop with Ctrl+C, --duration or --max-events. + + \b + Examples: + dittoctl things watch -n org.example + dittoctl things watch -f 'exists(features/temp)' --fields thingId,features/temp/properties/value + dittoctl things watch --ids org.example:sensor-1 --max-events 1 --duration 2m + """ + events = watch_things( + state.client(), + rql_filter=resolve_filter(rql_filter, not no_validate), + # the context's default namespaces would hide explicitly given things of other namespaces + namespaces=resolve_namespaces(state, namespaces) if namespaces or not ids else None, + thing_ids=[i.strip() for i in ids.split(",") if i.strip()] if ids else None, + fields=fields, + extra_fields=extra_fields, + ) + bounded = Timeboxed(events, duration=output.agent_duration(duration, max_events), max_items=max_events) + limits = [ + f"for {bounded.duration:g}s" if bounded.duration else "", + f"for {max_events} changes" if max_events else "", + ] + output.info(f"Watching for changes {' or '.join(x for x in limits if x) or 'until Ctrl+C'}.") + count = 0 + with suppress(KeyboardInterrupt): + count = write_ndjson(bounded, sys.stdout, flush=True) + if bounded.stopped == "duration": + output.info(f"Stopped after {bounded.duration:g}s with {count} change(s) (--duration).") + + +@things_group.command("history") +@click.argument("thing_id") +@click.option("--from-revision", type=int, help="First revision; negative counts back from the current one.") +@click.option("--to-revision", type=int, help="Last revision; 0 is the current one, negative counts back.") +@click.option("--from-time", metavar="TIMESTAMP", help="First point in time (ISO-8601).") +@click.option("--to-time", metavar="TIMESTAMP", help="Last point in time (ISO-8601).") +@click.option( + "--fields", + default="thingId,_revision,_modified,attributes,features", + show_default=True, + help="Fields of each change; add _context for the command that caused it.", +) +@click.option("-f", "--filter", "rql_filter", metavar="RQL", help="Only states matching this filter.") +@click.option("--limit", type=click.IntRange(min=1), help="Stop after this many changes.") +@all_option +@pass_state +def history( + state: AppState, + thing_id: str, + from_revision: int | None, + to_revision: int | None, + from_time: str | None, + to_time: str | None, + fields: str, + rql_filter: str | None, + limit: int | None, + all_items: bool, +) -> None: + """Show the changes of a thing per revision as NDJSON, oldest first (needs history retention in Ditto). + + Each line has the changed parts only, like 'things watch'; 'things get --at-revision N' shows the + complete thing at a revision. + + \b + Examples: + dittoctl things history org.example:sensor-1 --from-revision -10 + dittoctl things history org.example:sensor-1 --from-time 2026-11-01T00:00:00Z --to-time 2026-11-02T00:00:00Z + """ + if from_revision is None and from_time is None: + raise click.UsageError("pass --from-revision or --from-time") + if from_revision is not None and from_time is not None: + raise click.UsageError("use either revisions or times") + events = thing_history( + state.client(), + thing_id, + from_revision=from_revision, + to_revision=to_revision, + from_time=from_time, + to_time=to_time, + fields=fields, + rql_filter=resolve_filter(rql_filter, True), + ) + cap = limit or output.agent_limit(limit, all_items) + states: Iterable[Any] = Limited(events, cap) if cap else events + with suppress(KeyboardInterrupt): + write_ndjson(states, sys.stdout, flush=True) + if isinstance(states, Limited) and states.more and not limit: + output.more_results("changes", states.limit, "Narrow --from/--to, use --limit N or --all.") + + +@things_group.command("td") +@click.argument("thing_id") +@click.option("--feature", help="The Thing Description of this feature instead.") +@click.option( + "--with-features", + is_flag=True, + help="Add the Thing Descriptions of all the thing's features, under 'features'.", +) +@click.option( + "--compact", + is_flag=True, + help="Only titles, descriptions, data schemas and the path of each property, action and event; " + "single-line JSON when piped.", +) +@click.option( + "--no-schema-descriptions", + is_flag=True, + help="With --compact: leave out the descriptions inside data schemas (those of properties, actions and " + "events stay).", +) +@pass_state +def td( + state: AppState, + thing_id: str, + feature: str | None, + with_features: bool, + compact: bool, + no_schema_descriptions: bool, +) -> None: + """Show the WoT Thing Description Ditto generates from the thing's definition (a Thing Model URL). + + --compact leaves out what follows from Ditto's conventions (forms, security, error schemas) and + lists repeated parts once, which makes the description 2 to 12 times smaller, e.g. for an LLM. Paths + are relative to the thing, or to features/ for a feature's properties, actions and events. A + feature described exactly like an earlier one is shown as {"sameAs": ""}, a repeated data + schema as {"$ref": "#/"}. + + \b + Examples: + dittoctl things td org.example:lamp-1 + dittoctl things td org.example:lamp-1 --feature Spot1 + dittoctl things td org.example:lamp-1 --with-features --compact + """ + if feature and with_features: + raise click.UsageError("use either --feature or --with-features") + client = state.client() + if with_features: + description = thing_description_with_features(client, thing_id) + else: + description = thing_description(client, thing_id, feature) + if no_schema_descriptions and not compact: + raise click.UsageError("--no-schema-descriptions needs --compact") + if compact: + compacted = compact_thing_description(description, schema_descriptions=not no_schema_descriptions) + output.emit(compacted, "json" if sys.stdout.isatty() else "ndjson") + else: + output.emit(description) diff --git a/src/dittoctl/cli/things_write_cmd.py b/src/dittoctl/cli/things_write_cmd.py new file mode 100644 index 0000000..a2712b4 --- /dev/null +++ b/src/dittoctl/cli/things_write_cmd.py @@ -0,0 +1,605 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +"""Writing things: single-thing commands and bulk commands over a selection.""" + +from __future__ import annotations + +import difflib +import json +import sys +from typing import Any + +import click + +from dittoctl.cli import output +from dittoctl.cli.api_cmd import read_data +from dittoctl.cli.bulk_options import ( + WriteOptions, + confirm, + execute, + pop_selection, + read_json, + select, + selector_options, + write_options, +) +from dittoctl.cli.options import conditional_options, pop_conditions, protected_write +from dittoctl.cli.state import AppState, pass_state +from dittoctl.cli.things_cmd import things_group +from dittoctl.core.conditions import Conditions, IfEqual +from dittoctl.core.jsonops import ( + NO_CHANGE, + contains_array, + deep_equal, + equality, + json_diff, + merge_patch_diff, + nested, + segments, +) +from dittoctl.core.things import get_thing, get_things, thing_path +from dittoctl.core.writes import ( + array_operation, + delete_operation, + merge_operation, + migrate_definition_operation, + put_operation, +) +from dittoctl.errors import AbortedError, CheckFailedError, DittoctlError, DittoError +from dittoctl.formats.flatten import get_path + + +def _bulk_conditions(kwargs: dict[str, Any]) -> Conditions: + """Conditions of a bulk write; If-Equal defaults to 'skip' so that re-runs don't produce no-op events.""" + conditions = pop_conditions(kwargs) + return conditions if conditions.if_equal else conditions.replace(if_equal=IfEqual.SKIP) + + +def _check_stdin(selection_ids_file: str | None, *values: str | None) -> None: + if selection_ids_file == "-" and "@-" in values: + raise click.UsageError("stdin can't provide both the thing ids (--ids-file -) and the data (@-)") + + +# --- bulk writes ------------------------------------------------------------------------------ + + +@things_group.command("patch") +@click.argument("path") +@click.argument("thing_ids", nargs=-1, metavar="[THING_ID]...") +@click.option("-d", "--data", "data", required=True, metavar="JSON|@FILE|@-", help="The merge patch to apply.") +@click.option("--replace-array", is_flag=True, help="Allow arrays in the patch (they replace the whole array).") +@selector_options +@conditional_options +@write_options +@pass_state +def patch( + state: AppState, path: str, thing_ids: tuple[str, ...], data: str, replace_array: bool, **kwargs: Any +) -> None: + """Merge-patch (RFC 7396) a part of each selected thing; PATH '/' patches the whole thing. + + Unchanged values are skipped (--if-equal skip) unless --if-equal update is given. Things that don't + exist are reported as not-found; they are never created. + + \b + Examples: + dittoctl things patch attributes/location -d '{"room":"lab"}' org.example:sensor-1 + dittoctl things patch / -d @patch.json -f 'eq(attributes/model,"X1")' --dry-run + dittoctl things search -f 'exists(features/temp)' -o ids | dittoctl things patch features/temp/properties \\ + -d '{"unit":"°C"}' --ids-file - --yes + """ + options = WriteOptions.pop(kwargs) + conditions = _bulk_conditions(kwargs) + selection = pop_selection(state, thing_ids, kwargs) + _check_stdin(selection.ids_file, data) + body = read_json(data) + if contains_array(body) and not replace_array: + raise click.UsageError( + "the patch contains an array, and a merge patch replaces arrays as a whole, dropping existing items. " + "Use 'things array add|remove' to change items, or pass --replace-array if replacing is intended" + ) + if segments(path) == [] and not isinstance(body, dict): + raise click.UsageError("a patch of the whole thing must be a JSON object") + ids = select(state, selection) + confirm(state, len(ids), options, "patch") + execute( + state, ids, merge_operation(state.client(), path, body, conditions, dry_run=options.dry_run), options, "patch" + ) + + +@things_group.command("set") +@click.argument("path") +@click.argument("value") +@click.argument("thing_ids", nargs=-1, metavar="[THING_ID]...") +@click.option("--string", "as_string", is_flag=True, help="Treat VALUE as a string even if it is valid JSON.") +@selector_options +@conditional_options +@write_options +@pass_state +def set_(state: AppState, path: str, value: str, thing_ids: tuple[str, ...], as_string: bool, **kwargs: Any) -> None: + """Set the value at PATH of each selected thing, creating missing parents. + + VALUE is parsed as JSON if possible (42, true, {"a":1}), otherwise taken as a string. Things that don't + exist are reported as not-found; they are never created. + + \b + Examples: + dittoctl things set attributes/location/room lab org.example:sensor-1 + dittoctl things set features/config/properties/interval 60 -f 'eq(attributes/model,"X1")' + """ + if not segments(path): + raise click.UsageError("PATH must not be empty; use 'things patch /' to change the whole thing") + parsed: Any = value + if not as_string: + try: + parsed = json.loads(value) + except ValueError: + parsed = value + _merge_at_root(state, thing_ids, nested(path, parsed), "set", kwargs) + + +@things_group.command("unset") +@click.argument("path") +@click.argument("thing_ids", nargs=-1, metavar="[THING_ID]...") +@selector_options +@conditional_options +@write_options +@pass_state +def unset(state: AppState, path: str, thing_ids: tuple[str, ...], **kwargs: Any) -> None: + """Remove the value at PATH of each selected thing (absent values are fine, absent things are not-found). + + \b + Example: + dittoctl things unset attributes/obsolete -f 'exists(attributes/obsolete)' + """ + if not segments(path): + raise click.UsageError("PATH must not be empty; use 'things delete' to delete things") + _merge_at_root(state, thing_ids, nested(path, None), "unset", kwargs) + + +def _merge_at_root(state: AppState, thing_ids: tuple[str, ...], body: Any, action: str, kwargs: dict[str, Any]) -> None: + options = WriteOptions.pop(kwargs) + conditions = _bulk_conditions(kwargs) + ids = select(state, pop_selection(state, thing_ids, kwargs)) + confirm(state, len(ids), options, action) + execute( + state, ids, merge_operation(state.client(), "/", body, conditions, dry_run=options.dry_run), options, action + ) + + +@things_group.group("array") +def array_group() -> None: + """Add items to, or remove them from, an array in each selected thing, without losing concurrent changes.""" + + +def _array_command(remove: bool) -> Any: + name = "remove" if remove else "add" + as_set_option = ( + (lambda f: f) + if remove + else click.option("--as-set", is_flag=True, help="Only add items that aren't present yet.") + ) + + @array_group.command(name) + @click.argument("path") + @click.argument("thing_ids", nargs=-1, metavar="[THING_ID]...") + @click.option("--items", required=True, metavar="JSON|@FILE", help="A JSON array of the items.") + @as_set_option + @click.option( + "--compare", + type=click.Choice(["deep", "json"]), + default="deep", + show_default=True, + help="Item equality: 'deep' (1 equals 1.0) or 'json' (canonical text).", + ) + @click.option( + "--conflict-retries", + type=click.IntRange(min=0), + default=3, + show_default=True, + help="How often to re-read and retry when the array was changed concurrently.", + ) + @selector_options + @write_options + @pass_state + def command( + state: AppState, + path: str, + thing_ids: tuple[str, ...], + items: str, + compare: str, + conflict_retries: int, + as_set: bool = False, + **kwargs: Any, + ) -> None: + options = WriteOptions.pop(kwargs) + selection = pop_selection(state, thing_ids, kwargs) + _check_stdin(selection.ids_file, items) + values = read_json(items, "--items") + if not isinstance(values, list): + raise click.BadParameter("must be a JSON array", param_hint="--items") + ids = select(state, selection) + confirm(state, len(ids), options, f"{name} items for") + operation = array_operation( + state.client(), + path, + values, + remove=remove, + as_set=as_set, + equal=equality(compare), + conflict_retries=conflict_retries, + dry_run=options.dry_run, + ) + execute(state, ids, operation, options, f"array {name}") + + command.help = ( + f"{'Remove every occurrence of' if remove else 'Append'} the --items " + f"{'from' if remove else 'to'} the array at PATH of each selected thing.\n\n" + "Each array is read with its ETag and written with If-Match, so concurrent changes are never lost; " + "things whose array wouldn't change aren't written.\n\n" + "\b\nExample:\n" + f" dittoctl things array {name} attributes/tags --items '[\"maintenance\"]'" + f"{' --as-set' if not remove else ''} -f 'eq(attributes/building,\"B1\")'" + ) + return command + + +_array_command(remove=False) +_array_command(remove=True) + + +@things_group.command("delete") +@click.argument("thing_ids", nargs=-1, metavar="[THING_ID]...") +@selector_options +@conditional_options +@write_options +@pass_state +def delete(state: AppState, thing_ids: tuple[str, ...], **kwargs: Any) -> None: + """Delete the selected things. Their policies are kept. + + \b + Examples: + dittoctl things delete org.example:sensor-1 + dittoctl things delete -f 'eq(attributes/decommissioned,true)' --dry-run + """ + options = WriteOptions.pop(kwargs) + conditions = pop_conditions(kwargs) + ids = select(state, pop_selection(state, thing_ids, kwargs)) + confirm(state, len(ids), options, "delete", destructive=True) + execute(state, ids, delete_operation(state.client(), conditions, dry_run=options.dry_run), options, "delete") + + +def _read_things(source: str) -> dict[str, Any]: + """Things from NDJSON, a JSON array or a single JSON object, keyed by thingId.""" + text = read_data(source if source.startswith("@") else f"@{source}") + stripped = text.strip() + try: + if stripped.startswith("["): + items = json.loads(stripped) + elif stripped.startswith("{") and "\n{" not in stripped: + items = [json.loads(stripped)] + else: + items = [json.loads(line) for line in stripped.splitlines() if line.strip()] + except ValueError as e: + raise DittoctlError(f"cannot parse {source}: {e}") from None + things: dict[str, Any] = {} + for index, item in enumerate(items, 1): + if not isinstance(item, dict) or not isinstance(item.get("thingId"), str): + raise DittoctlError(f"{source}: item {index} is not a thing with a thingId") + things[item["thingId"]] = item + return things + + +@things_group.command("import") +@click.argument("source", metavar="FILE|-") +@click.option( + "--mode", + type=click.Choice(["create", "upsert"]), + default="create", + show_default=True, + help="'create' only creates things that don't exist; 'upsert' also replaces existing ones.", +) +@write_options +@pass_state +def import_(state: AppState, source: str, mode: str, **kwargs: Any) -> None: + """Create (or replace) things from NDJSON or a JSON array, such as a 'things export -o ndjson'. + + Each thing needs a thingId. Importing again is safe: existing things are reported as 'exists' (create) or + left alone when unchanged (upsert). + + \b + Examples: + dittoctl things export -n org.example -o ndjson --out backup.ndjson + dittoctl --context staging things import backup.ndjson --yes + """ + options = WriteOptions.pop(kwargs) + things = _read_things(source) + conditions = Conditions(if_none_match="*") if mode == "create" else Conditions(if_equal=IfEqual.SKIP) + output.info(f"Read {len(things)} thing(s) from {source}.") + confirm(state, len(things), options, "import" if mode == "create" else "upsert") + execute( + state, + list(things), + put_operation(state.client(), things, conditions, dry_run=options.dry_run), + options, + "import", + ) + + +@things_group.command("verify") +@click.argument("path") +@click.argument("thing_ids", nargs=-1, metavar="[THING_ID]...") +@click.option("--equals", "expected", required=True, metavar="JSON|@FILE", help="The expected value at PATH.") +@click.option( + "--compare", + type=click.Choice(["deep", "json"]), + default="deep", + show_default=True, + help="Value equality: 'deep' (1 equals 1.0) or 'json' (canonical text).", +) +@click.option("--failed-out", metavar="FILE", help="Write the things that don't match here (usable as --ids-file).") +@selector_options +@pass_state +def verify( + state: AppState, + path: str, + thing_ids: tuple[str, ...], + expected: str, + compare: str, + failed_out: str | None, + **kwargs: Any, +) -> None: + """Check that PATH has the expected value in each selected thing, for example after a bulk change. + + Prints the things that don't match as NDJSON and exits with code 6 if there are any. + + \b + Example: + dittoctl things verify features/config/properties/interval --equals 60 -f 'eq(attributes/model,"X1")' + """ + selection = pop_selection(state, thing_ids, kwargs) + value = read_json(expected, "--equals") + equal = equality(compare) + ids = select(state, selection) + pointer = "/".join(segments(path)) + seen: set[str] = set() + counts = {"match": 0, "mismatch": 0, "missing": 0} + log = open(failed_out, "w", encoding="utf-8") if failed_out else None # noqa: SIM115 + try: + if log: + log.write("# thingId\tresult\tactual\n") + for thing in get_things(state.client(), ids, fields=f"thingId,{pointer}"): + thing_id = thing.get("thingId") + seen.add(thing_id) + actual = get_path(thing, pointer) + result = ( + "match" + if actual is not None and equal(actual, value) + else ("missing" if actual is None else "mismatch") + ) + counts[result] += 1 + if result != "match": + output.line({"thingId": thing_id, "result": result, "actual": actual}) + if log: + log.write(f"{thing_id}\t{result}\t{json.dumps(actual, ensure_ascii=False)}\n") + not_found = [i for i in ids if i not in seen] + for thing_id in not_found: + output.line({"thingId": thing_id, "result": "not-found"}) + if log: + log.write(f"{thing_id}\tnot-found\t\n") + finally: + if log: + log.close() + summary = ", ".join(f"{k} {v}" for k, v in counts.items()) + f", not found {len(not_found)}" + output.info(f"Verified {len(ids)} thing(s): {summary}") + if counts["mismatch"] or counts["missing"] or not_found: + raise CheckFailedError(f"{len(ids) - counts['match']} of {len(ids)} thing(s) don't have the expected value") + + +@things_group.command("migrate-definition") +@click.argument("thing_ids", nargs=-1, metavar="[THING_ID]...") +@click.option("--definition", required=True, metavar="TM_URL", help="URL of the new WoT Thing Model.") +@click.option("--payload", metavar="JSON|@FILE", help="Attributes/features to merge, may use {{ thing-json:... }}.") +@click.option( + "--patch-condition", + "patch_conditions", + multiple=True, + metavar="PATH=RQL", + help="Only merge the payload at PATH if the RQL matches, e.g. features/temp=not(exists(features/temp)).", +) +@click.option("--init-defaults", is_flag=True, help="Initialize missing properties from the model's defaults.") +@selector_options +@write_options +@pass_state +def migrate_definition( + state: AppState, + thing_ids: tuple[str, ...], + definition: str, + payload: str | None, + patch_conditions: tuple[str, ...], + init_defaults: bool, + **kwargs: Any, +) -> None: + """Move each selected thing to a new thing definition (Thing Model version), optionally updating it. + + --dry-run lets Ditto compute the result without applying it (Ditto 3.7+). + + \b + Example: + dittoctl things migrate-definition --definition https://models.example.org/sensor-2.0.0.tm.jsonld \\ + --init-defaults -f 'eq(definition,"https://models.example.org/sensor-1.0.0.tm.jsonld")' --dry-run + """ + options = WriteOptions.pop(kwargs) + selection = pop_selection(state, thing_ids, kwargs) + conditions = {} + for item in patch_conditions: + path, sep, rql = item.partition("=") + if not sep or not path: + raise click.BadParameter(f"expected PATH=RQL, got '{item}'", param_hint="--patch-condition") + key = path if path.startswith("thing:") else "thing:/" + path.strip("/") + conditions[key] = rql + ids = select(state, selection) + confirm(state, len(ids), options, "migrate the definition of") + operation = migrate_definition_operation( + state.client(), + definition, + payload=read_json(payload, "--payload") if payload else None, + patch_conditions=conditions, + initialize_defaults=init_defaults, + dry_run=options.dry_run, + ) + execute(state, ids, operation, options, "migrate definition") + + +# --- single-thing writes ---------------------------------------------------------------------- + + +@things_group.command("create") +@click.argument("thing_id", required=False) +@click.option("-d", "--data", metavar="JSON|@FILE|@-", help="The thing JSON (attributes, features, ...).") +@click.option( + "--definition", + metavar="URL|NS:NAME:VERSION", + help="Thing definition; a WoT Thing Model URL makes Ditto generate the thing's skeleton.", +) +@click.option("--policy-id", help="Use this existing policy instead of a new one.") +@protected_write() +@pass_state +def create( + state: AppState, thing_id: str | None, data: str | None, definition: str | None, policy_id: str | None +) -> None: + """Create a thing; fails if it already exists. Without THING_ID, Ditto generates the id. + + \b + Examples: + dittoctl things create org.example:sensor-1 -d '{"attributes":{"room":"lab"}}' + dittoctl things create org.example:lamp-1 --definition https://example.org/models/lamp-1.0.0.tm.jsonld + """ + body = read_json(data) if data else {} + if not isinstance(body, dict): + raise click.BadParameter("must be a JSON object", param_hint="--data") + if definition: + body["definition"] = definition + if policy_id: + body["policyId"] = policy_id + client = state.client() + if thing_id: + response = client.put(thing_path(thing_id), json=body, conditions=Conditions(if_none_match="*")) + else: + response = client.post("/api/2/things", json=body) + output.emit(response.body) + + +@things_group.command("put") +@click.argument("thing_id") +@click.option("-d", "--data", required=True, metavar="JSON|@FILE|@-", help="The complete thing JSON.") +@conditional_options +@protected_write() +@pass_state +def put(state: AppState, thing_id: str, data: str, **kwargs: Any) -> None: + """Create or completely replace a thing. + + \b + Example: + dittoctl things put org.example:sensor-1 -d @sensor-1.json --if-match rev:7 + """ + conditions = pop_conditions(kwargs) + body = read_json(data) + response = state.client().put(thing_path(thing_id), json=body, conditions=conditions) + if response.body is not None: + output.emit(response.body) + else: + output.info(f"Replaced {thing_id}.") + + +def _pretty(value: Any) -> str: + return json.dumps(value, indent=2, sort_keys=True, ensure_ascii=False) + "\n" + + +@things_group.command("edit") +@click.argument("thing_id") +@click.option("--path", help="Only edit this part, e.g. attributes.") +@protected_write() +@pass_state +def edit(state: AppState, thing_id: str, path: str | None) -> None: + """Edit a thing in $EDITOR; the changes are sent as a merge patch with If-Match. + + If the thing was changed by someone else in the meantime, nothing is written. + """ + client = state.client() + response = get_thing(client, thing_id, path=path) + original = response.body + edited_text = click.edit(_pretty(original), extension=".json", require_save=True) + if edited_text is None: + output.info("No changes.") + return + try: + edited = json.loads(edited_text) + except ValueError as e: + raise DittoctlError(f"the edited JSON is invalid, nothing was written: {e}") from None + patch_body = merge_patch_diff(original, edited) + if patch_body is NO_CHANGE: + output.info("No changes.") + return + if not isinstance(original, dict) or not isinstance(edited, dict): + # a scalar or array at --path: replace it + client.put(thing_path(thing_id, path), json=edited, conditions=Conditions(if_match=response.etag)) + else: + try: + client.patch(thing_path(thing_id, path), json=patch_body, conditions=Conditions(if_match=response.etag)) + except DittoError as e: + if e.status == 412 and not e.condition_failed: + raise AbortedError(f"{thing_id} was changed in the meantime; nothing was written. Edit again") from None + raise + output.info(f"Updated {thing_id}.") + + +@things_group.command("diff") +@click.argument("thing_id") +@click.option("--file", "file", required=True, metavar="FILE|-", help="Local JSON to compare with.") +@click.option("--path", help="Compare only this part of the thing.") +@click.option( + "-o", + "--output", + "output_format", + type=click.Choice(["text", "json"]), + help='Output format: a unified diff, or a JSON list of {"op", "path", "old", "new"} with op add, remove or ' + "replace and old being the value in Ditto (default: text; agent mode: json).", +) +@click.pass_context +def diff(ctx: click.Context, thing_id: str, file: str, path: str | None, output_format: str | None) -> None: + """Show the differences between a local JSON file and the thing in Ditto (exit code 6 if they differ).""" + state = ctx.find_object(AppState) + assert state is not None + remote = get_thing(state.client(), thing_id, path=path).body + local = read_json(file if file.startswith("@") else f"@{file}", "--file") + if (output_format or ("json" if output.agent_mode() else "text")) == "json": + changes = json_diff(remote, local) + output.emit(changes) + if changes: + raise CheckFailedError(f"{len(changes)} difference(s) between {thing_id} and {file}") + return + if deep_equal(local, remote): + output.info("No differences.") + return + lines = difflib.unified_diff( + _pretty(remote).splitlines(keepends=True), + _pretty(local).splitlines(keepends=True), + fromfile=f"ditto:{thing_id}{'/' + path.strip('/') if path else ''}", + tofile=file, + ) + sys.stdout.writelines(lines) + raise CheckFailedError(f"{thing_id} and {file} differ") diff --git a/src/dittoctl/cli/wot_cmd.py b/src/dittoctl/cli/wot_cmd.py new file mode 100644 index 0000000..bdaa433 --- /dev/null +++ b/src/dittoctl/cli/wot_cmd.py @@ -0,0 +1,37 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +"""``dittoctl wot``: Web of Things integration.""" + +from __future__ import annotations + +import click + +from dittoctl.cli import output +from dittoctl.cli.state import AppState, pass_state +from dittoctl.core.things import wot_directory + + +@click.group("wot") +def wot_group() -> None: + """Web of Things (WoT): Ditto's Thing Directory. See also 'things td' and 'things migrate-definition'.""" + + +@wot_group.command("directory") +@pass_state +def directory(state: AppState) -> None: + """Show Ditto's WoT Thing Directory description (/.well-known/wot, Ditto 3.9+).""" + output.emit(wot_directory(state.client())) diff --git a/src/dittoctl/config.py b/src/dittoctl/config.py new file mode 100644 index 0000000..71b6cf4 --- /dev/null +++ b/src/dittoctl/config.py @@ -0,0 +1,248 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +"""Contexts: named Ditto endpoints with their auth settings, stored as TOML. + +The config file never holds secrets (passwords, tokens, client secrets); those live in the +secret store, see :mod:`dittoctl.auth.store`. + +Example:: + + current-context = "local" + + [contexts.local] + url = "http://localhost:8080" + + [contexts.local.auth] + method = "basic" + username = "ditto" +""" + +from __future__ import annotations + +import os +import tomllib +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any + +import tomli_w + +from dittoctl.errors import ConfigError + +AUTH_METHODS = ("none", "basic", "token", "preauth", "oidc") +OIDC_FLOWS = ("pkce", "device", "client-credentials") +CONFIG_FILE_NAME = "config.toml" + + +def config_dir() -> Path: + if explicit := os.environ.get("DITTOCTL_CONFIG_DIR"): + return Path(explicit) + base = os.environ.get("XDG_CONFIG_HOME") or str(Path.home() / ".config") + return Path(base) / "dittoctl" + + +def state_dir() -> Path: + if explicit := os.environ.get("DITTOCTL_STATE_DIR"): + return Path(explicit) + base = os.environ.get("XDG_STATE_HOME") or str(Path.home() / ".local" / "state") + return Path(base) / "dittoctl" + + +def default_config_path() -> Path: + return config_dir() / CONFIG_FILE_NAME + + +@dataclass +class AuthConfig: + method: str = "none" + # basic + username: str | None = None + # preauth: value of the x-ditto-pre-authenticated header, e.g. "nginx:ditto" + subject: str | None = None + # oidc + issuer: str | None = None + client_id: str | None = None + flow: str = "pkce" + scopes: list[str] = field(default_factory=lambda: ["openid"]) + # added to the authorization and token requests, e.g. {"audience": "ditto"} + extra_params: dict[str, str] = field(default_factory=dict) + # 0 picks a free port (RFC 8252 loopback redirect); set a fixed port if the IdP requires an exact redirect URI + redirect_port: int = 0 + # which token of the token response to send to Ditto: "access" or "id" + use_token: str = "access" + + def validate(self, context_name: str) -> None: + where = f"context '{context_name}'" + if self.method not in AUTH_METHODS: + expected = ", ".join(AUTH_METHODS) + raise ConfigError(f"{where}: unknown auth method '{self.method}', expected one of {expected}") + if self.method == "basic" and not self.username: + raise ConfigError(f"{where}: auth method 'basic' requires a username") + if self.method == "preauth" and not self.subject: + raise ConfigError(f"{where}: auth method 'preauth' requires a subject, e.g. 'nginx:ditto'") + if self.method == "oidc": + if not self.issuer or not self.client_id: + raise ConfigError(f"{where}: auth method 'oidc' requires an issuer and a client id") + if self.flow not in OIDC_FLOWS: + raise ConfigError(f"{where}: unknown OIDC flow '{self.flow}', expected one of {', '.join(OIDC_FLOWS)}") + if self.use_token not in ("access", "id"): + raise ConfigError(f"{where}: use-token must be 'access' or 'id'") + + def to_toml(self) -> dict[str, Any]: + data: dict[str, Any] = {"method": self.method} + if self.method == "basic": + data["username"] = self.username + elif self.method == "preauth": + data["subject"] = self.subject + elif self.method == "oidc": + data.update( + { + "issuer": self.issuer, + "client-id": self.client_id, + "flow": self.flow, + "scopes": self.scopes, + "use-token": self.use_token, + } + ) + if self.extra_params: + data["extra-params"] = self.extra_params + if self.redirect_port: + data["redirect-port"] = self.redirect_port + return data + + @classmethod + def from_toml(cls, data: dict[str, Any]) -> AuthConfig: + return cls( + method=data.get("method", "none"), + username=data.get("username"), + subject=data.get("subject"), + issuer=data.get("issuer"), + client_id=data.get("client-id"), + flow=data.get("flow", "pkce"), + scopes=list(data.get("scopes", ["openid"])), + extra_params=dict(data.get("extra-params", {})), + redirect_port=int(data.get("redirect-port", 0)), + use_token=data.get("use-token", "access"), + ) + + +@dataclass +class Context: + name: str + url: str + auth: AuthConfig = field(default_factory=AuthConfig) + namespaces: list[str] = field(default_factory=list) + headers: dict[str, str] = field(default_factory=dict) + protected: bool = False + timeout: float = 30.0 + # True, False or the path of a CA bundle + verify: bool | str = True + # stream id-only searches via SSE; turn off where the gateway throttles SSE search + search_streaming: bool = True + + def validate(self) -> None: + if not self.url.startswith(("http://", "https://")): + raise ConfigError(f"context '{self.name}': url must start with http:// or https://") + self.auth.validate(self.name) + + def to_toml(self) -> dict[str, Any]: + data: dict[str, Any] = {"url": self.url} + if self.namespaces: + data["namespaces"] = self.namespaces + if self.headers: + data["headers"] = self.headers + if self.protected: + data["protected"] = True + if self.timeout != 30.0: + data["timeout"] = self.timeout + if self.verify is not True: + data["verify"] = self.verify + if not self.search_streaming: + data["search-streaming"] = False + data["auth"] = self.auth.to_toml() + return data + + @classmethod + def from_toml(cls, name: str, data: dict[str, Any]) -> Context: + if "url" not in data: + raise ConfigError(f"context '{name}' has no url") + return cls( + name=name, + url=str(data["url"]).rstrip("/"), + auth=AuthConfig.from_toml(data.get("auth", {})), + namespaces=list(data.get("namespaces", [])), + headers=dict(data.get("headers", {})), + protected=bool(data.get("protected", False)), + timeout=float(data.get("timeout", 30.0)), + verify=data.get("verify", True), + search_streaming=bool(data.get("search-streaming", True)), + ) + + +@dataclass +class Config: + path: Path + current_context: str | None = None + contexts: dict[str, Context] = field(default_factory=dict) + + @classmethod + def load(cls, path: Path | None = None) -> Config: + path = path or default_config_path() + if not path.exists(): + return cls(path=path) + try: + data = tomllib.loads(path.read_text(encoding="utf-8")) + except (OSError, tomllib.TOMLDecodeError) as e: + raise ConfigError(f"cannot read config file {path}: {e}") from e + contexts = {name: Context.from_toml(name, ctx) for name, ctx in data.get("contexts", {}).items()} + return cls(path=path, current_context=data.get("current-context"), contexts=contexts) + + def save(self) -> None: + data: dict[str, Any] = {} + if self.current_context: + data["current-context"] = self.current_context + data["contexts"] = {name: ctx.to_toml() for name, ctx in sorted(self.contexts.items())} + self.path.parent.mkdir(parents=True, exist_ok=True) + tmp = self.path.with_suffix(".toml.tmp") + fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + with os.fdopen(fd, "w", encoding="utf-8") as f: + f.write(tomli_w.dumps(data)) + tmp.replace(self.path) + + def get_context(self, name: str | None = None) -> Context: + name = name or self.current_context + if not name: + raise ConfigError( + "no context selected. Create one with 'dittoctl config add-context', " + "select one with 'dittoctl config use-context' or pass --url" + ) + try: + return self.contexts[name] + except KeyError: + known = ", ".join(sorted(self.contexts)) or "none" + raise ConfigError(f"unknown context '{name}' (known contexts: {known})") from None + + def set_context(self, context: Context) -> None: + context.validate() + self.contexts[context.name] = context + + def delete_context(self, name: str) -> Context: + context = self.get_context(name) + del self.contexts[name] + if self.current_context == name: + self.current_context = None + return context diff --git a/src/dittoctl/core/__init__.py b/src/dittoctl/core/__init__.py new file mode 100644 index 0000000..56e7a62 --- /dev/null +++ b/src/dittoctl/core/__init__.py @@ -0,0 +1,22 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +"""Library API: usable without the CLI. Nothing in this package prints.""" + +from dittoctl.core.client import DittoClient, DittoResponse +from dittoctl.core.conditions import Conditions, IfEqual, LiveTimeoutStrategy + +__all__ = ["Conditions", "DittoClient", "DittoResponse", "IfEqual", "LiveTimeoutStrategy"] diff --git a/src/dittoctl/core/bulk.py b/src/dittoctl/core/bulk.py new file mode 100644 index 0000000..50432cd --- /dev/null +++ b/src/dittoctl/core/bulk.py @@ -0,0 +1,272 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +"""The bulk engine: run one operation per thing, concurrently, rate-limited, journaled and resumable.""" + +from __future__ import annotations + +import threading +import time +from collections import Counter +from collections.abc import Callable, Iterable, Sequence +from concurrent.futures import FIRST_COMPLETED, Future, ThreadPoolExecutor, wait +from dataclasses import dataclass, field +from enum import StrEnum +from pathlib import Path +from typing import Any, TextIO + +from dittoctl.errors import DittoctlError, DittoError + + +class Category(StrEnum): + OK = "ok" + # Ditto skipped the write because the value didn't change (If-Equal: skip), or nothing needed to change + UNCHANGED = "unchanged" + # the request's --condition didn't match + CONDITION_NOT_MET = "condition-not-met" + # create-only (If-None-Match: *) on a thing that already exists + EXISTS = "exists" + # If-Match didn't match, also after re-reading (concurrent modification) + CONFLICT = "conflict" + NOT_FOUND = "not-found" + FAILED = "failed" + # dry run: what would be sent + PLANNED = "planned" + + +FAILURES = frozenset({Category.CONFLICT, Category.NOT_FOUND, Category.FAILED}) + + +@dataclass +class Outcome: + thing_id: str + category: Category + status: int | None = None + error: str | None = None + message: str | None = None + # dry run: the planned request; messages: the response + detail: Any = None + # Ditto's explanation of an error, e.g. which fields don't conform to the thing's WoT model + description: str | None = None + + @property + def failed(self) -> bool: + return self.category in FAILURES + + +def is_unchanged(exc: DittoError) -> bool: + """Ditto answers If-Equal: skip with 412 like a failed If-Match; only the message tells them apart.""" + return exc.status == 412 and "previous value was equal" in (exc.message or "") + + +def classify(thing_id: str, exc: Exception) -> Outcome: + """Map an error of one thing's operation to an outcome.""" + if isinstance(exc, DittoError): + if exc.status == 412: + if exc.condition_failed: + category = Category.CONDITION_NOT_MET + elif is_unchanged(exc): + category = Category.UNCHANGED + else: + category = Category.CONFLICT + else: + category = Category.NOT_FOUND if exc.status == 404 else Category.FAILED + return Outcome(thing_id, category, exc.status, exc.error, exc.message, description=exc.description) + if isinstance(exc, DittoctlError): + return Outcome(thing_id, Category.FAILED, None, "dittoctl", str(exc)) + return Outcome(thing_id, Category.FAILED, None, type(exc).__name__, str(exc)) + + +class RateLimiter: + """Spaces calls evenly to at most ``rate`` per second, across threads.""" + + def __init__( + self, rate: float, clock: Callable[[], float] = time.monotonic, sleep: Callable[[float], None] = time.sleep + ) -> None: + if rate <= 0: + raise DittoctlError("--rate must be greater than 0") + self.interval = 1.0 / rate + self.clock = clock + self.sleep = sleep + self._next = 0.0 + self._lock = threading.Lock() + + def acquire(self) -> None: + with self._lock: + now = self.clock() + slot = max(now, self._next) + self._next = slot + self.interval + if slot > now: + self.sleep(slot - now) + + +class Journal: + """Append-only record of finished things (``idcategory``) so that an interrupted run can be resumed. + + Failed things are not recorded: a resumed run tries them again. + """ + + def __init__(self, path: str | Path) -> None: + self.path = Path(path) + self._lock = threading.Lock() + self._file: TextIO | None = None + + def completed(self) -> set[str]: + if not self.path.exists(): + return set() + with self.path.open(encoding="utf-8") as f: + return {line.split("\t", 1)[0] for line in f if line.strip() and not line.startswith("#")} + + def record(self, outcome: Outcome) -> None: + if outcome.failed or outcome.category == Category.PLANNED: + return + with self._lock: + if self._file is None: + self._file = self.path.open("a", encoding="utf-8") + self._file.write(f"{outcome.thing_id}\t{outcome.category}\n") + self._file.flush() + + def close(self) -> None: + if self._file: + self._file.close() + + +class FailureLog: + """Writes failed things as ``idstatuserrormessagedescription``. + + The file can be used as ``--ids-file``. + """ + + def __init__(self, path: str | Path) -> None: + self.path = Path(path) + self._lock = threading.Lock() + self._file: TextIO | None = None + + def record(self, outcome: Outcome) -> None: + if not outcome.failed: + return + message, description = ( + (text or "").replace("\t", " ").replace("\n", " ") for text in (outcome.message, outcome.description) + ) + with self._lock: + if self._file is None: + self._file = self.path.open("w", encoding="utf-8") + self._file.write("# thingId\tstatus\terror\tmessage\tdescription\n") + self._file.write( + f"{outcome.thing_id}\t{outcome.status or ''}\t{outcome.error or ''}\t{message}\t{description}\n" + ) + self._file.flush() + + def close(self) -> None: + if self._file: + self._file.close() + + +@dataclass +class Summary: + total: int + counts: Counter[Category] = field(default_factory=Counter) + skipped_by_journal: int = 0 + elapsed: float = 0.0 + interrupted: bool = False + + @property + def processed(self) -> int: + return sum(self.counts.values()) + + @property + def failures(self) -> int: + return sum(n for category, n in self.counts.items() if category in FAILURES) + + def describe(self, noun: str = "things") -> str: + parts = [f"{category} {n}" for category, n in sorted(self.counts.items(), key=lambda kv: -kv[1])] + if self.skipped_by_journal: + parts.append(f"already done (journal) {self.skipped_by_journal}") + rate = f" ({self.processed / self.elapsed:.0f}/s)" if self.elapsed > 0 and self.processed else "" + return f"{self.processed} of {self.total} {noun} in {self.elapsed:.1f}s{rate}: " + (", ".join(parts) or "none") + + +def run_bulk( + thing_ids: Sequence[str], + operation: Callable[[str], Outcome], + *, + concurrency: int = 8, + rate: float | None = None, + journal: Journal | None = None, + resume: bool = False, + failure_log: FailureLog | None = None, + on_outcome: Callable[[Outcome], None] | None = None, +) -> Summary: + """Run ``operation`` for each thing id with up to ``concurrency`` in flight. + + Errors raised by an operation are classified per thing and never stop the run. Ctrl+C stops submitting new + things, waits for the ones in flight and returns a summary with ``interrupted`` set; with a journal, the + run can then be resumed. + """ + if concurrency < 1: + raise DittoctlError("--concurrency must be at least 1") + done_before = journal.completed() if journal and resume else set() + pending: Iterable[str] = [i for i in thing_ids if i not in done_before] + summary = Summary(total=len(thing_ids), skipped_by_journal=len(thing_ids) - len(pending)) + limiter = RateLimiter(rate) if rate else None + started = time.monotonic() + + def task(thing_id: str) -> Outcome: + if limiter: + limiter.acquire() + try: + return operation(thing_id) + except Exception as e: + return classify(thing_id, e) + + def finish(future: Future[Outcome]) -> None: + outcome = future.result() + summary.counts[outcome.category] += 1 + if journal: + journal.record(outcome) + if failure_log: + failure_log.record(outcome) + if on_outcome: + on_outcome(outcome) + + executor = ThreadPoolExecutor(max_workers=concurrency, thread_name_prefix="dittoctl-bulk") + in_flight: set[Future[Outcome]] = set() + try: + for thing_id in pending: + while len(in_flight) >= concurrency * 2: + done, in_flight = wait(in_flight, return_when=FIRST_COMPLETED) + for future in done: + finish(future) + in_flight.add(executor.submit(task, thing_id)) + while in_flight: + done, in_flight = wait(in_flight, return_when=FIRST_COMPLETED) + for future in done: + finish(future) + except KeyboardInterrupt: + summary.interrupted = True + for future in in_flight: + future.cancel() + for future in in_flight: + if not future.cancelled(): + finish(future) + finally: + executor.shutdown(wait=True, cancel_futures=True) + summary.elapsed = time.monotonic() - started + if journal: + journal.close() + if failure_log: + failure_log.close() + return summary diff --git a/src/dittoctl/core/client.py b/src/dittoctl/core/client.py new file mode 100644 index 0000000..603c10b --- /dev/null +++ b/src/dittoctl/core/client.py @@ -0,0 +1,305 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +"""Thin HTTP client for the Ditto HTTP API. + +Adds authentication, correlation ids, conditional headers, retries with backoff and Ditto error mapping +on top of httpx. It never prints; ``on_request``/``on_response`` hooks let the CLI show traffic. +""" + +from __future__ import annotations + +import itertools +import json as jsonlib +import time +import uuid +from collections.abc import Callable, Iterator, Mapping +from contextlib import contextmanager +from dataclasses import dataclass +from email.utils import parsedate_to_datetime +from typing import Any +from urllib.parse import urlencode + +import httpx + +from dittoctl import __version__ +from dittoctl.auth.base import AuthProvider +from dittoctl.core.conditions import Conditions +from dittoctl.errors import DittoctlError, DittoError + +RETRYABLE_STATUS = frozenset({429, 502, 503, 504}) +# requests that may be repeated without changing the outcome; merge PATCH is idempotent too +IDEMPOTENT_METHODS = frozenset({"GET", "HEAD", "OPTIONS", "PUT", "DELETE", "PATCH"}) +MAX_RETRY_DELAY_SECONDS = 30.0 +MERGE_PATCH = "application/merge-patch+json" + +_UNSET: Any = object() + + +@dataclass +class DittoResponse: + status: int + headers: httpx.Headers + body: Any + text: str + + @property + def etag(self) -> str | None: + return self.headers.get("etag") + + @property + def revision(self) -> int | None: + value = self.headers.get("entity-revision") + return int(value) if value and value.isdigit() else None + + @property + def correlation_id(self) -> str | None: + return self.headers.get("correlation-id") + + @classmethod + def from_httpx(cls, response: httpx.Response) -> DittoResponse: + body: Any = None + if response.content: + if "json" in response.headers.get("content-type", ""): + try: + body = response.json() + except ValueError: + body = response.text + else: + body = response.text + return cls(status=response.status_code, headers=response.headers, body=body, text=response.text) + + +def _retry_after(response: httpx.Response) -> float | None: + value = response.headers.get("retry-after") + if not value: + return None + if value.isdigit(): + return float(value) + try: + return max(0.0, parsedate_to_datetime(value).timestamp() - time.time()) + except (TypeError, ValueError): + return None + + +class DittoClient: + def __init__( + self, + base_url: str, + auth: AuthProvider | None = None, + *, + headers: Mapping[str, str] | None = None, + timeout: float = 30.0, + verify: bool | str = True, + max_retries: int = 3, + backoff: float = 0.5, + correlation_id: str | None = None, + on_request: Callable[[httpx.Request], None] | None = None, + on_response: Callable[[httpx.Response], None] | None = None, + transport: httpx.BaseTransport | None = None, + sleep: Callable[[float], None] = time.sleep, + ) -> None: + self.base_url = base_url.rstrip("/") + self.auth = auth + self.max_retries = max_retries + self.backoff = backoff + self.run_id = correlation_id or f"dittoctl-{uuid.uuid4().hex[:12]}" + self._sequence = itertools.count(1) + self.on_request = on_request + self.on_response = on_response + self.sleep = sleep + self.http = httpx.Client( + base_url=self.base_url, + headers={"User-Agent": f"dittoctl/{__version__}", **(headers or {})}, + timeout=timeout, + verify=verify, + transport=transport, + ) + + def close(self) -> None: + self.http.close() + + def __enter__(self) -> DittoClient: + return self + + def __exit__(self, *exc: object) -> None: + self.close() + + def next_correlation_id(self) -> str: + return f"{self.run_id}-{next(self._sequence)}" + + def request( + self, + method: str, + path: str, + *, + params: Mapping[str, Any] | None = None, + json: Any = _UNSET, + data: Mapping[str, str] | None = None, + content: str | bytes | None = None, + content_type: str | None = None, + headers: Mapping[str, str] | None = None, + conditions: Conditions | None = None, + raise_for_status: bool = True, + retry: bool | None = None, + timeout: float | None = None, + ) -> DittoResponse: + """Send a request to ``path`` (relative to the base URL, e.g. ``/api/2/things/ns:id``). + + The body is ``json`` (serialized; merge patch for PATCH), ``data`` (form-encoded) or raw ``content``. + ``retry`` defaults to True for idempotent methods; ``timeout`` overrides the client's timeout in seconds. + Ditto error responses raise :class:`DittoError` unless ``raise_for_status`` is False. + """ + method = method.upper() + if json is not _UNSET: + content = jsonlib.dumps(json) + content_type = content_type or (MERGE_PATCH if method == "PATCH" else "application/json") + elif data is not None: + content = urlencode(data) + content_type = content_type or "application/x-www-form-urlencoded" + request_headers, request_params = self._prepare(path, params, content_type, headers, conditions) + + retry = method in IDEMPOTENT_METHODS if retry is None else retry + refreshed = False + attempt = 0 + while True: + request = self._build( + method, + path, + request_params, + content, + request_headers, + timeout=httpx.Timeout(timeout) if timeout is not None else None, + ) + try: + response = self.http.send(request) + except httpx.TransportError as e: + if retry and attempt < self.max_retries: + self.sleep(self._delay(attempt, None)) + attempt += 1 + continue + raise DittoctlError(f"{method} {request.url} failed: {e}") from e + if self.on_response: + self.on_response(response) + + if response.status_code == 401 and self.auth and not refreshed and self.auth.refresh(): + refreshed = True + continue + if response.status_code in RETRYABLE_STATUS and retry and attempt < self.max_retries: + self.sleep(self._delay(attempt, response)) + attempt += 1 + continue + if raise_for_status and response.status_code >= 400: + raise DittoError.from_response(response) + return DittoResponse.from_httpx(response) + + @contextmanager + def stream( + self, + method: str, + path: str, + *, + params: Mapping[str, Any] | None = None, + headers: Mapping[str, str] | None = None, + read_timeout: float | None = None, + ) -> Iterator[httpx.Response]: + """Open a streaming request, e.g. for server-sent events. The read timeout defaults to none.""" + request_headers, request_params = self._prepare(path, params, None, headers, None) + timeout = httpx.Timeout(self.http.timeout.connect, read=read_timeout) + refreshed = False + while True: + request = self._build(method.upper(), path, request_params, None, request_headers, timeout=timeout) + try: + response = self.http.send(request, stream=True) + except httpx.TransportError as e: + raise DittoctlError(f"{method} {request.url} failed: {e}") from e + try: + if self.on_response: + self.on_response(response) + if response.status_code == 401 and self.auth and not refreshed and self.auth.refresh(): + refreshed = True + continue + if response.status_code >= 400: + response.read() + raise DittoError.from_response(response) + yield response + return + finally: + response.close() + + def _prepare( + self, + path: str, + params: Mapping[str, Any] | None, + content_type: str | None, + headers: Mapping[str, str] | None, + conditions: Conditions | None, + ) -> tuple[dict[str, str], dict[str, Any]]: + if not path.startswith("/"): + raise DittoctlError(f"path must start with '/': {path}") + request_headers: dict[str, str] = {} + request_params: dict[str, Any] = dict(params or {}) + if conditions: + request_headers.update(conditions.headers()) + request_params.update(conditions.params()) + if content_type: + request_headers["Content-Type"] = content_type + request_headers.update(headers or {}) + if not any(k.lower() == "correlation-id" for k in request_headers): + request_headers["correlation-id"] = self.next_correlation_id() + return request_headers, request_params + + def _build( + self, + method: str, + path: str, + params: Mapping[str, Any], + content: str | bytes | None, + headers: Mapping[str, str], + timeout: httpx.Timeout | None = None, + ) -> httpx.Request: + # auth headers are fetched per attempt: a refresh after a 401 changes them + auth_headers = self.auth.headers() if self.auth else {} + extensions = {"timeout": timeout.as_dict()} if timeout else None + request = self.http.build_request( + method, path, params=params, content=content, headers={**auth_headers, **headers}, extensions=extensions + ) + if self.on_request: + self.on_request(request) + return request + + def _delay(self, attempt: int, response: httpx.Response | None) -> float: + hinted = _retry_after(response) if response is not None else None + delay = hinted if hinted is not None else self.backoff * (2**attempt) + return min(delay, MAX_RETRY_DELAY_SECONDS) + + def get(self, path: str, **kwargs: Any) -> DittoResponse: + return self.request("GET", path, **kwargs) + + def put(self, path: str, **kwargs: Any) -> DittoResponse: + return self.request("PUT", path, **kwargs) + + def patch(self, path: str, **kwargs: Any) -> DittoResponse: + return self.request("PATCH", path, **kwargs) + + def post(self, path: str, **kwargs: Any) -> DittoResponse: + return self.request("POST", path, **kwargs) + + def delete(self, path: str, **kwargs: Any) -> DittoResponse: + return self.request("DELETE", path, **kwargs) + + def whoami(self) -> Any: + return self.get("/api/2/whoami").body diff --git a/src/dittoctl/core/conditions.py b/src/dittoctl/core/conditions.py new file mode 100644 index 0000000..b943f2a --- /dev/null +++ b/src/dittoctl/core/conditions.py @@ -0,0 +1,100 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +"""Ditto's conditional request options as one value object. + +See https://eclipse.dev/ditto/httpapi-concepts.html#conditional-headers and +https://eclipse.dev/ditto/basic-conditional-requests.html +""" + +from __future__ import annotations + +import dataclasses +import json +from collections.abc import Mapping +from dataclasses import dataclass, field +from enum import StrEnum + + +class IfEqual(StrEnum): + UPDATE = "update" + SKIP = "skip" + SKIP_MINIMIZING_MERGE = "skip-minimizing-merge" + + +class LiveTimeoutStrategy(StrEnum): + FAIL = "fail" + USE_TWIN = "use-twin" + + +def normalize_etag(value: str) -> str: + """Ditto ETags look like ``"rev:5"``; accept ``rev:5`` as well and add the quotes. + + Proxies and CDNs that compress responses (nginx with gzip, Cloudflare) turn Ditto's strong ETags into + weak ones (``W/"rev:5"``). Ditto compares ``If-Match`` strongly (as RFC 7232 requires) and, until + https://github.com/eclipse-ditto/ditto/issues/2636 is fixed, ``If-None-Match`` too, so a weak ETag + never matches. The ``W/`` prefix is dropped so that ETags received through such proxies work. + """ + value = value.strip() + if value.startswith("W/"): + value = value[2:] + if value == "*" or value.startswith('"'): + return value + return f'"{value}"' + + +@dataclass(frozen=True) +class Conditions: + if_match: str | None = None + if_none_match: str | None = None + if_equal: IfEqual | None = None + # RQL condition evaluated by Ditto against the current entity before applying the request + condition: str | None = None + # JSON pointer -> RQL; for merge (PATCH) requests on things, Ditto 3.8+ + patch_conditions: Mapping[str, str] = field(default_factory=dict) + # RQL deciding whether a retrieve is routed to the live channel + live_condition: str | None = None + live_timeout_strategy: LiveTimeoutStrategy | None = None + + def headers(self) -> dict[str, str]: + headers: dict[str, str] = {} + if self.if_match: + headers["If-Match"] = normalize_etag(self.if_match) + if self.if_none_match: + headers["If-None-Match"] = normalize_etag(self.if_none_match) + if self.if_equal: + headers["If-Equal"] = str(self.if_equal) + if self.patch_conditions: + headers["merge-thing-patch-conditions"] = json.dumps(dict(self.patch_conditions), separators=(",", ":")) + if self.live_timeout_strategy: + headers["live-channel-timeout-strategy"] = str(self.live_timeout_strategy) + return headers + + def params(self) -> dict[str, str]: + # RQL expressions go into query parameters rather than headers, so that httpx URL-encodes them + # and non-ASCII values are possible + params: dict[str, str] = {} + if self.condition: + params["condition"] = self.condition + if self.live_condition: + params["live-channel-condition"] = self.live_condition + return params + + def is_empty(self) -> bool: + return not (self.headers() or self.params()) + + def replace(self, **changes: object) -> Conditions: + return dataclasses.replace(self, **changes) # type: ignore[arg-type] diff --git a/src/dittoctl/core/connections.py b/src/dittoctl/core/connections.py new file mode 100644 index 0000000..b5c41c0 --- /dev/null +++ b/src/dittoctl/core/connections.py @@ -0,0 +1,72 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +"""Connections. See https://eclipse.dev/ditto/connectivity-manage-connections.html""" + +from __future__ import annotations + +import re +from typing import Any +from urllib.parse import quote, urlsplit, urlunsplit + +from dittoctl.core.client import DittoClient, DittoResponse + +CONNECTIONS_PATH = "/api/2/connections" +COMMANDS = { + "open": "connectivity.commands:openConnection", + "close": "connectivity.commands:closeConnection", + "reset-metrics": "connectivity.commands:resetConnectionMetrics", + "enable-logs": "connectivity.commands:enableConnectionLogs", + "reset-logs": "connectivity.commands:resetConnectionLogs", +} + + +def connection_path(connection_id: str, *parts: str) -> str: + return f"{CONNECTIONS_PATH}/{quote(connection_id, safe='')}" + "".join(f"/{p}" for p in parts) + + +def send_command(client: DittoClient, connection_id: str, command: str) -> DittoResponse: + """Send one of :data:`COMMANDS` (by its short name) to a connection.""" + return client.post(connection_path(connection_id, "command"), content=COMMANDS[command], content_type="text/plain") + + +def redact_uri(uri: str) -> str: + """``amqps://user:secret@host:5671`` becomes ``amqps://user:***@host:5671``.""" + try: + parts = urlsplit(uri) + except ValueError: + return uri + if not parts.password: + return uri + host = parts.hostname or "" + if parts.port: + host += f":{parts.port}" + return urlunsplit(parts._replace(netloc=f"{parts.username}:***@{host}")) + + +_AUTH_HEADER = re.compile(r"(?i)(authorization\"?\s*[=:]\s*\"?)(basic|bearer)\s+[A-Za-z0-9+/=._~-]+") +_URI_PASSWORD = re.compile(r"(?i)(\b[a-z][a-z0-9+.-]*://[^:/@\s]+:)[^@\s]+@") + + +def redact_secrets(text: str) -> str: + """Mask Authorization header values and passwords in URIs within a text, e.g. a connection log message: + Ditto's connection logs include the headers of the request that caused a message.""" + return _URI_PASSWORD.sub(r"\1***@", _AUTH_HEADER.sub(r"\1\2 ***", text)) + + +def log_key(entry: dict[str, Any]) -> tuple[Any, ...]: + """Identifies a connection log entry, to show each entry only once when following the logs.""" + return tuple(entry.get(k) for k in ("timestamp", "correlationId", "category", "type", "address", "message")) diff --git a/src/dittoctl/core/curl.py b/src/dittoctl/core/curl.py new file mode 100644 index 0000000..ada0649 --- /dev/null +++ b/src/dittoctl/core/curl.py @@ -0,0 +1,52 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +"""Render requests as equivalent curl commands for ``--verbose``.""" + +from __future__ import annotations + +import shlex + +import httpx + +SENSITIVE_HEADERS = {"authorization", "cookie", "x-ditto-pre-authenticated"} +SKIPPED_HEADERS = {"host", "content-length", "accept-encoding", "connection", "user-agent"} + + +def redact(name: str, value: str) -> str: + if name.lower() not in SENSITIVE_HEADERS: + return value + scheme, _, _ = value.partition(" ") + return f"{scheme} ***" if scheme.lower() in ("bearer", "basic") else "***" + + +def to_curl(request: httpx.Request, *, redact_secrets: bool = True) -> str: + parts = ["curl", "-X", request.method, shlex.quote(str(request.url))] + # raw headers keep the original spelling, items() would lowercase the names + for raw_name, raw_value in request.headers.raw: + name, value = raw_name.decode("latin-1"), raw_value.decode("latin-1") + if name.lower() in SKIPPED_HEADERS: + continue + shown = redact(name, value) if redact_secrets else value + parts += ["-H", shlex.quote(f"{name}: {shown}")] + content = request.content + if content: + try: + body = content.decode("utf-8") + except UnicodeDecodeError: + body = f"<{len(content)} bytes>" + parts += ["--data-raw", shlex.quote(body)] + return " ".join(parts) diff --git a/src/dittoctl/core/devops.py b/src/dittoctl/core/devops.py new file mode 100644 index 0000000..95433c7 --- /dev/null +++ b/src/dittoctl/core/devops.py @@ -0,0 +1,186 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +"""DevOps commands: log levels, runtime config, piggyback commands, search reindexing, namespace erasure, status. + +See https://eclipse.dev/ditto/installation-operating.html#devops-commands +""" + +from __future__ import annotations + +import re +from collections.abc import Sequence +from typing import Any +from urllib.parse import quote + +from dittoctl.core.client import DittoClient, DittoResponse +from dittoctl.errors import DittoctlError + +LOGGING_PATH = "/devops/logging" +CONFIG_PATH = "/devops/config" +PIGGYBACK_PATH = "/devops/piggyback" +PUB_SUB_MEDIATOR = "/system/distributedPubSubMediator" +BACKGROUND_SYNC = "/user/thingsWildcardSearchRoot/searchUpdaterRoot/backgroundSyncProxy" +THINGS_UPDATER = "/user/thingsWildcardSearchRoot/searchUpdaterRoot/thingsUpdater" +# the service name of the search service in piggyback paths ("things-search" in log level responses) +SEARCH_SERVICE = "search" + + +def _path(base: str, *segments: str | None) -> str: + return base + "".join(f"/{quote(s, safe='')}" for s in segments if s) + + +def get_logging(client: DittoClient, service: str | None = None) -> Any: + return client.get(_path(LOGGING_PATH, service)).body + + +def set_logging(client: DittoClient, logger: str, level: str, service: str | None = None) -> Any: + return client.put(_path(LOGGING_PATH, service), json={"logger": logger, "level": level.lower()}).body + + +def get_config( + client: DittoClient, service: str | None = None, instance: str | None = None, path: str | None = None +) -> Any: + params = {"path": path} if path else None + return client.get(_path(CONFIG_PATH, service, instance if service else None), params=params).body + + +def duration_seconds(value: str) -> float: + """Ditto duration strings: ``500ms``, ``10s``, ``2m``, ``1h``, or plain seconds.""" + match = re.fullmatch(r"\s*(\d+(?:\.\d+)?)\s*(ms|s|m|h)?\s*", value) + if not match: + raise DittoctlError(f"invalid duration '{value}', expected e.g. 500ms, 10s, 2m") + number, unit = float(match.group(1)), match.group(2) or "s" + return number * {"ms": 0.001, "s": 1, "m": 60, "h": 3600}[unit] + + +def piggyback( + client: DittoClient, + command: dict[str, Any], + *, + service: str | None = None, + instance: str | None = None, + timeout: str = "10s", +) -> DittoResponse: + """Send a piggyback command (``{"targetActorSelection": ..., "headers": ..., "piggybackCommand": ...}``).""" + return client.post( + _path(PIGGYBACK_PATH, service, instance if service else None), + json=command, + params={"timeout": timeout}, + raise_for_status=False, + retry=False, + # the HTTP request has to outlive the time Ditto waits for the responses + timeout=duration_seconds(timeout) + 15, + ) + + +def reindex_command(namespaces: Sequence[str] | None = None) -> dict[str, Any]: + """Force the next background sync to update the search index of all things (or of the given namespaces).""" + headers: dict[str, Any] = {"aggregate": False, "is-group-topic": False, "force-update": True} + if namespaces: + headers["namespaces"] = list(namespaces) + return { + "targetActorSelection": BACKGROUND_SYNC, + "headers": headers, + "piggybackCommand": {"type": "common.commands:shutdown"}, + } + + +def reindex_thing_command(thing_id: str) -> dict[str, Any]: + """Update the search index entry of one thing immediately.""" + return { + "targetActorSelection": THINGS_UPDATER, + "headers": {"aggregate": False, "is-group-topic": True}, + "piggybackCommand": {"type": "thing-search.sudo.commands:sudoUpdateThing", "thingId": thing_id}, + } + + +def block_namespace_command(namespace: str) -> dict[str, Any]: + return { + "targetActorSelection": PUB_SUB_MEDIATOR, + "headers": {"aggregate": False}, + "piggybackCommand": {"type": "namespaces.commands:blockNamespace", "namespace": namespace}, + } + + +def shutdown_namespace_command(namespace: str) -> dict[str, Any]: + # Ditto requires the headers field, although the documented example leaves it out + return { + "targetActorSelection": PUB_SUB_MEDIATOR, + "headers": {"aggregate": False}, + "piggybackCommand": { + "type": "common.commands:shutdown", + "reason": {"type": "purge-namespace", "details": namespace}, + }, + } + + +def purge_namespace_command(namespace: str) -> dict[str, Any]: + return { + "targetActorSelection": PUB_SUB_MEDIATOR, + "headers": {"aggregate": True, "is-group-topic": True}, + "piggybackCommand": {"type": "namespaces.commands:purgeNamespace", "namespace": namespace}, + } + + +def unblock_namespace_command(namespace: str) -> dict[str, Any]: + return { + "targetActorSelection": PUB_SUB_MEDIATOR, + "headers": {"aggregate": False}, + "piggybackCommand": {"type": "namespaces.commands:unblockNamespace", "namespace": namespace}, + } + + +def purge_results(body: Any) -> list[dict[str, Any]]: + """The per-resource-type results of a purgeNamespace response (nested under arbitrary keys).""" + results: list[dict[str, Any]] = [] + + def collect(value: Any) -> None: + if isinstance(value, dict): + if value.get("type") == "namespaces.responses:purgeNamespace": + results.append(value) + else: + for child in value.values(): + collect(child) + + collect(body) + return results + + +def piggyback_errors(body: Any) -> list[dict[str, Any]]: + """The error responses in a piggyback answer: the answer itself, or (aggregated) those of single instances. + + Ditto answers HTTP 200 even if the addressed actors failed, e.g. with ``devops.responses:errorResponse``. + """ + if not isinstance(body, dict): + return [] + status = body.get("status") + if isinstance(status, int) and status >= 400: + return [body] + return [error for child in body.values() for error in piggyback_errors(child)] + + +def purge_succeeded(result: dict[str, Any]) -> bool: + """Ditto 3.9 reports success as status 200; the docs show a ``successful`` flag, which is honored if present.""" + return bool(result.get("successful", result.get("status") == 200)) + + +def health_lines(node: dict[str, Any], depth: int = 0) -> list[tuple[int, str, str]]: + """Flatten Ditto's health tree (``/status/health``) into (depth, label, status) rows.""" + rows = [(depth, str(node.get("label", "")), str(node.get("status", "")))] + for child in node.get("children", []): + rows.extend(health_lines(child, depth + 1)) + return rows diff --git a/src/dittoctl/core/fields.py b/src/dittoctl/core/fields.py new file mode 100644 index 0000000..33b544d --- /dev/null +++ b/src/dittoctl/core/fields.py @@ -0,0 +1,103 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +"""The shape of things: which paths occur in a set of things, with their JSON types and example values. + +Ditto things are schemaless, so knowing the paths and types is what it takes to write RQL filters and +field selectors; this works for things without a WoT model, too. +""" + +from __future__ import annotations + +import json +from collections.abc import Iterable +from dataclasses import dataclass, field +from typing import Any + +from dittoctl.formats.flatten import flatten + +MAX_EXAMPLE_LENGTH = 120 +MAX_EXAMPLE_ITEMS = 3 + + +def json_type(value: Any) -> str: + """The JSON type of a value; numbers are 'integer' or 'number', arrays carry their item types.""" + if value is None: + return "null" + if isinstance(value, bool): + return "boolean" + if isinstance(value, int): + return "integer" + if isinstance(value, float): + return "number" + if isinstance(value, str): + return "string" + if isinstance(value, list): + items = sorted({json_type(item) for item in value}) + return f"array<{'|'.join(items)}>" if items else "array" + return "object" + + +def _example(value: Any) -> Any: + if isinstance(value, str) and len(value) > MAX_EXAMPLE_LENGTH: + return value[: MAX_EXAMPLE_LENGTH - 1] + "…" + if isinstance(value, list): + return [_example(item) for item in value[:MAX_EXAMPLE_ITEMS]] + ( + ["…"] if len(value) > MAX_EXAMPLE_ITEMS else [] + ) + if isinstance(value, dict): + text = json.dumps(value, ensure_ascii=False, separators=(",", ":")) + return value if len(text) <= MAX_EXAMPLE_LENGTH else text[: MAX_EXAMPLE_LENGTH - 1] + "…" + return value + + +@dataclass +class FieldStats: + path: str + count: int = 0 + types: set[str] = field(default_factory=set) + examples: list[Any] = field(default_factory=list) + _seen: set[str] = field(default_factory=set, repr=False) + + def add(self, value: Any, max_examples: int) -> None: + self.count += 1 + self.types.add(json_type(value)) + if len(self.examples) < max_examples: + key = json.dumps(value, sort_keys=True, ensure_ascii=False) + if key not in self._seen: + self._seen.add(key) + self.examples.append(_example(value)) + + def to_json(self, total: int) -> dict[str, Any]: + return { + "path": self.path, + "types": sorted(self.types), + "count": self.count, + "share": round(self.count / total, 3) if total else 0, + "examples": self.examples, + } + + +def field_stats(things: Iterable[dict[str, Any]], max_examples: int = 3) -> tuple[list[FieldStats], int]: + """The leaf paths of the things (arrays and empty objects count as leaves), sorted by path, and the number of + things inspected.""" + stats: dict[str, FieldStats] = {} + total = 0 + for thing in things: + total += 1 + for path, value in flatten(thing).items(): + stats.setdefault(path, FieldStats(path)).add(value, max_examples) + return sorted(stats.values(), key=lambda s: s.path), total diff --git a/src/dittoctl/core/jsonops.py b/src/dittoctl/core/jsonops.py new file mode 100644 index 0000000..e6e851b --- /dev/null +++ b/src/dittoctl/core/jsonops.py @@ -0,0 +1,120 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +"""JSON helpers for writes: building merge patches (RFC 7396), comparing values, editing arrays.""" + +from __future__ import annotations + +import json +from collections.abc import Callable, Sequence +from typing import Any + +# returned by merge_patch_diff when both documents are equal +NO_CHANGE: Any = object() + +Equality = Callable[[Any, Any], bool] + + +def segments(path: str) -> list[str]: + return [s for s in path.strip("/").split("/") if s] + + +def nested(path: str, value: Any) -> Any: + """``nested("attributes/location/room", "lab")`` is ``{"attributes": {"location": {"room": "lab"}}}``.""" + for segment in reversed(segments(path)): + value = {segment: value} + return value + + +def contains_array(value: Any) -> bool: + if isinstance(value, list): + return True + if isinstance(value, dict): + return any(contains_array(v) for v in value.values()) + return False + + +def deep_equal(a: Any, b: Any) -> bool: + """Structural JSON equality: object key order doesn't matter, 1 equals 1.0, but true doesn't equal 1.""" + if isinstance(a, bool) or isinstance(b, bool): + return isinstance(a, bool) and isinstance(b, bool) and a == b + if isinstance(a, int | float) and isinstance(b, int | float): + return a == b + if isinstance(a, dict) and isinstance(b, dict): + return a.keys() == b.keys() and all(deep_equal(a[k], b[k]) for k in a) + if isinstance(a, list) and isinstance(b, list): + return len(a) == len(b) and all(deep_equal(x, y) for x, y in zip(a, b, strict=True)) + return type(a) is type(b) and a == b + + +def json_equal(a: Any, b: Any) -> bool: + """Equality of the canonical serialization: like deep_equal, but 1 and 1.0 differ.""" + return json.dumps(a, sort_keys=True) == json.dumps(b, sort_keys=True) + + +def equality(mode: str) -> Equality: + return json_equal if mode == "json" else deep_equal + + +def array_add(current: Sequence[Any] | None, items: Sequence[Any], *, as_set: bool, equal: Equality) -> list[Any]: + """Append items; with ``as_set`` only those not present yet (and each only once).""" + result = list(current or []) + for item in items: + if as_set and any(equal(item, existing) for existing in result): + continue + result.append(item) + return result + + +def array_remove(current: Sequence[Any] | None, items: Sequence[Any], *, equal: Equality) -> list[Any]: + """Remove every occurrence of each item.""" + return [existing for existing in current or [] if not any(equal(existing, item) for item in items)] + + +def json_diff(old: Any, new: Any, path: str = "") -> list[dict[str, Any]]: + """The differences between two JSON values as ``{"op", "path", "old", "new"}``, ops add/remove/replace. + + Objects are compared key by key, everything else (including arrays) as a whole. ``path`` is a JSON pointer. + """ + if isinstance(old, dict) and isinstance(new, dict): + changes: list[dict[str, Any]] = [] + for key in sorted(old.keys() | new.keys()): + child = f"{path}/{key}" + if key not in new: + changes.append({"op": "remove", "path": child, "old": old[key]}) + elif key not in old: + changes.append({"op": "add", "path": child, "new": new[key]}) + else: + changes.extend(json_diff(old[key], new[key], child)) + return changes + return [] if deep_equal(old, new) else [{"op": "replace", "path": path or "/", "old": old, "new": new}] + + +def merge_patch_diff(old: Any, new: Any) -> Any: + """The merge patch (RFC 7396) that turns ``old`` into ``new``, or :data:`NO_CHANGE`.""" + if isinstance(old, dict) and isinstance(new, dict): + patch: dict[str, Any] = {} + for key in old.keys() - new.keys(): + patch[key] = None + for key, value in new.items(): + if key not in old: + patch[key] = value + continue + child = merge_patch_diff(old[key], value) + if child is not NO_CHANGE: + patch[key] = child + return patch or NO_CHANGE + return NO_CHANGE if deep_equal(old, new) else new diff --git a/src/dittoctl/core/policies.py b/src/dittoctl/core/policies.py new file mode 100644 index 0000000..686ea96 --- /dev/null +++ b/src/dittoctl/core/policies.py @@ -0,0 +1,161 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +"""Policies: paths, discovery via things, subject migration and permission checks. + +See https://eclipse.dev/ditto/basic-policy.html and https://eclipse.dev/ditto/httpapi-concepts.html +""" + +from __future__ import annotations + +import copy +import re +from collections.abc import Collection, Sequence +from dataclasses import dataclass +from typing import Any +from urllib.parse import quote + +from dittoctl.core.bulk import Category, Outcome +from dittoctl.core.client import DittoClient +from dittoctl.core.conditions import Conditions +from dittoctl.core.search import find_things +from dittoctl.core.writes import Operation +from dittoctl.errors import DittoctlError, DittoError + +POLICIES_PATH = "/api/2/policies" +CHECK_PERMISSIONS_PATH = "/api/2/checkPermissions" +ALLOW_LOCKOUT_PARAM = "allow-policy-lockout" + + +def policy_path(policy_id: str, *segments: str) -> str: + """``policy_path("ns:p", "entries", "owner", "subjects", "nginx:ditto")``, each segment URL-encoded.""" + return f"{POLICIES_PATH}/{quote(policy_id, safe=':')}" + "".join(f"/{quote(s, safe=':')}" for s in segments if s) + + +def lockout_params(allow_lockout: bool) -> dict[str, str] | None: + return {ALLOW_LOCKOUT_PARAM: "true"} if allow_lockout else None + + +def policy_ids_of_things( + client: DittoClient, *, rql_filter: str | None, namespaces: Sequence[str] | None = None +) -> list[str]: + """The distinct policy ids of the things matching the filter (Ditto has no search for policies).""" + seen: dict[str, None] = {} + for thing in find_things(client, rql_filter=rql_filter, namespaces=namespaces, fields="policyId"): + if policy_id := thing.get("policyId"): + seen.setdefault(policy_id) + return list(seen) + + +@dataclass(frozen=True) +class SubjectChange: + label: str + old: str + new: str + removed_old: bool + + def describe(self) -> str: + verb = "replace" if self.removed_old else "add" + return f"{self.label}: {verb} {self.old} -> {self.new}" + + +def migrate_subjects( + policy: dict[str, Any], + pattern: re.Pattern[str], + template: str, + *, + labels: Collection[str] | None = None, + remove_old: bool = False, +) -> tuple[dict[str, Any], list[SubjectChange]]: + """For each subject whose id fully matches ``pattern``, add a subject ``match.expand(template)`` with the same + value (type, expiry, ...) to the same entry; with ``remove_old`` the old subject is removed. Idempotent: a + subject that already exists is left as it is. + """ + migrated = copy.deepcopy(policy) + changes: list[SubjectChange] = [] + for label, entry in migrated.get("entries", {}).items(): + if labels and label not in labels: + continue + subjects: dict[str, Any] = entry.get("subjects", {}) + for subject_id in list(subjects): + match = pattern.fullmatch(subject_id) + if not match: + continue + new_id = match.expand(template) + if new_id == subject_id: + continue + added = new_id not in subjects + if added: + subjects[new_id] = copy.deepcopy(subjects[subject_id]) + if remove_old: + del subjects[subject_id] + if added or remove_old: + changes.append(SubjectChange(label, subject_id, new_id, remove_old)) + return migrated, changes + + +def subject_migration_operation( + client: DittoClient, + pattern: re.Pattern[str], + template: str, + *, + labels: Collection[str] | None = None, + remove_old: bool = False, + allow_lockout: bool = False, + conflict_retries: int = 3, + dry_run: bool = False, +) -> Operation: + """Migrate the subjects of each policy, written atomically per policy with ``If-Match``.""" + + def operation(policy_id: str) -> Outcome: + target = policy_path(policy_id) + for _ in range(conflict_retries + 1): + response = client.get(target) + policy, etag = response.body, response.etag + if not isinstance(policy, dict): + raise DittoctlError(f"unexpected policy JSON for {policy_id}") + migrated, changes = migrate_subjects(policy, pattern, template, labels=labels, remove_old=remove_old) + if not changes: + return Outcome(policy_id, Category.UNCHANGED, message="no matching subjects to migrate") + described = [c.describe() for c in changes] + if dry_run: + return Outcome(policy_id, Category.PLANNED, detail={"policyId": policy_id, "changes": described}) + try: + result = client.put( + target, json=migrated, conditions=Conditions(if_match=etag), params=lockout_params(allow_lockout) + ) + return Outcome(policy_id, Category.OK, result.status, detail=described) + except DittoError as e: + if e.status != 412 or e.condition_failed: + raise + return Outcome( + policy_id, + Category.CONFLICT, + 412, + "conflict", + f"modified concurrently {conflict_retries + 1} times in a row", + ) + + return operation + + +def check_permissions(client: DittoClient, checks: dict[str, dict[str, Any]]) -> dict[str, bool]: + """Ask Ditto whether the caller has the given permissions; ``checks`` maps a name to + ``{"resource": "thing:/attributes", "entityId": "ns:id", "hasPermissions": ["READ"]}``.""" + body = client.post(CHECK_PERMISSIONS_PATH, json=checks, retry=True).body + if not isinstance(body, dict): + raise DittoctlError(f"unexpected checkPermissions response: {body!r}") + return body diff --git a/src/dittoctl/core/rql.py b/src/dittoctl/core/rql.py new file mode 100644 index 0000000..1176781 --- /dev/null +++ b/src/dittoctl/core/rql.py @@ -0,0 +1,253 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +"""Offline parser and formatter for Ditto RQL filter expressions. + +Grammar (see https://eclipse.dev/ditto/basic-rql.html):: + + query = comparison | in | property-op | logical | not + comparison = ("eq" | "ne" | "gt" | "ge" | "lt" | "le" | "like" | "ilike") "(" property "," value ")" + in = "in" "(" property "," value ("," value)* ")" + property-op= ("exists" | "empty") "(" property ")" + logical = ("and" | "or") "(" query ("," query)* ")" + not = "not" "(" query ")" + value = string | number | "true" | "false" | "null" + +Whitespace between tokens is accepted here; :func:`compact` produces the canonical form without it, +which is what dittoctl sends to Ditto. +""" + +from __future__ import annotations + +import json +import re +from dataclasses import dataclass +from typing import Any + +COMPARISON_OPS = ("eq", "ne", "gt", "ge", "lt", "le", "like", "ilike") +PROPERTY_OPS = ("exists", "empty") +LOGICAL_OPS = ("and", "or") +ALL_OPS = (*COMPARISON_OPS, "in", *PROPERTY_OPS, *LOGICAL_OPS, "not") + +_NUMBER = re.compile(r"-?(0|[1-9]\d*)(\.\d+)?([eE][+-]?\d+)?") +_OPERATOR = re.compile(r"[A-Za-z]+") +_PROPERTY_END = set(",()\"' \t\r\n") + + +class RqlError(ValueError): + def __init__(self, message: str, source: str, position: int) -> None: + super().__init__(message) + self.message = message + self.source = source + self.position = position + + def render(self, width: int = 60) -> str: + """The message plus the relevant part of the expression with a caret under the error position.""" + start = max(0, self.position - width // 2) + end = min(len(self.source), start + width) + snippet = self.source[start:end].replace("\n", " ").replace("\t", " ") + prefix = "…" if start > 0 else "" + suffix = "…" if end < len(self.source) else "" + caret = " " * (len(prefix) + self.position - start) + "^" + return f"{self.message} (at position {self.position})\n {prefix}{snippet}{suffix}\n {caret}" + + def __str__(self) -> str: + return f"{self.message} (at position {self.position})" + + +@dataclass(frozen=True) +class Value: + raw: str # exactly as written, so that strings keep their quotes and escapes + value: Any + + +@dataclass(frozen=True) +class Comparison: + op: str + property: str + values: tuple[Value, ...] + + +@dataclass(frozen=True) +class PropertyOp: + op: str + property: str + + +@dataclass(frozen=True) +class Logical: + op: str + children: tuple[Node, ...] + + +Node = Comparison | PropertyOp | Logical + + +class _Parser: + def __init__(self, text: str) -> None: + self.text = text + self.pos = 0 + + def error(self, message: str, position: int | None = None) -> RqlError: + return RqlError(message, self.text, self.pos if position is None else position) + + def skip_ws(self) -> None: + while self.pos < len(self.text) and self.text[self.pos].isspace(): + self.pos += 1 + + def peek(self) -> str: + self.skip_ws() + return self.text[self.pos] if self.pos < len(self.text) else "" + + def expect(self, char: str, context: str) -> None: + found = self.peek() + if found != char: + what = f"'{found}'" if found else "the end of the expression" + raise self.error(f"expected '{char}' {context}, found {what}") + self.pos += 1 + + def parse(self) -> Node: + if not self.text.strip(): + raise self.error("the expression is empty", 0) + node = self.query() + if self.peek(): + raise self.error("unexpected input after the end of the expression") + return node + + def query(self) -> Node: + self.skip_ws() + start = self.pos + match = _OPERATOR.match(self.text, self.pos) + if not match: + raise self.error("expected an operator such as eq, in, exists, and, or, not") + op = match.group(0) + if op not in ALL_OPS: + hint = f"; operators are lowercase: '{op.lower()}'" if op.lower() in ALL_OPS else "" + raise self.error(f"unknown operator '{op}'{hint}", start) + self.pos = match.end() + self.expect("(", f"after '{op}'") + if op in LOGICAL_OPS or op == "not": + children = [self.query()] + while op != "not" and self.peek() == ",": + self.pos += 1 + children.append(self.query()) + self.expect(")", f"to close '{op}('" + ("" if op == "not" else " or ',' before the next query")) + return Logical(op, tuple(children)) + prop = self.property() + if op in PROPERTY_OPS: + self.expect(")", f"to close '{op}(' (it takes only a property)") + return PropertyOp(op, prop) + self.expect(",", f"after the property of '{op}('") + values = [self.value()] + while op == "in" and self.peek() == ",": + self.pos += 1 + values.append(self.value()) + closing = "after the values of 'in('" if op == "in" else f"to close '{op}(' (it takes one value)" + self.expect(")", closing) + return Comparison(op, prop, tuple(values)) + + def property(self) -> str: + self.skip_ws() + start = self.pos + while self.pos < len(self.text) and self.text[self.pos] not in _PROPERTY_END: + self.pos += 1 + if self.pos == start: + raise self.error("expected a property path such as attributes/location or _modified") + return self.text[start : self.pos] + + def value(self) -> Value: + self.skip_ws() + start = self.pos + char = self.text[self.pos] if self.pos < len(self.text) else "" + if char in ('"', "'"): + return self.string(char) + if match := _NUMBER.match(self.text, self.pos): + end = match.end() + # "1abc" is not a number followed by garbage, it's an invalid value + if end >= len(self.text) or self.text[end] in _PROPERTY_END: + self.pos = end + raw = match.group(0) + return Value(raw, json.loads(raw)) + for keyword, value in (("true", True), ("false", False), ("null", None)): + end = self.pos + len(keyword) + if self.text.startswith(keyword, self.pos) and (end >= len(self.text) or self.text[end] in _PROPERTY_END): + self.pos = end + return Value(keyword, value) + raise self.error( + "expected a value: a quoted string, a number, true, false or null (strings need quotes)", start + ) + + def string(self, quote: str) -> Value: + start = self.pos + self.pos += 1 + chars: list[str] = [] + while self.pos < len(self.text): + char = self.text[self.pos] + if char == "\\" and self.pos + 1 < len(self.text): + chars.append(self.text[self.pos + 1]) + self.pos += 2 + continue + if char == quote: + self.pos += 1 + return Value(self.text[start : self.pos], "".join(chars)) + chars.append(char) + self.pos += 1 + raise self.error(f"unterminated string: the {quote} is never closed", start) + + +def parse(text: str) -> Node: + """Parse an RQL filter expression. Raises :class:`RqlError` with the position of the first error.""" + return _Parser(text).parse() + + +def compact(node: Node) -> str: + """The canonical single-line form, without whitespace.""" + if isinstance(node, Logical): + return f"{node.op}({','.join(compact(c) for c in node.children)})" + if isinstance(node, PropertyOp): + return f"{node.op}({node.property})" + return f"{node.op}({node.property},{','.join(v.raw for v in node.values)})" + + +def pretty(node: Node, indent: str = " ", _level: int = 0) -> str: + """Multi-line form: logical operators on their own lines, comparisons on one line.""" + if not isinstance(node, Logical): + return indent * _level + compact(node) + inner = ",\n".join(pretty(child, indent, _level + 1) for child in node.children) + pad = indent * _level + return f"{pad}{node.op}(\n{inner}\n{pad})" + + +# Ditto rejects exists() on these whole objects ("Unknown property name"), see eclipse-ditto/ditto#2637 +_UNSUPPORTED_EXISTS = ("attributes", "features") + + +def warnings(node: Node) -> list[str]: + """Problems Ditto will report although the expression is valid RQL.""" + if isinstance(node, Logical): + return [w for child in node.children for w in warnings(child)] + if isinstance(node, PropertyOp) and node.op == "exists" and node.property.strip("/") in _UNSUPPORTED_EXISTS: + name = node.property.strip("/") + return [ + f"Ditto rejects exists({name}) on the whole object (eclipse-ditto/ditto#2637); " + f"use a concrete path such as exists({name}/)" + ] + return [] + + +def normalize(text: str) -> str: + """Validate an expression and return its canonical form.""" + return compact(parse(text)) diff --git a/src/dittoctl/core/search.py b/src/dittoctl/core/search.py new file mode 100644 index 0000000..26bf25b --- /dev/null +++ b/src/dittoctl/core/search.py @@ -0,0 +1,220 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +"""Things search: cursor paging and SSE streaming. See https://eclipse.dev/ditto/httpapi-search.html + +Paging is the default. Ditto streams search results via SSE by retrieving each thing with its own +command, which is about 4x slower and more expensive for Ditto than the batched retrieval of a page +as soon as any field besides ``thingId`` is selected. With only ``thingId`` no retrieval is needed and +SSE is about twice as fast (measured with Ditto 3.9, see PLAN.md). :func:`find_things` picks accordingly. +""" + +from __future__ import annotations + +import json +from collections.abc import Iterator, Sequence +from enum import StrEnum +from typing import Any + +import httpx + +from dittoctl.core.client import DittoClient, DittoResponse +from dittoctl.core.sse import iter_sse +from dittoctl.errors import DittoctlError, DittoError + +SEARCH_PATH = "/api/2/search/things" +COUNT_PATH = "/api/2/search/things/count" +MAX_PAGE_SIZE = 200 +# above this length the query goes into a form-encoded POST body instead of the URL +POST_THRESHOLD = 2000 +# Ditto ends idle search streams after 60s by default (gateway streaming.search-idle-timeout) +STREAM_READ_TIMEOUT = 90.0 +STREAM_RECONNECTS = 3 + + +class Transport(StrEnum): + AUTO = "auto" + PAGING = "paging" + SSE = "sse" + + +def sort_option(sort: str | Sequence[str] | None) -> str | None: + """Turn ``-_modified,attributes/name`` (or a list of keys) into ``sort(-_modified,+attributes/name)``.""" + if not sort: + return None + keys = sort.split(",") if isinstance(sort, str) else list(sort) + normalized = [] + for key in (k.strip() for k in keys): + if not key: + continue + normalized.append(key if key[0] in "+-" else f"+{key}") + return f"sort({','.join(normalized)})" if normalized else None + + +def _query(client: DittoClient, path: str, params: dict[str, Any]) -> DittoResponse: + length = sum(len(str(v)) for v in params.values()) + if length > POST_THRESHOLD: + # searching is read-only, so the POST can be retried like a GET + return client.post(path, data={k: str(v) for k, v in params.items()}, retry=True) + return client.get(path, params=params) + + +def _base_params(rql_filter: str | None, namespaces: Sequence[str] | None) -> dict[str, Any]: + params: dict[str, Any] = {} + if rql_filter: + params["filter"] = rql_filter + if namespaces: + params["namespaces"] = ",".join(namespaces) + return params + + +def search_things( + client: DittoClient, + *, + rql_filter: str | None = None, + namespaces: Sequence[str] | None = None, + fields: str | None = None, + sort: str | Sequence[str] | None = None, + limit: int | None = None, + page_size: int = MAX_PAGE_SIZE, +) -> Iterator[dict[str, Any]]: + """Yield all things matching the filter, following the search cursor page by page.""" + if not 1 <= page_size <= MAX_PAGE_SIZE: + raise DittoctlError(f"page size must be between 1 and {MAX_PAGE_SIZE}") + if limit is not None and limit < 1: + return + size = min(page_size, limit) if limit else page_size + params = _base_params(rql_filter, namespaces) + if fields: + params["fields"] = fields + sort_part = sort_option(sort) + cursor: str | None = None + yielded = 0 + while True: + option = [f"size({size})"] + if sort_part: + option.append(sort_part) + if cursor: + option.append(f"cursor({cursor})") + body = _query(client, SEARCH_PATH, {**params, "option": ",".join(option)}).body + if not isinstance(body, dict): + raise DittoctlError(f"unexpected search response: {body!r}") + for item in body.get("items", []): + yield item + yielded += 1 + if limit and yielded >= limit: + return + cursor = body.get("cursor") + if not cursor: + return + + +def stream_things( + client: DittoClient, + *, + rql_filter: str | None = None, + namespaces: Sequence[str] | None = None, + fields: str | None = None, + sort: str | Sequence[str] | None = None, + limit: int | None = None, + max_reconnects: int = STREAM_RECONNECTS, +) -> Iterator[dict[str, Any]]: + """Yield the things matching the filter from Ditto's SSE search stream. + + A dropped connection is resumed after the last received thing via ``Last-Event-ID``. Errors arrive as + events with a Ditto error body (the HTTP status is already 200 then) and are raised as :class:`DittoError`. + """ + if limit is not None and limit < 1: + return + params = _base_params(rql_filter, namespaces) + if fields: + params["fields"] = fields + if sort_part := sort_option(sort): + params["option"] = sort_part + last_id: str | None = None + yielded = 0 + reconnects = 0 + while True: + headers = {"Accept": "text/event-stream"} + if last_id: + headers["Last-Event-ID"] = last_id + try: + with client.stream( + "GET", SEARCH_PATH, params=params, headers=headers, read_timeout=STREAM_READ_TIMEOUT + ) as response: + for event in iter_sse(response.iter_lines()): + if not event.data.strip(): + continue + item = json.loads(event.data) + if DittoError.is_error_body(item) and "thingId" not in item: + raise DittoError.from_body(item["status"], item, response.headers.get("correlation-id")) + yield item + yielded += 1 + last_id = event.id or item.get("thingId") or last_id + if limit and yielded >= limit: + return + return + except httpx.TransportError as e: + if reconnects >= max_reconnects: + raise DittoctlError(f"search stream failed after {reconnects} reconnects: {e}") from e + client.sleep(client.backoff * 2**reconnects) + reconnects += 1 + + +def choose_transport( + transport: Transport, *, fields: str | None, rql_filter: str | None, streaming_allowed: bool +) -> Transport: + """Resolve ``auto``: SSE for id-only searches whose filter fits into a URL, if the context allows it.""" + if transport != Transport.AUTO: + return transport + ids_only = fields is not None and fields.replace(" ", "") == "thingId" + fits_url = len(rql_filter or "") <= POST_THRESHOLD + return Transport.SSE if ids_only and streaming_allowed and fits_url else Transport.PAGING + + +def find_things( + client: DittoClient, + *, + rql_filter: str | None = None, + namespaces: Sequence[str] | None = None, + fields: str | None = None, + sort: str | Sequence[str] | None = None, + limit: int | None = None, + page_size: int = MAX_PAGE_SIZE, + transport: Transport = Transport.AUTO, + streaming_allowed: bool = True, +) -> Iterator[dict[str, Any]]: + """Search things with the cheaper transport, or the one asked for. + + ``auto`` streams via SSE when only thing ids are requested and ``streaming_allowed`` (contexts can turn it + off, e.g. when the gateway throttles SSE search) and the filter fits into a URL; otherwise it pages. + """ + transport = choose_transport(transport, fields=fields, rql_filter=rql_filter, streaming_allowed=streaming_allowed) + if transport == Transport.SSE: + return stream_things( + client, rql_filter=rql_filter, namespaces=namespaces, fields=fields, sort=sort, limit=limit + ) + return search_things( + client, rql_filter=rql_filter, namespaces=namespaces, fields=fields, sort=sort, limit=limit, page_size=page_size + ) + + +def count_things(client: DittoClient, *, rql_filter: str | None = None, namespaces: Sequence[str] | None = None) -> int: + body = _query(client, COUNT_PATH, _base_params(rql_filter, namespaces)).body + try: + return int(body) + except (TypeError, ValueError): + raise DittoctlError(f"unexpected count response: {body!r}") from None diff --git a/src/dittoctl/core/selectors.py b/src/dittoctl/core/selectors.py new file mode 100644 index 0000000..1a435d9 --- /dev/null +++ b/src/dittoctl/core/selectors.py @@ -0,0 +1,129 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +"""Selecting the things a command acts on: explicit ids, an id file, or an RQL filter.""" + +from __future__ import annotations + +import re +import sys +from collections.abc import Callable, Iterable, Sequence +from dataclasses import dataclass, field + +from dittoctl.core.client import DittoClient +from dittoctl.core.search import Transport, choose_transport, count_things, find_things +from dittoctl.errors import DittoctlError + +_SEPARATORS = re.compile(r"[\t,;\s]") + + +def read_ids(lines: Iterable[str]) -> list[str]: + """Thing ids from lines of text: the first column of each line, skipping blank lines and ``#`` comments. + + The first column is taken so that files written with ``--failed-out`` (id, status, error, ...) can be + passed back as ``--ids-file`` directly. + """ + ids = [] + for line in lines: + line = line.strip().lstrip("") + if not line or line.startswith("#"): + continue + ids.append(_SEPARATORS.split(line, maxsplit=1)[0]) + return ids + + +def read_ids_file(path: str) -> list[str]: + if path == "-": + return read_ids(sys.stdin) + try: + with open(path, encoding="utf-8") as f: + return read_ids(f) + except OSError as e: + raise DittoctlError(f"cannot read ids file {path}: {e}") from e + + +def unique(ids: Iterable[str]) -> list[str]: + return list(dict.fromkeys(ids)) + + +@dataclass +class Selection: + ids: Sequence[str] = () + ids_file: str | None = None + rql_filter: str | None = None + namespaces: Sequence[str] = field(default_factory=list) + include_file: str | None = None + exclude_file: str | None = None + + def describe(self) -> str: + if self.rql_filter: + where = f" in {', '.join(self.namespaces)}" if self.namespaces else "" + return f"things matching {self.rql_filter}{where}" + return "the given things" + + +def _select_by_filter( + client: DittoClient, selection: Selection, streaming_allowed: bool, warn: Callable[[str], None] +) -> list[str]: + def ids_via(transport: Transport) -> list[str]: + found = find_things( + client, + rql_filter=selection.rql_filter, + namespaces=selection.namespaces, + fields="thingId", + sort="+thingId", + transport=transport, + ) + return unique(item["thingId"] for item in found if "thingId" in item) + + transport = choose_transport( + Transport.AUTO, fields="thingId", rql_filter=selection.rql_filter, streaming_allowed=streaming_allowed + ) + ids = ids_via(transport) + if transport == Transport.SSE: + # Ditto can end an SSE search stream early without an error event, e.g. when a search node fails + # mid-stream. A selection for writes must be complete, so check it against the count. + expected = count_things(client, rql_filter=selection.rql_filter, namespaces=selection.namespaces) + if len(ids) < expected: + warn(f"the SSE search stream returned {len(ids)} of {expected} things; selecting again with paging") + ids = ids_via(Transport.PAGING) + return ids + + +def resolve( + client: DittoClient, + selection: Selection, + *, + streaming_allowed: bool = True, + warn: Callable[[str], None] = lambda _m: None, +) -> list[str]: + """The ids of the selected things, without duplicates, in a stable order.""" + explicit = list(selection.ids) + if selection.ids_file: + explicit += read_ids_file(selection.ids_file) + has_ids = bool(selection.ids) or selection.ids_file is not None + if has_ids and selection.rql_filter: + raise DittoctlError("select things either by id (arguments, --ids-file) or by --filter, not both") + if not has_ids and not selection.rql_filter: + raise DittoctlError("no things selected: pass thing ids, --ids-file or --filter") + ids = unique(explicit) if has_ids else _select_by_filter(client, selection, streaming_allowed, warn) + if selection.include_file: + include = set(read_ids_file(selection.include_file)) + ids = [i for i in ids if i in include] + if selection.exclude_file: + exclude = set(read_ids_file(selection.exclude_file)) + ids = [i for i in ids if i not in exclude] + return ids diff --git a/src/dittoctl/core/sse.py b/src/dittoctl/core/sse.py new file mode 100644 index 0000000..6a97de9 --- /dev/null +++ b/src/dittoctl/core/sse.py @@ -0,0 +1,55 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +"""Minimal server-sent events parser (https://html.spec.whatwg.org/multipage/server-sent-events.html).""" + +from __future__ import annotations + +from collections.abc import Iterable, Iterator +from dataclasses import dataclass + + +@dataclass(frozen=True) +class SseEvent: + data: str + event: str | None = None + id: str | None = None + + +def iter_sse(lines: Iterable[str]) -> Iterator[SseEvent]: + """Group the lines of an event stream into events. Comment lines (``:``) are keep-alives and skipped.""" + data: list[str] = [] + event: str | None = None + event_id: str | None = None + for line in lines: + line = line.rstrip("\r\n") + if not line: + if data: + yield SseEvent("\n".join(data), event, event_id) + data, event = [], None + continue + if line.startswith(":"): + continue + name, _, value = line.partition(":") + value = value.removeprefix(" ") + if name == "data": + data.append(value) + elif name == "event": + event = value + elif name == "id": + event_id = value + if data: + yield SseEvent("\n".join(data), event, event_id) diff --git a/src/dittoctl/core/streams.py b/src/dittoctl/core/streams.py new file mode 100644 index 0000000..43e933f --- /dev/null +++ b/src/dittoctl/core/streams.py @@ -0,0 +1,127 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +"""Bounding results and streams: at most N items, or only for a while.""" + +from __future__ import annotations + +import queue +import threading +import time +from collections.abc import Iterable, Iterator +from dataclasses import dataclass +from typing import Generic, TypeVar + +T = TypeVar("T") + + +class Limited(Generic[T]): + """The first ``limit`` items of an iterable; afterwards, ``more`` tells whether there were more. + + The source is read one item further than ``limit`` to find out. + """ + + def __init__(self, items: Iterable[T], limit: int) -> None: + self._items = items + self.limit = limit + self.more = False + + def __iter__(self) -> Iterator[T]: + source = iter(self._items) + try: + for count, item in enumerate(source): + if count == self.limit: + self.more = True + return + yield item + finally: + _close(source) + + +def _close(source: Iterator[object]) -> None: + """Close a generator that wasn't read to the end, e.g. to end its HTTP stream now rather than at exit.""" + close = getattr(source, "close", None) + if close: + close() + + +@dataclass +class _Failure: + error: BaseException + + +_DONE = object() + + +class Timeboxed(Generic[T]): + """Items of a blocking iterable (e.g. an SSE stream) until ``duration`` seconds passed or ``max_items`` arrived. + + The source is read in a background thread, so that waiting for the next item can't outlast the duration. + Afterwards, ``stopped`` is ``"duration"``, ``"max-items"``, or ``None`` if the source ended by itself. + Errors of the source are raised by the iteration. + """ + + def __init__(self, items: Iterable[T], *, duration: float | None = None, max_items: int | None = None) -> None: + self._items = items + self.duration = duration + self.max_items = max_items + self.stopped: str | None = None + + def __iter__(self) -> Iterator[T]: + if self.duration is None and self.max_items is None: + yield from self._items + return + if self.duration is None: + yield from self._first_items() + return + received: queue.Queue[object] = queue.Queue() + + def pump() -> None: + try: + for item in self._items: + received.put(item) + received.put(_DONE) + except BaseException as e: + received.put(_Failure(e)) + + threading.Thread(target=pump, daemon=True, name="dittoctl-stream").start() + deadline = time.monotonic() + self.duration + count = 0 + while self.max_items is None or count < self.max_items: + try: + item = received.get(timeout=max(deadline - time.monotonic(), 0)) + except queue.Empty: + self.stopped = "duration" + return + if item is _DONE: + return + if isinstance(item, _Failure): + raise item.error + count += 1 + yield item # type: ignore[misc] + self.stopped = "max-items" + + def _first_items(self) -> Iterator[T]: + assert self.max_items is not None + source = iter(self._items) + try: + for count, item in enumerate(source, 1): + yield item + if count == self.max_items: + self.stopped = "max-items" + return + finally: + _close(source) diff --git a/src/dittoctl/core/things.py b/src/dittoctl/core/things.py new file mode 100644 index 0000000..304f853 --- /dev/null +++ b/src/dittoctl/core/things.py @@ -0,0 +1,168 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +"""Reading things: single retrieve, retrieve by ids, history and the change stream.""" + +from __future__ import annotations + +import json +from collections.abc import Iterator, Sequence +from typing import Any +from urllib.parse import quote + +from dittoctl.core.client import DittoClient, DittoResponse +from dittoctl.core.conditions import Conditions +from dittoctl.core.sse import iter_sse +from dittoctl.errors import DittoError + +THINGS_PATH = "/api/2/things" +# conservative: keeps GET /api/2/things?ids=... well below common URL length limits +IDS_BATCH_CHARS = 1500 + + +def thing_path(thing_id: str, path: str | None = None) -> str: + """The API path of a thing or of a JSON pointer within it, with each segment URL-encoded.""" + result = f"{THINGS_PATH}/{quote(thing_id, safe=':')}" + segments = [quote(s, safe=":") for s in (path or "").split("/") if s] + return result + "".join(f"/{s}" for s in segments) + + +def get_thing( + client: DittoClient, + thing_id: str, + *, + path: str | None = None, + fields: str | None = None, + at_revision: int | None = None, + at_timestamp: str | None = None, + live: bool = False, + live_timeout: int | None = None, + conditions: Conditions | None = None, +) -> DittoResponse: + """Retrieve a thing (or a path within it), optionally as it was at a historical revision or timestamp. + + ``live`` asks the device itself (Ditto's live channel) instead of the twin; combine it with the + ``live_condition`` and ``live_timeout_strategy`` conditions to fall back to the twin. + """ + headers: dict[str, str] = {} + if at_revision is not None: + headers["at-historical-revision"] = str(at_revision) + if at_timestamp: + headers["at-historical-timestamp"] = at_timestamp + params: dict[str, str] = {"fields": fields} if fields else {} + if live: + params["channel"] = "live" + if live_timeout: + params["timeout"] = f"{live_timeout}s" + return client.get(thing_path(thing_id, path), params=params, headers=headers, conditions=conditions) + + +def _id_batches(thing_ids: Sequence[str]) -> Iterator[list[str]]: + batch: list[str] = [] + length = 0 + for thing_id in thing_ids: + if batch and length + len(thing_id) + 1 > IDS_BATCH_CHARS: + yield batch + batch, length = [], 0 + batch.append(thing_id) + length += len(thing_id) + 1 + if batch: + yield batch + + +def get_things(client: DittoClient, thing_ids: Sequence[str], *, fields: str | None = None) -> Iterator[dict[str, Any]]: + """Retrieve several things by id, in batches. Things that don't exist or aren't visible are left out.""" + for batch in _id_batches(thing_ids): + params = {"ids": ",".join(batch)} + if fields: + params["fields"] = fields + body = client.get(THINGS_PATH, params=params).body + yield from body or [] + + +def watch_things( + client: DittoClient, + *, + rql_filter: str | None = None, + namespaces: Sequence[str] | None = None, + thing_ids: Sequence[str] | None = None, + fields: str | None = None, + extra_fields: str | None = None, +) -> Iterator[dict[str, Any]]: + """Follow the server-sent event stream of thing changes. See https://eclipse.dev/ditto/httpapi-sse.html""" + params: dict[str, str] = {} + if rql_filter: + params["filter"] = rql_filter + if namespaces: + params["namespaces"] = ",".join(namespaces) + if thing_ids: + params["ids"] = ",".join(thing_ids) + if fields: + params["fields"] = fields + if extra_fields: + params["extraFields"] = extra_fields + with client.stream("GET", THINGS_PATH, params=params, headers={"Accept": "text/event-stream"}) as response: + for event in iter_sse(response.iter_lines()): + if event.data.strip(): + yield json.loads(event.data) + + +def thing_history( + client: DittoClient, + thing_id: str, + *, + from_revision: int | None = None, + to_revision: int | None = None, + from_time: str | None = None, + to_time: str | None = None, + fields: str | None = None, + rql_filter: str | None = None, +) -> Iterator[dict[str, Any]]: + """Stream the changes of a thing per revision, i.e. its historical events (needs history retention in Ditto). + + Revisions may be negative to count back from the current one. See https://eclipse.dev/ditto/basic-history.html + """ + params: dict[str, str] = {} + for name, value in ( + ("from-historical-revision", from_revision), + ("to-historical-revision", to_revision), + ("from-historical-timestamp", from_time), + ("to-historical-timestamp", to_time), + ("fields", fields), + ("filter", rql_filter), + ): + if value is not None: + params[name] = str(value) + path = thing_path(thing_id) + with client.stream("GET", path, params=params, headers={"Accept": "text/event-stream"}) as response: + for event in iter_sse(response.iter_lines()): + if not event.data.strip(): + continue + item = json.loads(event.data) + if DittoError.is_error_body(item) and "thingId" not in item: + raise DittoError.from_body(item["status"], item, response.headers.get("correlation-id")) + yield item + + +def thing_description(client: DittoClient, thing_id: str, feature: str | None = None) -> Any: + """The WoT Thing Description Ditto generates from the thing's (or feature's) definition.""" + path = thing_path(thing_id, f"features/{feature}" if feature else None) + return client.get(path, headers={"Accept": "application/td+json"}).body + + +def wot_directory(client: DittoClient) -> Any: + """Ditto's WoT Thing Directory (``/.well-known/wot``, Ditto 3.9+).""" + return client.get("/.well-known/wot", headers={"Accept": "application/td+json"}).body diff --git a/src/dittoctl/core/wot.py b/src/dittoctl/core/wot.py new file mode 100644 index 0000000..ddc3116 --- /dev/null +++ b/src/dittoctl/core/wot.py @@ -0,0 +1,174 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +"""WoT Thing Descriptions: a thing together with its features, and a compact projection. + +The Thing Descriptions Ditto generates are verbose: every property carries four forms (read, write, +merge, observe) that each repeat the content type and Ditto's error schema. Their paths and methods +follow fixed Ditto conventions, so the compact projection keeps only what describes the thing itself: +titles, descriptions, data schemas, units and semantic types, plus the Ditto path of each affordance. +""" + +from __future__ import annotations + +import json +from typing import Any + +from dittoctl.core.client import DittoClient +from dittoctl.core.things import thing_description +from dittoctl.errors import DittoError + +AFFORDANCES = ("properties", "actions", "events") +FEATURES_PREFIX = "features/" +# added by Ditto to every TD, referenced only by the forms' additionalResponses +DITTO_ERROR_SCHEMA = "dittoError" +# repeated data schemas at least this long (as compact JSON) are replaced by a reference to the first one +MIN_SHARED_SCHEMA = 200 + + +def feature_links(td: dict[str, Any]) -> list[str]: + """The names of the features a thing's TD links to (``rel: item``), in order.""" + names = [] + for link in td.get("links") or []: + href = link.get("href", "") + if link.get("rel") == "item" and href.startswith(FEATURES_PREFIX): + names.append(href.removeprefix(FEATURES_PREFIX)) + return names + + +def thing_description_with_features(client: DittoClient, thing_id: str) -> dict[str, Any]: + """The thing's TD with the TDs of all its features under ``features``. + + A feature whose TD can't be retrieved (for example because its model can't be resolved) gets + ``{"error": ...}`` instead, so the rest of the thing is still described. + """ + td = thing_description(client, thing_id) + features: dict[str, Any] = {} + for name in feature_links(td): + try: + features[name] = thing_description(client, thing_id, name) + except DittoError as exc: + features[name] = {"error": exc.error or str(exc.status), "message": exc.message} + if features: + td = {**td, "features": features} + return td + + +def _first_href(forms: list[dict[str, Any]] | None) -> str | None: + return next((form["href"] for form in forms or [] if "href" in form), None) + + +def _compact_affordance(affordance: dict[str, Any]) -> dict[str, Any]: + result: dict[str, Any] = {} + path = _first_href(affordance.get("forms")) + if path: + result["path"] = path + result.update((k, v) for k, v in affordance.items() if k not in ("forms", "additionalResponses")) + return result + + +def _prefixes(td: dict[str, Any]) -> dict[str, str]: + context = td.get("@context") + entries = context if isinstance(context, list) else [context] + prefixes: dict[str, str] = {} + for entry in entries: + if isinstance(entry, dict): + prefixes.update((k, v) for k, v in entry.items() if isinstance(v, str)) + return prefixes + + +def compact_td(td: dict[str, Any]) -> dict[str, Any]: + """The parts of a TD that describe the thing, without forms, security and Ditto boilerplate. + + Each affordance gets the ``path`` of its first form, relative to the TD's base: the thing for a + thing's TD, ``features/`` for a feature's TD. + """ + if "error" in td and "title" not in td: + return td + result: dict[str, Any] = {} + for key in ("title", "description"): + if key in td: + result[key] = td[key] + if td.get("@type") not in (None, "Thing"): + result["@type"] = td["@type"] + model = next((link["href"] for link in td.get("links") or [] if link.get("rel") == "type"), None) + if model: + result["model"] = model + for kind in AFFORDANCES: + affordances = td.get(kind) + if affordances: + result[kind] = {name: _compact_affordance(a) for name, a in affordances.items()} + schemas = {k: v for k, v in (td.get("schemaDefinitions") or {}).items() if k != DITTO_ERROR_SCHEMA} + if schemas: + result["schemaDefinitions"] = schemas + return result + + +def compact_thing_description(td: dict[str, Any], *, schema_descriptions: bool = True) -> dict[str, Any]: + """:func:`compact_td` for a TD from :func:`thing_description_with_features`, or for a single TD. + + The ``@context`` prefixes of all TDs (e.g. ``om2`` for units) are merged into one ``prefixes`` + map. A feature described exactly like an earlier one becomes ``{"sameAs": ""}``, and + a data schema repeated within the properties, actions and events (e.g. the same schema for each day of + the week) becomes a JSON Schema reference to its first occurrence, ``{"$ref": "#/features/..."}``. Without + ``schema_descriptions``, the descriptions inside data schemas are left out; those of the properties, + actions and events themselves stay. + """ + prefixes = _prefixes(td) + result = compact_td(td) + features: dict[str, Any] = {} + seen: list[tuple[dict[str, Any], str]] = [] + for name, feature_td in (td.get("features") or {}).items(): + prefixes.update(_prefixes(feature_td)) + compact = compact_td(feature_td) + same = next((earlier for described, earlier in seen if described == compact), None) + if same is not None: + features[name] = {"sameAs": same} + continue + features[name] = compact + if "error" not in compact: + seen.append((compact, name)) + if features: + result["features"] = features + result = _share_schemas(result, "", {}, inside=False, descriptions=schema_descriptions) + return {"prefixes": prefixes, **result} if prefixes else result + + +def _pointer(path: str, key: str) -> str: + return f"{path}/{key.replace('~', '~0').replace('/', '~1')}" + + +def _share_schemas(node: Any, path: str, seen: dict[str, str], *, inside: bool, descriptions: bool) -> Any: + """Replace repeated data schemas below the affordances (objects with a ``path``) by references.""" + if isinstance(node, list): + return [ + _share_schemas(v, f"{path}/{i}", seen, inside=inside, descriptions=descriptions) for i, v in enumerate(node) + ] + if not isinstance(node, dict): + return node + # only data schemas (with a type), not maps of property names, so that a reference is unambiguous + if inside and "type" in node: + key = json.dumps(node, sort_keys=True, separators=(",", ":"), ensure_ascii=False) + if len(key) >= MIN_SHARED_SCHEMA: + if key in seen: + return {"$ref": "#" + seen[key]} + seen[key] = path + affordance = "path" in node and not inside + return { + k: _share_schemas(v, _pointer(path, k), seen, inside=inside or affordance, descriptions=descriptions) + for k, v in node.items() + if descriptions or not inside or k != "description" + } diff --git a/src/dittoctl/core/writes.py b/src/dittoctl/core/writes.py new file mode 100644 index 0000000..c81ccc3 --- /dev/null +++ b/src/dittoctl/core/writes.py @@ -0,0 +1,253 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +"""Per-thing write operations for the bulk engine. Each returns an :class:`Outcome` or raises; the engine +classifies errors. With ``dry_run`` nothing is written and the outcome describes the planned request.""" + +from __future__ import annotations + +from collections.abc import Callable, Mapping, Sequence +from typing import Any + +from dittoctl.core.bulk import Category, Outcome, is_unchanged +from dittoctl.core.client import DittoClient +from dittoctl.core.conditions import Conditions +from dittoctl.core.jsonops import Equality, array_add, array_remove, deep_equal, segments +from dittoctl.core.things import thing_path +from dittoctl.errors import DittoctlError, DittoError + +Operation = Callable[[str], Outcome] + + +def _planned(thing_id: str, method: str, path: str, body: Any = None, conditions: Conditions | None = None) -> Outcome: + plan: dict[str, Any] = {"method": method, "path": path} + if body is not None: + plan["body"] = body + if conditions and not conditions.is_empty(): + plan["headers"] = conditions.headers() + if params := conditions.params(): + plan["params"] = params + return Outcome(thing_id, Category.PLANNED, detail=plan) + + +def merge_operation( + client: DittoClient, path: str, body: Any, conditions: Conditions, *, dry_run: bool = False +) -> Operation: + """PATCH (merge) ``body`` at ``path`` of each thing; things that don't exist are reported as not found. + + Ditto creates a thing that doesn't exist when merging at its root, so a mistyped id would silently + create a new thing. Root merges therefore send ``If-Match: *`` (only if the thing exists), unless the + caller set ``If-Match`` or ``If-None-Match`` itself. Merges below the root fail with 404 anyway. + """ + require_existing = not segments(path) and not conditions.if_match and not conditions.if_none_match + if require_existing: + conditions = conditions.replace(if_match="*") + + def operation(thing_id: str) -> Outcome: + target = thing_path(thing_id, path) + if dry_run: + return _planned(thing_id, "PATCH", target, body, conditions) + try: + response = client.patch(target, json=body, conditions=conditions) + except DittoError as e: + # with If-Match: *, a failed precondition that isn't If-Equal's "unchanged" means the thing is missing + if require_existing and e.status == 412 and not e.condition_failed and not is_unchanged(e): + return Outcome(thing_id, Category.NOT_FOUND, 404, "things:thing.notfound", "the thing doesn't exist") + raise + return Outcome(thing_id, Category.OK, response.status) + + return operation + + +def delete_operation(client: DittoClient, conditions: Conditions, *, dry_run: bool = False) -> Operation: + def operation(thing_id: str) -> Outcome: + target = thing_path(thing_id) + if dry_run: + return _planned(thing_id, "DELETE", target, conditions=conditions) + response = client.delete(target, conditions=conditions) + return Outcome(thing_id, Category.OK, response.status) + + return operation + + +def put_operation( + client: DittoClient, + things: Mapping[str, Any], + conditions: Conditions, + *, + dry_run: bool = False, +) -> Operation: + """PUT the given JSON of each thing. With ``If-None-Match: *`` existing things count as 'exists'.""" + create_only = conditions.if_none_match == "*" + + def operation(thing_id: str) -> Outcome: + target = thing_path(thing_id) + if dry_run: + return _planned(thing_id, "PUT", target, things[thing_id], conditions) + try: + response = client.put(target, json=things[thing_id], conditions=conditions) + except DittoError as e: + if create_only and e.status == 412 and not e.condition_failed: + return Outcome(thing_id, Category.EXISTS, 412, e.error, "the thing already exists") + raise + return Outcome(thing_id, Category.OK, response.status) + + return operation + + +def array_operation( + client: DittoClient, + path: str, + items: Sequence[Any], + *, + remove: bool = False, + as_set: bool = False, + equal: Equality = deep_equal, + conflict_retries: int = 3, + dry_run: bool = False, +) -> Operation: + """Add items to, or remove them from, the array at ``path`` of each thing. + + Read-modify-write with optimistic concurrency: the array is read together with its ETag and written with + ``If-Match`` (``If-None-Match: *`` if it doesn't exist yet). If another writer changed it in between, it is + read again, up to ``conflict_retries`` times. Things whose array wouldn't change are not written at all. + """ + + def operation(thing_id: str) -> Outcome: + target = thing_path(thing_id, path) + for _ in range(conflict_retries + 1): + try: + response = client.get(target) + current, etag = response.body, response.etag + except DittoError as e: + if e.status != 404: + raise + current, etag = None, None + if current is not None and not isinstance(current, list): + raise DittoctlError(f"{path} is not an array but {type(current).__name__}") + updated = ( + array_remove(current, items, equal=equal) + if remove + else array_add(current, items, as_set=as_set, equal=equal) + ) + if current is not None and deep_equal(current, updated): + return Outcome(thing_id, Category.UNCHANGED, message="nothing to change") + if current is None and remove: + return Outcome(thing_id, Category.UNCHANGED, message="the array doesn't exist") + conditions = Conditions(if_match=etag) if etag else Conditions(if_none_match="*") + if dry_run: + outcome = _planned(thing_id, "PUT", target, updated, conditions) + outcome.detail["before"] = current + return outcome + try: + result = client.put(target, json=updated, conditions=conditions) + return Outcome(thing_id, Category.OK, result.status) + except DittoError as e: + if e.status != 412: + raise + # changed concurrently: read again and recompute + return Outcome( + thing_id, Category.CONFLICT, 412, "conflict", f"modified concurrently {conflict_retries + 1} times in a row" + ) + + return operation + + +def migrate_definition_operation( + client: DittoClient, + definition_url: str, + *, + payload: Any = None, + patch_conditions: Mapping[str, str] | None = None, + initialize_defaults: bool = False, + dry_run: bool = False, +) -> Operation: + """Migrate each thing to a new thing definition (WoT Thing Model) via Ditto's ``migrateDefinition``. + + The dry run is done by Ditto (``dry-run=true``): the outcome's ``detail`` is the migration result. + """ + body: dict[str, Any] = {"thingDefinitionUrl": definition_url} + if payload is not None: + body["migrationPayload"] = payload + if patch_conditions: + body["patchConditions"] = dict(patch_conditions) + if initialize_defaults: + body["initializeMissingPropertiesFromDefaults"] = True + + def operation(thing_id: str) -> Outcome: + params = {"dry-run": "true"} if dry_run else None + response = client.post(thing_path(thing_id, "migrateDefinition"), json=body, params=params, retry=True) + category = Category.PLANNED if dry_run else Category.OK + return Outcome(thing_id, category, response.status, detail=response.body) + + return operation + + +def message_operation( + client: DittoClient, + subject: str, + body: Any, + *, + feature: str | None = None, + outbox: bool = False, + timeout: int | None = None, + content_type: str | None = None, + paginate: tuple[str, str] | None = None, + max_pages: int = 100, + dry_run: bool = False, +) -> Operation: + """Send a message to (inbox) or from (outbox) each thing or one of its features. + + ``timeout=0`` doesn't wait for a response (Ditto answers 202). Otherwise the response is in ``detail``. + ``paginate=(response_field, request_field)`` follows paged answers: as long as a response contains + ``response_field``, the message is sent again with its value as ``request_field``; ``detail`` is then the + list of all responses. + """ + box = "outbox" if outbox else "inbox" + if paginate and not isinstance(body, dict | None): + raise DittoctlError("--paginate needs a JSON object as message payload (or none)") + + def send(target: str, payload: Any) -> Any: + params = {"timeout": str(timeout)} if timeout is not None else None + if isinstance(payload, str | bytes) and content_type and "json" not in content_type: + return client.post(target, content=payload, content_type=content_type, params=params) + return client.post(target, json=payload, content_type=content_type, params=params) + + def operation(thing_id: str) -> Outcome: + path = f"features/{feature}/{box}/messages/{subject}" if feature else f"{box}/messages/{subject}" + target = thing_path(thing_id, path) + if dry_run: + return _planned(thing_id, "POST", target, body) + response = send(target, body) + if not paginate: + return Outcome(thing_id, Category.OK, response.status, detail=response.body) + response_field, request_field = paginate + pages = [response.body] + while isinstance(response.body, dict) and response.body.get(response_field) and len(pages) < max_pages: + response = send(target, {**(body or {}), request_field: response.body[response_field]}) + pages.append(response.body) + if isinstance(response.body, dict) and response.body.get(response_field): + return Outcome( + thing_id, + Category.FAILED, + response.status, + "pagination", + f"stopped after --max-pages {max_pages} with more pages left", + detail=pages, + ) + return Outcome(thing_id, Category.OK, response.status, detail=pages) + + return operation diff --git a/src/dittoctl/errors.py b/src/dittoctl/errors.py new file mode 100644 index 0000000..52ce388 --- /dev/null +++ b/src/dittoctl/errors.py @@ -0,0 +1,162 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +"""Exception hierarchy and process exit codes.""" + +from __future__ import annotations + +from enum import IntEnum +from typing import Any + +import httpx + + +class ExitCode(IntEnum): + OK = 0 + ERROR = 1 + PARTIAL_FAILURE = 2 + AUTH = 3 + NOT_FOUND = 4 + ABORTED = 5 + # a check found what it checks for: differences (diff), denied permissions, invalid RQL, mismatches (verify) + CHECK_FAILED = 6 + INTERRUPTED = 130 + + +class DittoctlError(Exception): + """Base class for all errors dittoctl reports to the user.""" + + exit_code: ExitCode = ExitCode.ERROR + + +class ConfigError(DittoctlError): + pass + + +class AuthError(DittoctlError): + exit_code = ExitCode.AUTH + + +class AbortedError(DittoctlError): + exit_code = ExitCode.ABORTED + + +class CheckFailedError(DittoctlError): + exit_code = ExitCode.CHECK_FAILED + + +class InterruptedRunError(DittoctlError): + """A bulk run stopped with Ctrl+C; the things in flight were finished.""" + + exit_code = ExitCode.INTERRUPTED + + +class DittoError(DittoctlError): + """An error response returned by Ditto. + + Ditto error bodies have the shape + ``{"status": 404, "error": "things:thing.notfound", "message": "...", "description": "...", "href": "..."}``. + """ + + def __init__( + self, + status: int, + error: str | None = None, + message: str | None = None, + description: str | None = None, + href: str | None = None, + correlation_id: str | None = None, + body: Any = None, + ) -> None: + self.status = status + self.error = error + self.message = message + self.description = description + self.href = href + self.correlation_id = correlation_id + self.body = body + super().__init__(self._summary()) + + @property + def exit_code(self) -> ExitCode: # type: ignore[override] + if self.status == 401: + return ExitCode.AUTH + if self.status == 404: + return ExitCode.NOT_FOUND + return ExitCode.ERROR + + def _summary(self) -> str: + head = f"{self.status}" + if self.error: + head += f" {self.error}" + return f"{head}: {self.message}" if self.message else head + + @property + def condition_failed(self) -> bool: + """The request's RQL ``condition`` didn't match (e.g. ``things:condition.failed``). + + Not to be confused with ``things:precondition.failed`` (If-Match, If-None-Match, If-Equal: skip). + """ + return self.status == 412 and (self.error or "").rpartition(":")[2] == "condition.failed" + + @staticmethod + def is_error_body(body: Any) -> bool: + """Whether a JSON value has the shape of a Ditto error, e.g. an error event within an SSE stream.""" + return isinstance(body, dict) and isinstance(body.get("status"), int) and isinstance(body.get("error"), str) + + @classmethod + def from_body(cls, status: int, body: dict[str, Any], correlation_id: str | None = None) -> DittoError: + return cls( + status=status, + error=body.get("error"), + message=body.get("message"), + description=body.get("description"), + href=body.get("href"), + correlation_id=correlation_id, + body=body, + ) + + @classmethod + def from_response(cls, response: httpx.Response) -> DittoError: + correlation_id = response.headers.get("correlation-id") + try: + body = response.json() + except ValueError: + body = response.text or None + if isinstance(body, dict): + return cls.from_body(response.status_code, body, correlation_id) + # an HTML error page (e.g. from a reverse proxy in front of Ditto) is useless on a terminal + is_html = "html" in response.headers.get("content-type", "") or ( + isinstance(body, str) and body.lstrip().lower().startswith((" Callable[[str], Any]: + """``out.write``, but on a terminal with JSON syntax highlighting, as for single JSON documents.""" + if not out.isatty(): + return out.write + console = Console(file=out, emoji=False, markup=False, highlight=False, soft_wrap=True) + highlight = JSONHighlighter() + return lambda text: console.print(highlight(Text(text)), end="") + + +def write_json_array(items: Iterable[Any], out: TextIO, *, compact: bool = False) -> int: + """A JSON array, written item by item: pretty-printed, or on a single line with ``compact``.""" + write = json_writer(out) + count = 0 + write("[") + for item in items: + if compact: + write(("," if count else "") + json.dumps(item, ensure_ascii=False, separators=(",", ":"))) + else: + write(",\n" if count else "\n") + text = json.dumps(item, indent=2, ensure_ascii=False) + write("\n".join(" " + line for line in text.splitlines())) + count += 1 + write("]\n" if compact or not count else "\n]\n") + return count + + +def write_ndjson(items: Iterable[Any], out: TextIO, *, flush: bool = False) -> int: + write = json_writer(out) + count = 0 + for item in items: + write(json.dumps(item, ensure_ascii=False, separators=(",", ":")) + "\n") + if flush: + out.flush() + count += 1 + return count + + +def write_ids(items: Iterable[Any], out: TextIO, key: str = "thingId") -> int: + count = 0 + for item in items: + if isinstance(item, dict) and key in item: + out.write(f"{item[key]}\n") + count += 1 + return count + + +def write_items( + items: Iterable[Any], + fmt: str, + out: TextIO, + *, + columns: Columns | None = None, + delimiter: str = ",", + header: bool = True, + excel: bool = False, + compact: bool = False, + warn: Callable[[str], None] = lambda _m: None, +) -> int: + """Write items in the given format and return how many were written; ``compact`` puts a JSON array on one line.""" + if fmt == "json": + return write_json_array(items, out, compact=compact) + if fmt == "ndjson": + return write_ndjson(items, out) + if fmt == "ids": + return write_ids(items, out) + if fmt == "csv": + return write_csv(items, out, columns=columns, delimiter=delimiter, header=header, excel=excel, warn=warn) + if fmt == "table": + # on a terminal the table fits its width; elsewhere (pipes, files) lines are never wrapped + width = None if out.isatty() else 100_000 + return print_table( + items, + Console(emoji=False, markup=False, file=out, width=width, soft_wrap=False), + columns=columns, + warn=warn, + ) + raise ValueError(f"unknown format: {fmt}") + + +__all__ = ["ITEM_FORMATS", "Columns", "write_csv", "write_ids", "write_items", "write_json_array", "write_ndjson"] diff --git a/src/dittoctl/formats/flatten.py b/src/dittoctl/formats/flatten.py new file mode 100644 index 0000000..935d91f --- /dev/null +++ b/src/dittoctl/formats/flatten.py @@ -0,0 +1,88 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +"""Turn nested JSON into flat ``/``-separated paths for tabular output.""" + +from __future__ import annotations + +import json +from collections.abc import Iterable +from typing import Any + +SEPARATOR = "/" + + +def flatten(value: Any, prefix: str = "") -> dict[str, Any]: + """``{"a": {"b": 1}, "c": [1, 2]}`` becomes ``{"a/b": 1, "c": [1, 2]}``; arrays stay whole.""" + if not isinstance(value, dict): + return {prefix or "value": value} + if not value and prefix: + return {prefix: {}} + result: dict[str, Any] = {} + for key, child in value.items(): + path = f"{prefix}{SEPARATOR}{key}" if prefix else str(key) + if isinstance(child, dict) and child: + result.update(flatten(child, path)) + else: + result[path] = child + return result + + +def get_path(value: Any, path: str) -> Any: + """The value at a ``/``-separated path, or ``None`` if any segment is missing.""" + current = value + for segment in path.strip(SEPARATOR).split(SEPARATOR): + if not isinstance(current, dict) or segment not in current: + return None + current = current[segment] + return current + + +def cell(value: Any) -> str: + """Render a JSON value for a table or CSV cell.""" + if value is None: + return "" + if isinstance(value, bool): + return "true" if value else "false" + if isinstance(value, str): + return value + if isinstance(value, int | float): + return json.dumps(value) + return json.dumps(value, ensure_ascii=False, separators=(",", ":")) + + +def short_headers(paths: Iterable[str]) -> dict[str, str]: + """Map each path to its shortest unambiguous suffix. + + ``features/temp/properties/value`` becomes ``value`` if no other column ends in ``value``, or + ``temp/properties/value`` if another column ends in ``properties/value``. + """ + paths = list(paths) + split = {p: p.split(SEPARATOR) for p in paths} + result: dict[str, str] = {} + for path, segments in split.items(): + for length in range(1, len(segments) + 1): + suffix = segments[-length:] + clashes = any( + other != path and others[-length:] == suffix and len(others) >= length + for other, others in split.items() + ) + if not clashes: + result[path] = SEPARATOR.join(suffix) + break + else: + result[path] = path + return result diff --git a/src/dittoctl/formats/tabular.py b/src/dittoctl/formats/tabular.py new file mode 100644 index 0000000..93f5002 --- /dev/null +++ b/src/dittoctl/formats/tabular.py @@ -0,0 +1,142 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +"""CSV and table output with column discovery.""" + +from __future__ import annotations + +import csv +import re +from collections.abc import Callable, Iterable, Iterator, Sequence +from dataclasses import dataclass +from datetime import UTC, datetime +from itertools import chain, islice +from typing import Any, TextIO + +from rich.console import Console +from rich.table import Table + +from dittoctl.formats.flatten import cell, flatten, get_path, short_headers + +_ISO_TIMESTAMP = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$") + + +def excel_timestamp(value: str) -> str: + """``2026-11-06T15:19:54.123Z`` becomes ``2026-11-06 15:19:54`` (UTC), which Excel recognizes as a date.""" + if not _ISO_TIMESTAMP.match(value): + return value + parsed = datetime.fromisoformat(value.replace("Z", "+00:00")) + return parsed.astimezone(UTC).strftime("%Y-%m-%d %H:%M:%S") + + +@dataclass +class Columns: + """Column selection: explicit paths, or discovered from the first ``discover_rows`` rows (0: all rows).""" + + explicit: Sequence[str] | None = None + discover_rows: int = 100 + short: bool = False + + +class _ColumnResolver: + def __init__(self, columns: Columns, warn: Callable[[str], None]) -> None: + self.columns = columns + self.warn = warn + self.paths: list[str] = [] + self._known: set[str] = set() + self._warned: set[str] = set() + + def resolve(self, items: Iterable[Any]) -> Iterator[Any]: + """Determine the columns; returns an iterator over all items (buffered ones first).""" + iterator = iter(items) + if self.columns.explicit: + self.paths = list(self.columns.explicit) + return iterator + limit = self.columns.discover_rows + buffered = list(iterator) if limit <= 0 else list(islice(iterator, limit)) + for item in buffered: + for path in flatten(item): + if path not in self._known: + self._known.add(path) + self.paths.append(path) + return chain(buffered, iterator) + + def row(self, item: Any) -> list[Any]: + if self.columns.explicit: + # explicit columns may name a parent object, so look the paths up in the nested item + return [get_path(item, path) for path in self.paths] + flat = flatten(item) + unknown = flat.keys() - self._known - self._warned + if unknown: + self._warned.update(unknown) + names = ", ".join(sorted(unknown)[:5]) + (" …" if len(unknown) > 5 else "") + self.warn( + f"column(s) {names} first appeared after the first {self.columns.discover_rows} rows and are left " + "out; pass --discover-rows 0 or --columns" + ) + return [flat.get(path) for path in self.paths] + + def headers(self) -> list[str]: + if not self.columns.short: + return list(self.paths) + mapping = short_headers(self.paths) + return [mapping[p] for p in self.paths] + + +def write_csv( + items: Iterable[Any], + out: TextIO, + *, + columns: Columns | None = None, + delimiter: str = ",", + header: bool = True, + excel: bool = False, + warn: Callable[[str], None] = lambda _m: None, +) -> int: + """Stream items as CSV rows; only the discovery window is held in memory. Returns the number of rows.""" + resolver = _ColumnResolver(columns or Columns(), warn) + remaining = resolver.resolve(items) + writer = csv.writer(out, delimiter=delimiter, lineterminator="\n") + if header: + writer.writerow(resolver.headers()) + count = 0 + for item in remaining: + values = [cell(v) for v in resolver.row(item)] + if excel: + values = [excel_timestamp(v) for v in values] + writer.writerow(values) + count += 1 + return count + + +def print_table( + items: Iterable[Any], + console: Console, + *, + columns: Columns | None = None, + warn: Callable[[str], None] = lambda _m: None, +) -> int: + """Render items as a table. All rows are collected first, so use CSV or NDJSON for large results.""" + columns = columns or Columns(discover_rows=0) + resolver = _ColumnResolver(columns, warn) + rows = [resolver.row(item) for item in resolver.resolve(items)] + table = Table(box=None, pad_edge=False, header_style="bold") + for name in resolver.headers(): + table.add_column(name, overflow="fold") + for row in rows: + table.add_row(*(cell(v) for v in row)) + console.print(table) + return len(rows) diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..d482981 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,55 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +from __future__ import annotations + +import io +import os +import sys +from dataclasses import dataclass + +import pytest + +from dittoctl.cli.main import main + + +@pytest.fixture(autouse=True) +def isolated_env(tmp_path, monkeypatch): + """Keep tests away from the real config, keyring, DITTOCTL_* variables and agent detection.""" + for key in list(os.environ): + if key.startswith("DITTOCTL_") or key in ("CLAUDECODE", "AI_AGENT"): + monkeypatch.delenv(key) + monkeypatch.setenv("DITTOCTL_CONFIG_DIR", str(tmp_path / "config")) + monkeypatch.setenv("DITTOCTL_STATE_DIR", str(tmp_path / "state")) + monkeypatch.setenv("DITTOCTL_SECRET_STORE", "file") + + +@dataclass +class Result: + exit_code: int + stdout: str + stderr: str + + +@pytest.fixture +def run(capsys, monkeypatch): + def _run(*args: str, stdin: str | None = None) -> Result: + monkeypatch.setattr(sys, "stdin", io.StringIO(stdin or "")) + code = main(list(args)) + out, err = capsys.readouterr() + return Result(int(code), out, err) + + return _run diff --git a/tests/test_agent.py b/tests/test_agent.py new file mode 100644 index 0000000..e5aa65e --- /dev/null +++ b/tests/test_agent.py @@ -0,0 +1,374 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +"""Agent mode, protected contexts, bounded output and the other features for use by LLM agents.""" + +from __future__ import annotations + +import json +import threading +import time + +import httpx +import pytest +import respx + +from dittoctl.core import rql +from dittoctl.core.fields import field_stats, json_type +from dittoctl.core.jsonops import json_diff +from dittoctl.core.streams import Limited, Timeboxed +from dittoctl.errors import ExitCode +from test_search_things import paged_search + +URL = "http://ditto.test" +A = "org.example:a" +B = "org.example:b" + + +@pytest.fixture +def ditto(): + with respx.mock(base_url=URL, assert_all_called=False) as mock: + yield mock + + +@pytest.fixture +def agent(monkeypatch): + monkeypatch.setenv("CLAUDECODE", "1") + + +# --- agent mode ------------------------------------------------------------------------------- + + +def test_agent_mode_is_detected_and_can_be_switched_off(run, ditto, monkeypatch): + ditto.get(f"/api/2/things/{A}").mock(return_value=httpx.Response(200, json={"thingId": A, "attributes": {}})) + assert run("--url", URL, "things", "get", A).stdout.count("\n") > 1 # indented + monkeypatch.setenv("AI_AGENT", "some-agent") + assert run("--url", URL, "things", "get", A).stdout == '{"thingId":"org.example:a","attributes":{}}\n' + assert run("--url", URL, "--no-agent", "things", "get", A).stdout.count("\n") > 1 + monkeypatch.delenv("AI_AGENT") + assert run("--url", URL, "--agent", "things", "get", A).stdout.count("\n") == 1 + + +def test_agent_errors_are_json(run, ditto, agent): + ditto.get(f"/api/2/things/{A}").mock( + return_value=httpx.Response( + 404, + json={"status": 404, "error": "things:thing.notfound", "message": "not found", "description": "Check it."}, + headers={"correlation-id": "c-1"}, + ) + ) + result = run("--url", URL, "things", "get", A) + assert result.exit_code == ExitCode.NOT_FOUND + assert json.loads(result.stderr) == { + "exitCode": 4, + "message": "not found", + "status": 404, + "error": "things:thing.notfound", + "description": "Check it.", + "correlationId": "c-1", + } + usage = json.loads(run("--url", URL, "things", "get").stderr) + assert usage["exitCode"] == 1 + assert usage["error"] == "usage" + assert "dittoctl things get [OPTIONS] THING_ID..." in usage["usage"] + + +# --- bounded output --------------------------------------------------------------------------- + + +def test_agents_get_a_limited_search_result(run, ditto, agent): + ditto.get("/api/2/search/things").mock(side_effect=paged_search(120)) + result = run("--url", URL, "things", "search", "--fields", "thingId,attributes") + assert result.stdout.count("\n") == 50 + assert "Showing the first 50 things; there are more" in result.stderr + assert run("--url", URL, "things", "search", "--fields", "thingId,attributes", "--all").stdout.count("\n") == 120 + limited = run("--url", URL, "things", "search", "--fields", "thingId,attributes", "--limit", "70") + assert limited.stdout.count("\n") == 70 + assert "there are more" not in limited.stderr + + +def test_search_is_not_limited_without_agent(run, ditto): + ditto.get("/api/2/search/things").mock(side_effect=paged_search(120)) + assert run("--url", URL, "things", "search", "--fields", "thingId,attributes").stdout.count("\n") == 120 + + +def test_limited_closes_its_source(): + closed = [] + + def source(): + try: + yield from range(10) + finally: + closed.append(True) + + limited = Limited(source(), 3) + assert list(limited) == [0, 1, 2] + assert limited.more + assert closed == [True] + exact = Limited(iter(range(3)), 3) + assert list(exact) == [0, 1, 2] + assert not exact.more + + +def test_timeboxed_stops_a_blocking_stream(): + release = threading.Event() + + def stream(): + yield 1 + release.wait(5) # blocks like an SSE stream without events + yield 2 + + started = time.monotonic() + boxed = Timeboxed(stream(), duration=0.2) + assert list(boxed) == [1] + assert boxed.stopped == "duration" + assert time.monotonic() - started < 2 + release.set() + + +def test_timeboxed_max_items_and_errors(): + boxed = Timeboxed(iter(range(10)), max_items=2) + assert list(boxed) == [0, 1] + assert boxed.stopped == "max-items" + timed = Timeboxed(iter(range(10)), duration=5, max_items=3) + assert list(timed) == [0, 1, 2] + assert timed.stopped == "max-items" + + def failing(): + yield 1 + raise ValueError("broken stream") + + with pytest.raises(ValueError, match="broken stream"): + list(Timeboxed(failing(), duration=5)) + + +def test_watch_max_events_and_explicit_ids_ignore_context_namespaces(run, ditto): + assert run("config", "add-context", "dev", "--url", URL, "--namespace", "other").exit_code == 0 + stream = b"".join(f'data: {{"thingId":"{A}","attributes":{{"n":{i}}}}}\n\n'.encode() for i in range(3)) + route = ditto.get("/api/2/things").mock(return_value=httpx.Response(200, content=stream)) + result = run("things", "watch", "--ids", A, "--max-events", "2") + assert result.exit_code == 0 + assert result.stdout.count("\n") == 2 + assert "namespaces" not in route.calls.last.request.url.params + run("things", "watch", "--max-events", "1") + assert route.calls.last.request.url.params["namespaces"] == "other" + + +def test_history_limit(run, ditto, agent): + stream = b"".join(f'data: {{"thingId":"{A}","_revision":{i}}}\n\n'.encode() for i in range(60)) + ditto.get(f"/api/2/things/{A}").mock(return_value=httpx.Response(200, content=stream)) + result = run("--url", URL, "things", "history", A, "--from-revision", "1") + assert result.stdout.count("\n") == 50 + assert "there are more" in result.stderr + assert run("--url", URL, "things", "history", A, "--from-revision", "1", "--limit", "5").stdout.count("\n") == 5 + + +# --- results of bulk writes ------------------------------------------------------------------- + + +def test_results_lines_and_summary(run, ditto, agent): + ditto.patch(f"/api/2/things/{A}").mock(return_value=httpx.Response(204)) + ditto.patch(f"/api/2/things/{B}").mock( + return_value=httpx.Response( + 400, + json={ + "status": 400, + "error": "wot:payload.validation.error", + "message": "not conform", + "description": "not defined in the model: [x]", + }, + ) + ) + result = run("--url", URL, "things", "set", "attributes/x", "1", A, B) + assert result.exit_code == ExitCode.PARTIAL_FAILURE + lines = [json.loads(line) for line in result.stdout.splitlines()] + assert lines[0] == { + "thingId": B, + "result": "failed", + "status": 400, + "error": "wot:payload.validation.error", + "message": "not conform", + "description": "not defined in the model: [x]", + } + assert lines[1]["summary"]["counts"] == {"ok": 1, "failed": 1} + assert lines[1]["summary"]["failures"] == 1 + every = run("--url", URL, "things", "set", "attributes/x", "1", A, B, "--results", "all") + assert sorted(json.loads(line).get("thingId", "") for line in every.stdout.splitlines()) == ["", A, B] + assert run("--url", URL, "things", "set", "attributes/x", "1", A, B, "--results", "none").stdout == "" + + +def test_dry_run_results_show_the_first_planned_requests(run, ditto, agent, tmp_path): + ids = tmp_path / "ids.txt" + ids.write_text("\n".join(f"org.example:t{i}" for i in range(10))) + result = run("--url", URL, "things", "set", "attributes/x", "1", "--ids-file", str(ids), "--dry-run") + lines = [json.loads(line) for line in result.stdout.splitlines()] + assert [line.get("result") for line in lines] == ["planned"] * 3 + [None] + assert lines[0]["plan"]["headers"] == {"If-Match": "*", "If-Equal": "skip"} + assert lines[-1]["summary"]["dryRun"] is True + + +# --- protected contexts ----------------------------------------------------------------------- + + +def test_single_writes_need_protected_context_confirmation(run, ditto): + assert run("config", "add-context", "prod", "--url", URL, "--protected").exit_code == 0 + route = ditto.put("/api/2/policies/org.example:p").mock(return_value=httpx.Response(201, json={})) + refused = run("policies", "put", "org.example:p", "-d", "{}") + assert refused.exit_code == ExitCode.ABORTED + assert "--confirm-context prod" in refused.stderr + assert route.call_count == 0 + assert run("policies", "put", "org.example:p", "-d", "{}", "--confirm-context", "prod").exit_code == 0 + assert route.call_count == 1 + + +def test_api_only_guards_writing_methods(run, ditto): + assert run("config", "add-context", "prod", "--url", URL, "--protected").exit_code == 0 + ditto.get("/api/2/whoami").mock(return_value=httpx.Response(200, json={})) + ditto.delete(f"/api/2/things/{A}").mock(return_value=httpx.Response(204)) + assert run("api", "GET", "/api/2/whoami").exit_code == 0 + assert run("api", "DELETE", f"/api/2/things/{A}").exit_code == ExitCode.ABORTED + + +def test_agents_dont_write_to_protected_contexts(run, ditto, agent): + assert run("config", "add-context", "prod", "--url", URL, "--protected").exit_code == 0 + route = ditto.patch(f"/api/2/things/{A}").mock(return_value=httpx.Response(204)) + for args in (("things", "set", "attributes/x", "1", A), ("things", "put", A, "-d", "{}")): + result = run(*args, "--confirm-context", "prod") + assert result.exit_code == ExitCode.ABORTED + assert ( + "doesn't write to protected contexts in agent mode" in json.loads(result.stderr.splitlines()[-1])["message"] + ) + assert route.call_count == 0 + assert run("things", "set", "attributes/x", "1", A, "--dry-run").exit_code == 0 + + +# --- checks, diff, RQL hints, fields ---------------------------------------------------------- + + +def test_json_diff(): + old = {"thingId": A, "attributes": {"on": False, "color": {"r": 1}, "tags": [1]}} + new = {"thingId": A, "attributes": {"on": True, "color": {"r": 1}, "room": "lab"}} + assert json_diff(old, new) == [ + {"op": "replace", "path": "/attributes/on", "old": False, "new": True}, + {"op": "add", "path": "/attributes/room", "new": "lab"}, + {"op": "remove", "path": "/attributes/tags", "old": [1]}, + ] + assert json_diff(old, old) == [] + assert json_diff(1, 2) == [{"op": "replace", "path": "/", "old": 1, "new": 2}] + + +def test_diff_as_json(run, ditto, agent, tmp_path): + ditto.get(f"/api/2/things/{A}").mock(return_value=httpx.Response(200, json={"attributes": {"x": 1}})) + local = tmp_path / "a.json" + local.write_text(json.dumps({"attributes": {"x": 2}})) + result = run("--url", URL, "things", "diff", A, "--file", str(local)) + assert result.exit_code == ExitCode.CHECK_FAILED + assert json.loads(result.stdout) == [{"op": "replace", "path": "/attributes/x", "old": 1, "new": 2}] + + +def test_rql_warns_about_exists_on_whole_objects(run): + assert rql.warnings(rql.parse("and(exists(attributes),exists(features/temp))")) == [ + "Ditto rejects exists(attributes) on the whole object (eclipse-ditto/ditto#2637); " + "use a concrete path such as exists(attributes/)" + ] + result = run("rql", "lint", "exists(features)") + assert result.exit_code == 0 + assert "Ditto rejects exists(features)" in result.stderr + + +def test_field_stats(): + things = [ + {"thingId": A, "attributes": {"room": "lab", "floor": 1, "tags": ["a", "b", "c", "d"]}}, + {"thingId": B, "attributes": {"room": "lab", "floor": 1.5}, "features": {}}, + ] + stats, total = field_stats(things) + by_path = {s.path: s.to_json(total) for s in stats} + assert total == 2 + assert by_path["attributes/room"] == { + "path": "attributes/room", + "types": ["string"], + "count": 2, + "share": 1.0, + "examples": ["lab"], + } + assert by_path["attributes/floor"]["types"] == ["integer", "number"] + assert by_path["attributes/tags"]["examples"] == [["a", "b", "c", "…"]] + assert by_path["features"]["types"] == ["object"] + assert json_type([1, "x"]) == "array" + + +def test_fields_command(run, ditto): + route = ditto.get("/api/2/search/things").mock( + return_value=httpx.Response(200, json={"items": [{"thingId": A, "attributes": {"room": "lab"}}]}) + ) + result = run("--url", URL, "things", "fields", "--path", "attributes", "--sample", "10") + assert [json.loads(line)["path"] for line in result.stdout.splitlines()] == ["attributes/room", "thingId"] + params = route.calls.last.request.url.params + assert params["fields"] == "attributes" + assert "size(10)" in params["option"] + + +def test_no_agent_holds_for_errors_before_the_command_runs(run, agent): + assert json.loads(run("thngs").stderr)["message"] == "No such command 'thngs'. Did you mean 'things'?" + assert run("--no-agent", "thngs").stderr.startswith("Usage: dittoctl") + + +def test_agent_json_lists_and_failed_checks(run, ditto, agent, tmp_path): + ditto.get("/api/2/search/things").mock(side_effect=paged_search(3)) + result = run("--url", URL, "things", "search", "--fields", "thingId,attributes", "-o", "json") + assert result.stdout.count("\n") == 1 + assert len(json.loads(result.stdout)) == 3 + ditto.get(f"/api/2/things/{A}").mock(return_value=httpx.Response(200, json={"x": 1})) + local = tmp_path / "a.json" + local.write_text('{"x": 2}') + diff = run("--url", URL, "things", "diff", A, "--file", str(local)) + assert json.loads(diff.stderr.splitlines()[-1]) == { + "exitCode": 6, + "message": f"1 difference(s) between {A} and {local}", + } + + +def test_connections_create_with_id_uses_put(run, ditto): + ditto.get("/api/2/connections/c-1").mock( + side_effect=[ + httpx.Response(404, json={"status": 404, "error": "connectivity:connection.notfound"}), + httpx.Response(200, json={"id": "c-1"}), + ] + ) + put = ditto.put("/api/2/connections/c-1").mock(return_value=httpx.Response(201, json={"id": "c-1"})) + result = run("--url", URL, "connections", "create", "-d", '{"id":"c-1","connectionType":"http-push"}') + assert result.exit_code == 0, result.stderr + assert put.call_count == 1 + exists = run("--url", URL, "connections", "create", "-d", '{"id":"c-1"}') + assert exists.exit_code == ExitCode.ERROR + assert "already exists" in exists.stderr + + +def test_piggyback_error_responses_fail(run, ditto): + ditto.post("/devops/piggyback/gateway").mock( + return_value=httpx.Response( + 200, + json={ + "type": "devops.responses:errorResponse", + "status": 503, + "instance": "gw-1", + "payload": {"status": 503, "error": "ask.error", "message": "Ask timed out"}, + }, + ) + ) + result = run("--url", URL, "devops", "piggyback", "gateway", "-d", '{"targetActorSelection":"/user/x"}') + assert result.exit_code == ExitCode.ERROR + assert "1 error response(s), e.g. from gw-1: 503 Ask timed out" in result.stderr diff --git a/tests/test_bulk.py b/tests/test_bulk.py new file mode 100644 index 0000000..de23480 --- /dev/null +++ b/tests/test_bulk.py @@ -0,0 +1,149 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +import threading + +import pytest + +from dittoctl.core.bulk import Category, FailureLog, Journal, Outcome, RateLimiter, classify, run_bulk +from dittoctl.core.selectors import read_ids +from dittoctl.errors import DittoctlError, DittoError + +SKIPPED = "The previous value was equal to the new value and the 'if-equal' header was set to 'skip'." + + +@pytest.mark.parametrize( + ("error", "category"), + [ + (DittoError(412, "things:precondition.failed", SKIPPED), Category.UNCHANGED), + ( + DittoError(412, "things:condition.failed", "The specified condition does not match"), + Category.CONDITION_NOT_MET, + ), + (DittoError(412, "policies:condition.failed", "no match"), Category.CONDITION_NOT_MET), + (DittoError(412, "things:precondition.failed", "if-match evaluated to false"), Category.CONFLICT), + (DittoError(404, "things:thing.notfound", "not found"), Category.NOT_FOUND), + (DittoError(500, "internal.error", "boom"), Category.FAILED), + (DittoctlError("GET failed: connection refused"), Category.FAILED), + (ValueError("bad"), Category.FAILED), + ], +) +def test_classify(error, category): + outcome = classify("a:1", error) + assert outcome.category == category + assert outcome.failed is (category in (Category.CONFLICT, Category.NOT_FOUND, Category.FAILED)) + + +def test_run_bulk_counts_and_never_stops_on_errors(): + def operation(thing_id): + if thing_id.endswith("3"): + raise DittoError(500, "internal.error", "boom") + if thing_id.endswith("4"): + raise DittoError(412, "things:precondition.failed", SKIPPED) + return Outcome(thing_id, Category.OK, 204) + + ids = [f"a:{i}" for i in range(10)] + seen = [] + summary = run_bulk(ids, operation, concurrency=3, on_outcome=lambda o: seen.append(o.thing_id)) + assert summary.counts == {Category.OK: 8, Category.FAILED: 1, Category.UNCHANGED: 1} + assert summary.failures == 1 + assert sorted(seen) == sorted(ids) + assert "8" in summary.describe() + + +def test_run_bulk_respects_concurrency(): + running = 0 + peak = 0 + lock = threading.Lock() + release = threading.Event() + + def operation(thing_id): + nonlocal running, peak + with lock: + running += 1 + peak = max(peak, running) + release.wait(0.01) + with lock: + running -= 1 + return Outcome(thing_id, Category.OK) + + run_bulk([f"a:{i}" for i in range(40)], operation, concurrency=4) + assert peak <= 4 + + +def test_journal_and_resume(tmp_path): + journal_path = tmp_path / "journal.tsv" + calls = [] + + def operation(thing_id): + calls.append(thing_id) + if thing_id == "a:2": + raise DittoError(500, "internal.error", "boom") + return Outcome(thing_id, Category.OK) + + ids = ["a:1", "a:2", "a:3"] + run_bulk(ids, operation, journal=Journal(journal_path)) + # failed things are not journaled, so a resumed run retries them + assert sorted(line.split("\t")[0] for line in journal_path.read_text().splitlines()) == ["a:1", "a:3"] + + calls.clear() + summary = run_bulk(ids, operation, journal=Journal(journal_path), resume=True) + assert calls == ["a:2"] + assert summary.skipped_by_journal == 2 + + +def test_failure_log_can_be_read_back_as_ids(tmp_path): + log_path = tmp_path / "failed.tsv" + + def operation(thing_id): + raise DittoError(404, "things:thing.notfound", "The Thing\twith ID\ncould not be found") + + run_bulk(["a:1", "a:2"], operation, failure_log=FailureLog(log_path)) + text = log_path.read_text() + assert text.startswith("# thingId\tstatus\terror\tmessage\tdescription\n") + assert "\ta:" not in text.split("\n", 1)[1] # tabs/newlines in messages are flattened + assert sorted(read_ids(text.splitlines())) == ["a:1", "a:2"] + + +def test_interrupt_finishes_in_flight_and_reports(tmp_path): + def operation(thing_id): + return Outcome(thing_id, Category.OK) + + def interrupt_after_first(outcome): + raise KeyboardInterrupt + + summary = run_bulk([f"a:{i}" for i in range(100)], operation, concurrency=2, on_outcome=interrupt_after_first) + assert summary.interrupted + assert summary.processed < 100 + + +def test_rate_limiter_spaces_calls(): + now = [0.0] + sleeps = [] + + def sleep(seconds): + sleeps.append(round(seconds, 6)) + now[0] += seconds + + limiter = RateLimiter(4, clock=lambda: now[0], sleep=sleep) + for _ in range(4): + limiter.acquire() + assert sleeps == [0.25, 0.25, 0.25] + + +def test_rate_must_be_positive(): + with pytest.raises(DittoctlError): + RateLimiter(0) diff --git a/tests/test_cli.py b/tests/test_cli.py new file mode 100644 index 0000000..5a73207 --- /dev/null +++ b/tests/test_cli.py @@ -0,0 +1,190 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +import base64 +import json + +import httpx +import respx + +from dittoctl import __version__ +from dittoctl.config import Config +from dittoctl.errors import ExitCode + +URL = "http://ditto.test" +THING = "/api/2/things/org.example:sensor-1" + + +def add_basic_context(run, name="local"): + result = run("config", "add-context", name, "--url", URL, "--auth", "basic", "--username", "ditto") + assert result.exit_code == 0, result.stderr + result = run("auth", "login", "--password-stdin", stdin="ditto-pw\n") + assert result.exit_code == 0, result.stderr + + +def test_version(run): + result = run("--version") + assert result.exit_code == 0 + assert __version__ in result.stdout + + +def test_usage_error_exits_with_1(run): + result = run("api") + assert result.exit_code == ExitCode.ERROR + assert "Missing argument" in result.stderr + + +def test_without_context_or_url(run): + result = run("whoami") + assert result.exit_code == ExitCode.ERROR + assert "no context selected" in result.stderr + + +def test_context_lifecycle(run): + add_basic_context(run, "local") + result = run("config", "add-context", "prod", "--url", "https://ditto.example.com/", "--protected") + assert result.exit_code == 0, result.stderr + + listed = run("config", "get-contexts").stdout + assert "local" in listed + assert "https://ditto.example.com" in listed + assert run("config", "current-context").stdout.strip() == "local" + + assert run("config", "use-context", "prod").exit_code == 0 + assert run("config", "current-context").stdout.strip() == "prod" + assert 'url = "https://ditto.example.com"' in run("config", "view", "prod").stdout + + duplicate = run("config", "add-context", "prod", "--url", URL) + assert duplicate.exit_code == ExitCode.ERROR + assert "--overwrite" in duplicate.stderr + + assert run("config", "delete-context", "local").exit_code == 0 + config = Config.load() + assert set(config.contexts) == {"prod"} + assert config.contexts["prod"].protected + + +def test_add_context_validates(run): + result = run("config", "add-context", "x", "--url", URL, "--auth", "oidc", "--issuer", "https://idp") + assert result.exit_code == ExitCode.ERROR + assert "client id" in result.stderr + + +@respx.mock +def test_whoami_with_basic_auth(run): + add_basic_context(run) + route = respx.get(f"{URL}/api/2/whoami").mock( + return_value=httpx.Response( + 200, json={"defaultSubject": "nginx:ditto", "subjects": ["nginx:ditto", "nginx:admins"]} + ) + ) + result = run("whoami") + assert result.exit_code == 0, result.stderr + assert result.stdout.splitlines() == ["nginx:ditto (default)", "nginx:admins"] + expected = "Basic " + base64.b64encode(b"ditto:ditto-pw").decode() + assert route.calls.last.request.headers["Authorization"] == expected + + +@respx.mock +def test_auth_status_and_logout(run): + add_basic_context(run) + assert "authenticated: yes" in run("auth", "status").stdout + assert run("auth", "logout").exit_code == 0 + assert "authenticated: no" in run("auth", "status").stdout + result = run("whoami") + assert result.exit_code == ExitCode.AUTH + assert "no password" in result.stderr + + +@respx.mock +def test_api_with_url_token_and_conditions(run, monkeypatch): + monkeypatch.setenv("DITTOCTL_TOKEN", "tkn") + route = respx.patch(f"{URL}{THING}/attributes").mock(return_value=httpx.Response(204)) + result = run( + "--url", URL, + "api", "patch", f"{THING}/attributes", + "-d", '{"room":"lab"}', + "--if-match", "rev:4", + "--if-equal", "skip", + "--condition", "exists(attributes)", + "--patch-condition", "/attributes/room=ne(attributes/room,\"lab\")", + ) # fmt: skip + assert result.exit_code == 0, result.stderr + request = route.calls.last.request + assert request.headers["Authorization"] == "Bearer tkn" + assert request.headers["Content-Type"] == "application/merge-patch+json" + assert request.headers["If-Match"] == '"rev:4"' + assert request.headers["If-Equal"] == "skip" + assert json.loads(request.headers["merge-thing-patch-conditions"]) == { + "/attributes/room": 'ne(attributes/room,"lab")' + } + assert request.url.params["condition"] == "exists(attributes)" + + +@respx.mock +def test_api_reads_body_from_stdin_and_prints_json(run, monkeypatch): + monkeypatch.setenv("DITTOCTL_TOKEN", "tkn") + thing = {"thingId": "org.example:sensor-1", "policyId": "org.example:sensor-1"} + route = respx.put(f"{URL}{THING}").mock(return_value=httpx.Response(201, json=thing)) + result = run("--url", URL, "api", "PUT", THING, "-d", "@-", "--if-none-match", "*", stdin=json.dumps(thing)) + assert result.exit_code == 0, result.stderr + assert json.loads(result.stdout) == thing + assert route.calls.last.request.headers["If-None-Match"] == "*" + assert route.calls.last.request.headers["Content-Type"] == "application/json" + + +@respx.mock +def test_api_query_params_and_ndjson(run): + route = respx.get(f"{URL}/api/2/search/things").mock( + return_value=httpx.Response(200, json=[{"thingId": "a"}, {"thingId": "b"}]) + ) + result = run("--url", URL, "api", "GET", "/api/2/search/things", "-q", "filter=exists(thingId)", "-o", "ndjson") + assert result.exit_code == 0, result.stderr + assert result.stdout.splitlines() == ['{"thingId":"a"}', '{"thingId":"b"}'] + assert route.calls.last.request.url.params["filter"] == "exists(thingId)" + + +@respx.mock +def test_api_not_found_exit_code_and_message(run): + respx.get(f"{URL}{THING}").mock( + return_value=httpx.Response( + 404, + json={"status": 404, "error": "things:thing.notfound", "message": "not found", "description": "Check ID"}, + ) + ) + result = run("--url", URL, "api", "GET", THING) + assert result.exit_code == ExitCode.NOT_FOUND + assert "things:thing.notfound" in result.stderr + assert "Check ID" in result.stderr + + +@respx.mock +def test_verbose_prints_redacted_curl(run, monkeypatch): + monkeypatch.setenv("DITTOCTL_TOKEN", "very-secret") + respx.get(f"{URL}/api/2/whoami").mock(return_value=httpx.Response(200, json={"subjects": []})) + result = run("-v", "--url", URL, "--correlation-id", "trace", "-H", "x-extra: 1", "whoami") + assert result.exit_code == 0, result.stderr + assert "curl -X GET" in result.stderr + assert "very-secret" not in result.stderr + assert "Bearer ***" in result.stderr + assert "correlation-id: trace-1" in result.stderr + assert "x-extra: 1" in result.stderr + + +def test_completion_script(run): + result = run("completion", "zsh") + assert result.exit_code == 0 + assert "_DITTOCTL_COMPLETE" in result.stdout diff --git a/tests/test_cli_things.py b/tests/test_cli_things.py new file mode 100644 index 0000000..a72d2e4 --- /dev/null +++ b/tests/test_cli_things.py @@ -0,0 +1,195 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +import json + +import httpx +import pytest +import respx + +from dittoctl.errors import ExitCode + +URL = "http://ditto.test" +SEARCH = f"{URL}/api/2/search/things" +THINGS = [ + {"thingId": "org.example:a", "attributes": {"room": "lab"}, "_modified": "2026-11-06T10:00:00Z"}, + {"thingId": "org.example:b", "attributes": {"room": "office", "floor": 2}, "_modified": "2026-11-06T11:00:00Z"}, +] + + +@pytest.fixture +def ditto(): + with respx.mock(base_url=URL, assert_all_called=False) as mock: + mock.get("/api/2/search/things").mock(return_value=httpx.Response(200, json={"items": THINGS})) + mock.get("/api/2/search/things/count").mock(return_value=httpx.Response(200, json=2)) + yield mock + + +def test_search_ndjson_with_filter_namespaces_fields(run, ditto): + result = run( + "--url", URL, "things", "search", + "-f", 'eq( attributes/room , "lab" )', "-n", "org.example,other", "--fields", "thingId,attributes", + "-o", "ndjson", + ) # fmt: skip + assert result.exit_code == 0, result.stderr + assert [json.loads(line) for line in result.stdout.splitlines()] == THINGS + params = ditto.calls.last.request.url.params + assert params["filter"] == 'eq(attributes/room,"lab")' # normalized before sending + assert params["namespaces"] == "org.example,other" + assert params["fields"] == "thingId,attributes" + + +def test_search_defaults_to_ndjson_when_piped(run, ditto): + result = run("--url", URL, "things", "search") + assert result.stdout.splitlines()[0].startswith('{"thingId":"org.example:a"') + + +def test_search_uses_context_namespaces(run, ditto): + assert run("config", "add-context", "c", "--url", URL, "--namespace", "org.example").exit_code == 0 + run("things", "search", "-o", "ids") + assert ditto.calls.last.request.url.params["namespaces"] == "org.example" + + +def test_search_csv_and_ids(run, ditto): + csv_result = run("--url", URL, "things", "search", "-o", "csv", "--short-headers", "--excel") + lines = csv_result.stdout.splitlines() + assert lines[0] == "thingId,room,_modified,floor" + assert lines[1] == "org.example:a,lab,2026-11-06 10:00:00," + assert run("--url", URL, "things", "search", "-o", "ids", "--transport", "paging").stdout == ( + "org.example:a\norg.example:b\n" + ) + + +def sse_stream(*ids: str) -> bytes: + return b"".join(f'id:{i}\ndata:{{"thingId":"{i}"}}\n\n'.encode() for i in ids) + + +def test_search_ids_streams_via_sse(run): + with respx.mock(base_url=URL) as mock: + route = mock.get("/api/2/search/things", headers={"Accept": "text/event-stream"}).mock( + return_value=httpx.Response(200, content=sse_stream("org.example:a", "org.example:b")) + ) + result = run("--url", URL, "things", "search", "-n", "org.example", "-o", "ids") + assert result.stdout == "org.example:a\norg.example:b\n" + assert route.calls.last.request.url.params["fields"] == "thingId" + + +def test_context_can_turn_off_search_streaming(run, ditto): + assert run("config", "add-context", "c", "--url", URL, "--no-search-streaming").exit_code == 0 + assert "search-streaming = false" in run("config", "view", "c").stdout + run("things", "search", "-o", "ids") + request = ditto.calls.last.request + assert request.headers.get("Accept") != "text/event-stream" + assert request.url.params["option"] == "size(200)" + + +def test_export_with_explicit_sse_transport(run, tmp_path): + with respx.mock(base_url=URL) as mock: + mock.get("/api/2/search/things", headers={"Accept": "text/event-stream"}).mock( + return_value=httpx.Response(200, content=sse_stream("org.example:a")) + ) + target = tmp_path / "out.ndjson" + result = run("--url", URL, "things", "export", "--transport", "sse", "-o", "ndjson", "--out", str(target)) + assert result.exit_code == 0, result.stderr + assert target.read_text() == '{"thingId":"org.example:a"}\n' + + +def test_search_table(run, ditto): + result = run("--url", URL, "things", "search", "-o", "table", "--columns", "thingId,attributes/room") + lines = result.stdout.splitlines() + assert lines[0].split() == ["thingId", "attributes/room"] + assert lines[2].split() == ["org.example:b", "office"] + + +def test_invalid_filter_is_rejected_before_sending(run, ditto): + result = run("--url", URL, "things", "search", "-f", "eq(attributes/room,lab)") + assert result.exit_code == ExitCode.ERROR + assert "expected a value" in result.stderr + assert "^" in result.stderr + assert not ditto.calls + + +def test_no_validate_sends_filter_as_is(run, ditto): + run("--url", URL, "things", "count", "-f", "eq(a,b)", "--no-validate") + assert ditto.calls.last.request.url.params["filter"] == "eq(a,b)" + + +def test_filter_from_file(run, ditto, tmp_path): + rql_file = tmp_path / "filter.rql" + rql_file.write_text("and(\n exists(attributes/room),\n eq(attributes/floor, 2)\n)\n", encoding="utf-8") + result = run("--url", URL, "things", "count", "-f", f"@{rql_file}") + assert result.stdout.strip() == "2" + assert ditto.calls.last.request.url.params["filter"] == "and(exists(attributes/room),eq(attributes/floor,2))" + + +def test_export_to_file(run, ditto, tmp_path): + target = tmp_path / "out.csv" + result = run("--url", URL, "things", "export", "--fields", "thingId,attributes", "--out", str(target), "--excel") + assert result.exit_code == 0, result.stderr + assert "Exported 2 things" in result.stderr + assert target.read_bytes().startswith(b"\xef\xbb\xbfthingId,attributes/room") + + +def test_get_single_and_path(run): + with respx.mock(base_url=URL) as mock: + route = mock.get("/api/2/things/org.example:a/attributes/room").mock( + return_value=httpx.Response(200, json="lab") + ) + result = run("--url", URL, "things", "get", "org.example:a", "--path", "attributes/room", "--at-revision", "3") + assert result.exit_code == 0, result.stderr + assert json.loads(result.stdout) == "lab" + assert route.calls.last.request.headers["at-historical-revision"] == "3" + + +def test_get_not_modified(run): + with respx.mock(base_url=URL) as mock: + route = mock.get("/api/2/things/org.example:a").mock(return_value=httpx.Response(304)) + result = run("--url", URL, "things", "get", "org.example:a", "--if-none-match", 'W/"rev:3"') + assert result.exit_code == 0 + assert "Not modified" in result.stderr + assert route.calls.last.request.headers["If-None-Match"] == '"rev:3"' + + +def test_get_several_warns_about_missing(run): + with respx.mock(base_url=URL) as mock: + mock.get("/api/2/things").mock(return_value=httpx.Response(200, json=[THINGS[0]])) + result = run("--url", URL, "things", "get", "org.example:a", "org.example:missing", "-o", "ndjson") + assert json.loads(result.stdout) == THINGS[0] + assert "1 of 2 things were not found" in result.stderr + + +def test_get_several_rejects_single_thing_options(run): + result = run("--url", URL, "things", "get", "a:1", "a:2", "--path", "attributes") + assert result.exit_code == ExitCode.ERROR + assert "single thing id" in result.stderr + + +def test_watch(run): + stream = b'data: {"thingId":"org.example:a","attributes":{"room":"lab"}}\n\n' + with respx.mock(base_url=URL) as mock: + mock.get("/api/2/things").mock(return_value=httpx.Response(200, content=stream)) + result = run("--url", URL, "things", "watch", "-n", "org.example") + assert result.exit_code == 0 + assert json.loads(result.stdout) == {"thingId": "org.example:a", "attributes": {"room": "lab"}} + + +def test_rql_lint_and_fmt(run): + assert run("rql", "lint", 'eq(a,"b")').exit_code == 0 + bad = run("rql", "lint", "and(eq(a,1),)") + assert bad.exit_code == ExitCode.CHECK_FAILED + assert "expected an operator" in bad.stderr + assert run("rql", "fmt", "or( eq(a,1), exists(b) )").stdout == "or(\n eq(a,1),\n exists(b)\n)\n" + assert run("rql", "fmt", "--compact", "@-", stdin="or(\n eq(a,1)\n)").stdout == "or(eq(a,1))\n" diff --git a/tests/test_cli_write.py b/tests/test_cli_write.py new file mode 100644 index 0000000..bb84dd9 --- /dev/null +++ b/tests/test_cli_write.py @@ -0,0 +1,296 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +import json + +import click +import httpx +import pytest +import respx + +from dittoctl.errors import ExitCode + +URL = "http://ditto.test" +A = "org.example:a" +B = "org.example:b" + + +@pytest.fixture +def ditto(): + with respx.mock(base_url=URL, assert_all_called=False) as mock: + yield mock + + +def test_patch_with_ids(run, ditto): + route = ditto.patch(f"/api/2/things/{A}/attributes").mock(return_value=httpx.Response(204)) + ditto.patch(f"/api/2/things/{B}/attributes").mock(return_value=httpx.Response(204)) + result = run("--url", URL, "things", "patch", "attributes", A, B, "-d", '{"room":"lab"}') + assert result.exit_code == 0, result.stderr + assert "Patch: 2 of 2 things" in result.stderr + assert route.calls.last.request.headers["If-Equal"] == "skip" + + +def test_patch_if_equal_can_be_overridden(run, ditto): + route = ditto.patch(f"/api/2/things/{A}").mock(return_value=httpx.Response(204)) + run("--url", URL, "things", "patch", "/", A, "-d", '{"attributes":{"x":1}}', "--if-equal", "update") + assert route.calls.last.request.headers["If-Equal"] == "update" + + +def test_patch_dry_run_writes_nothing(run, ditto): + route = ditto.patch(f"/api/2/things/{A}/attributes").mock(return_value=httpx.Response(204)) + result = run("--url", URL, "things", "patch", "attributes", A, "-d", '{"room":"lab"}', "--dry-run") + assert result.exit_code == 0 + assert route.call_count == 0 + assert "Dry run, nothing written" in result.stderr + assert json.loads(result.stdout)["path"] == f"/api/2/things/{A}/attributes" + + +def test_patch_refuses_arrays(run): + result = run("--url", URL, "things", "patch", "attributes", A, "-d", '{"tags":["x"]}') + assert result.exit_code == ExitCode.ERROR + assert "replaces arrays as a whole" in result.stderr + + +def test_max_affected_requires_yes(run, ditto, tmp_path): + ids = tmp_path / "ids.txt" + ids.write_text("\n".join(f"org.example:t{i}" for i in range(101))) + result = run("--url", URL, "things", "set", "attributes/x", "1", "--ids-file", str(ids)) + assert result.exit_code == ExitCode.ABORTED + assert "more than --max-affected 100" in result.stderr + assert not ditto.calls + + +def test_set_parses_json_values(run, ditto): + route = ditto.patch(f"/api/2/things/{A}").mock(return_value=httpx.Response(204)) + for value, expected in (("42", 42), ("lab", "lab"), ('{"a":true}', {"a": True})): + run("--url", URL, "things", "set", "attributes/location/room", value, A) + assert json.loads(route.calls.last.request.content) == {"attributes": {"location": {"room": expected}}} + run("--url", URL, "things", "set", "attributes/serial", "0042", A, "--string") + assert json.loads(route.calls.last.request.content) == {"attributes": {"serial": "0042"}} + + +def test_unset_sends_null(run, ditto): + route = ditto.patch(f"/api/2/things/{A}").mock(return_value=httpx.Response(204)) + run("--url", URL, "things", "unset", "attributes/old", A) + assert json.loads(route.calls.last.request.content) == {"attributes": {"old": None}} + + +PRECONDITION_FAILED = { + "status": 412, + "error": "things:precondition.failed", + "message": "The comparison of precondition header 'if-match' for the requested Thing resource evaluated to " + "false. Header value: '*', actual entity-tag: 'null'.", +} + + +def test_root_merges_never_create_things(run, ditto): + # Ditto creates a missing thing on a merge at its root; If-Match: * turns that into a failed precondition + ditto.patch(f"/api/2/things/{A}").mock(return_value=httpx.Response(204)) + missing = ditto.patch(f"/api/2/things/{B}").mock(return_value=httpx.Response(412, json=PRECONDITION_FAILED)) + for args in (("set", "attributes/x", "1"), ("unset", "attributes/x"), ("patch", "/", "-d", '{"attributes":{}}')): + result = run("--url", URL, "things", *args, A, B) + assert result.exit_code == ExitCode.PARTIAL_FAILURE, args + assert "ok 1, not-found 1" in result.stderr or "not-found 1, ok 1" in result.stderr + assert missing.calls.last.request.headers["If-Match"] == "*" + + +def test_root_merge_keeps_unchanged_and_explicit_preconditions(run, ditto): + route = ditto.patch(f"/api/2/things/{A}").mock( + return_value=httpx.Response( + 412, + json={ + "status": 412, + "error": "things:precondition.failed", + "message": "The previous value was equal to the new value and the 'if-equal' header was set to 'skip'.", + }, + ) + ) + result = run("--url", URL, "things", "set", "attributes/x", "1", A) + assert result.exit_code == 0 + assert "unchanged 1" in result.stderr + run("--url", URL, "things", "set", "attributes/x", "1", A, "--if-match", "rev:3") + assert route.calls.last.request.headers["If-Match"] == '"rev:3"' + + +def test_merges_below_the_root_need_no_precondition(run, ditto): + # Ditto answers 404 for a missing thing there, and If-Match: * would reject paths that don't exist yet + route = ditto.patch(f"/api/2/things/{A}/attributes/location").mock(return_value=httpx.Response(204)) + run("--url", URL, "things", "patch", "attributes/location", A, "-d", '{"room":"lab"}') + assert "If-Match" not in route.calls.last.request.headers + + +def test_failures_show_dittos_description(run, ditto, tmp_path): + ditto.patch(f"/api/2/things/{A}").mock( + return_value=httpx.Response( + 400, + json={ + "status": 400, + "error": "wot:payload.validation.error", + "message": "The provided payload did not conform to the specified WoT model.", + "description": "The Thing's attributes contained JSON fields which were not defined in the model: [x]", + }, + ) + ) + failed = tmp_path / "failed.tsv" + result = run("--url", URL, "things", "set", "attributes/x", "1", A, "--failed-out", str(failed)) + assert "not defined in the model: [x]" in result.stderr + assert failed.read_text().splitlines()[1].endswith("not defined in the model: [x]") + + +def test_array_remove_has_no_as_set(run): + result = run("--url", URL, "things", "array", "remove", "attributes/tags", A, "--items", "[1]", "--as-set") + assert result.exit_code == ExitCode.ERROR + assert "No such option" in result.stderr + + +def test_delete_needs_yes_when_not_interactive(run, ditto): + route = ditto.delete(f"/api/2/things/{A}").mock(return_value=httpx.Response(204)) + refused = run("--url", URL, "things", "delete", A) + assert refused.exit_code == ExitCode.ABORTED + assert route.call_count == 0 + assert run("--url", URL, "things", "delete", A, "--yes").exit_code == 0 + assert route.call_count == 1 + + +def test_protected_context_needs_confirmation(run, ditto): + assert run("config", "add-context", "prod", "--url", URL, "--protected").exit_code == 0 + route = ditto.patch(f"/api/2/things/{A}").mock(return_value=httpx.Response(204)) + refused = run("things", "set", "attributes/x", "1", A) + assert refused.exit_code == ExitCode.ABORTED + assert "--confirm-context prod" in refused.stderr + assert run("things", "set", "attributes/x", "1", A, "--confirm-context", "prod").exit_code == 0 + assert route.call_count == 1 + + +def test_failures_exit_2_and_are_listed(run, ditto, tmp_path): + ditto.patch(f"/api/2/things/{A}").mock(return_value=httpx.Response(204)) + ditto.patch(f"/api/2/things/{B}").mock( + return_value=httpx.Response(404, json={"status": 404, "error": "things:thing.notfound", "message": "gone"}) + ) + failed = tmp_path / "failed.tsv" + result = run("--url", URL, "things", "set", "attributes/x", "1", A, B, "--failed-out", str(failed)) + assert result.exit_code == ExitCode.PARTIAL_FAILURE + assert "1 of 2 things failed" in result.stderr + assert failed.read_text().splitlines()[1].split("\t")[:3] == [B, "404", "things:thing.notfound"] + + +def test_stdin_cannot_be_used_twice(run): + result = run("--url", URL, "things", "patch", "attributes", "--ids-file", "-", "-d", "@-") + assert result.exit_code == ExitCode.ERROR + assert "stdin can't provide both" in result.stderr + + +def test_import_create_reports_existing_without_failing(run, ditto, tmp_path): + source = tmp_path / "things.ndjson" + source.write_text(json.dumps({"thingId": A, "attributes": {}}) + "\n" + json.dumps({"thingId": B}) + "\n") + ditto.put(f"/api/2/things/{A}").mock(return_value=httpx.Response(201, json={})) + existing = ditto.put(f"/api/2/things/{B}").mock( + return_value=httpx.Response(412, json={"status": 412, "error": "things:precondition.failed", "message": "x"}) + ) + result = run("--url", URL, "things", "import", str(source)) + assert result.exit_code == 0, result.stderr + assert "ok 1" in result.stderr + assert "exists 1" in result.stderr + assert existing.calls.last.request.headers["If-None-Match"] == "*" + + +def test_import_rejects_items_without_thing_id(run, tmp_path): + source = tmp_path / "things.json" + source.write_text('[{"thingId": "a:1"}, {"attributes": {}}]') + result = run("--url", URL, "things", "import", str(source)) + assert result.exit_code == ExitCode.ERROR + assert "item 2 is not a thing" in result.stderr + + +def test_verify(run, ditto, tmp_path): + ditto.get("/api/2/things").mock( + return_value=httpx.Response(200, json=[ + {"thingId": A, "attributes": {"x": 1.0}}, + {"thingId": B, "attributes": {"x": 2}}, + {"thingId": "org.example:c"}, + ]) + ) # fmt: skip + failed = tmp_path / "mismatch.tsv" + result = run("--url", URL, "things", "verify", "attributes/x", A, B, "org.example:c", "org.example:d", + "--equals", "1", "--failed-out", str(failed)) # fmt: skip + assert result.exit_code == ExitCode.CHECK_FAILED + lines = [json.loads(line) for line in result.stdout.splitlines()] + assert [(line["thingId"], line["result"]) for line in lines] == [ + (B, "mismatch"), ("org.example:c", "missing"), ("org.example:d", "not-found"), + ] # fmt: skip + assert "match 1, mismatch 1, missing 1, not found 1" in result.stderr + assert len(failed.read_text().splitlines()) == 4 + + +def test_array_add_command(run, ditto): + ditto.get(f"/api/2/things/{A}/attributes/tags").mock( + return_value=httpx.Response(200, json=["a"], headers={"ETag": '"hash:1"'}) + ) + put = ditto.put(f"/api/2/things/{A}/attributes/tags").mock(return_value=httpx.Response(204)) + result = run("--url", URL, "things", "array", "add", "attributes/tags", A, "--items", '["b","a"]', "--as-set") + assert result.exit_code == 0, result.stderr + assert json.loads(put.calls.last.request.content) == ["a", "b"] + assert put.calls.last.request.headers["If-Match"] == '"hash:1"' + + +def test_edit_sends_merge_patch_with_if_match(run, ditto, monkeypatch): + ditto.get(f"/api/2/things/{A}").mock( + return_value=httpx.Response( + 200, json={"thingId": A, "attributes": {"a": 1, "b": 2}}, headers={"ETag": '"rev:4"'} + ) + ) + route = ditto.patch(f"/api/2/things/{A}").mock(return_value=httpx.Response(204)) + monkeypatch.setattr(click, "edit", lambda text, **_kw: text.replace('"b": 2', '"c": 3')) + result = run("--url", URL, "things", "edit", A) + assert result.exit_code == 0, result.stderr + assert json.loads(route.calls.last.request.content) == {"attributes": {"b": None, "c": 3}} + assert route.calls.last.request.headers["If-Match"] == '"rev:4"' + + +def test_edit_without_changes(run, ditto, monkeypatch): + ditto.get(f"/api/2/things/{A}").mock(return_value=httpx.Response(200, json={"thingId": A})) + monkeypatch.setattr(click, "edit", lambda text, **_kw: None) + assert "No changes" in run("--url", URL, "things", "edit", A).stderr + + +def test_diff(run, ditto, tmp_path): + ditto.get(f"/api/2/things/{A}").mock(return_value=httpx.Response(200, json={"thingId": A, "attributes": {"x": 1}})) + local = tmp_path / "a.json" + local.write_text(json.dumps({"thingId": A, "attributes": {"x": 2}})) + result = run("--url", URL, "things", "diff", A, "--file", str(local)) + assert result.exit_code == ExitCode.CHECK_FAILED + assert '- "x": 1' in result.stdout + assert '+ "x": 2' in result.stdout + local.write_text(json.dumps({"attributes": {"x": 1}, "thingId": A})) + assert run("--url", URL, "things", "diff", A, "--file", str(local)).exit_code == 0 + + +def test_messages_send_prints_responses(run, ditto): + for thing_id, reply in ((A, {"status": "fine"}), (B, {"status": "low battery"})): + ditto.post(f"/api/2/things/{thing_id}/inbox/messages/get-status").mock( + return_value=httpx.Response(200, json=reply) + ) + result = run("--url", URL, "messages", "send", "get-status", A, B, "-d", '{"verbose":true}', "--timeout", "5") + assert result.exit_code == 0, result.stderr + replies = {json.loads(line)["thingId"]: json.loads(line)["response"] for line in result.stdout.splitlines()} + assert replies == {A: {"status": "fine"}, B: {"status": "low battery"}} + + +def test_messages_are_not_retried(run, ditto): + route = ditto.post(f"/api/2/things/{A}/inbox/messages/reboot").mock(return_value=httpx.Response(503)) + result = run("--url", URL, "messages", "send", "reboot", A, "--timeout", "0") + assert result.exit_code == ExitCode.PARTIAL_FAILURE + assert route.call_count == 1 diff --git a/tests/test_client.py b/tests/test_client.py new file mode 100644 index 0000000..19ff953 --- /dev/null +++ b/tests/test_client.py @@ -0,0 +1,241 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +import json + +import httpx +import pytest +import respx + +from dittoctl.auth.base import AuthProvider +from dittoctl.config import Context +from dittoctl.core.client import DittoClient +from dittoctl.core.conditions import Conditions, IfEqual +from dittoctl.core.curl import to_curl +from dittoctl.errors import DittoctlError, DittoError, ExitCode + +BASE = "http://ditto.test" +THING = "/api/2/things/org.example:sensor-1" + + +class RefreshingAuth(AuthProvider): + """Hands out token-1 until refresh() is called, then token-2.""" + + def __init__(self) -> None: + super().__init__(Context(name="test", url=BASE), store=None) # type: ignore[arg-type] + self.token = "token-1" + self.refreshes = 0 + + def headers(self) -> dict[str, str]: + return {"Authorization": f"Bearer {self.token}"} + + def refresh(self) -> bool: + self.refreshes += 1 + self.token = "token-2" + return True + + +@pytest.fixture +def sleeps(): + return [] + + +@pytest.fixture +def client(sleeps): + with DittoClient(BASE, correlation_id="run", sleep=sleeps.append) as c: + yield c + + +@respx.mock +def test_get_parses_json_and_sets_correlation_id_and_user_agent(client): + route = respx.get(f"{BASE}/api/2/whoami").mock( + return_value=httpx.Response(200, json={"subjects": ["nginx:ditto"]}, headers={"ETag": '"rev:1"'}) + ) + first = client.get("/api/2/whoami") + client.get("/api/2/whoami") + assert first.body == {"subjects": ["nginx:ditto"]} + assert first.etag == '"rev:1"' + requests = [call.request for call in route.calls] + assert [r.headers["correlation-id"] for r in requests] == ["run-1", "run-2"] + assert requests[0].headers["user-agent"].startswith("dittoctl/") + + +@respx.mock +def test_explicit_correlation_id_header_wins(client): + route = respx.get(f"{BASE}{THING}").mock(return_value=httpx.Response(200, json={})) + client.get(THING, headers={"correlation-id": "mine"}) + assert route.calls.last.request.headers["correlation-id"] == "mine" + + +@respx.mock +def test_conditions_become_headers_and_url_encoded_params(client): + route = respx.patch(f"{BASE}{THING}/attributes").mock(return_value=httpx.Response(204)) + conditions = Conditions(if_match="rev:7", if_equal=IfEqual.SKIP, condition='eq(attributes/room,"Küche")') + response = client.patch(f"{THING}/attributes", json={"room": "lab"}, conditions=conditions) + request = route.calls.last.request + assert response.status == 204 + assert request.headers["If-Match"] == '"rev:7"' + assert request.headers["If-Equal"] == "skip" + assert request.headers["Content-Type"] == "application/merge-patch+json" + assert request.url.params["condition"] == 'eq(attributes/room,"Küche")' + assert json.loads(request.content) == {"room": "lab"} + + +@respx.mock +def test_put_json_uses_application_json(client): + route = respx.put(f"{BASE}{THING}").mock(return_value=httpx.Response(201, json={"thingId": "org.example:sensor-1"})) + client.put(THING, json={}) + assert route.calls.last.request.headers["Content-Type"] == "application/json" + + +@respx.mock +def test_ditto_error_body_is_mapped(client): + respx.get(f"{BASE}{THING}").mock( + return_value=httpx.Response( + 404, + json={ + "status": 404, + "error": "things:thing.notfound", + "message": "The Thing with ID 'org.example:sensor-1' could not be found.", + "description": "Check if the ID of your requested Thing was correct.", + }, + headers={"correlation-id": "run-1"}, + ) + ) + with pytest.raises(DittoError) as info: + client.get(THING) + error = info.value + assert error.status == 404 + assert error.error == "things:thing.notfound" + assert error.description.startswith("Check if") + assert error.correlation_id == "run-1" + assert error.exit_code == ExitCode.NOT_FOUND + assert str(error).startswith("404 things:thing.notfound: The Thing") + + +@respx.mock +def test_html_error_page_is_reduced_to_reason_phrase(client): + page = "\n401 Authorization Required\nnginx\n" + respx.get(f"{BASE}{THING}").mock(return_value=httpx.Response(401, text=page, headers={"Content-Type": "text/html"})) + with pytest.raises(DittoError) as info: + client.get(THING) + assert str(info.value) == "401: Unauthorized" + assert info.value.body == page + + +@respx.mock +def test_plain_text_error_body_is_kept(client): + respx.get(f"{BASE}{THING}").mock(return_value=httpx.Response(502, text="upstream unavailable")) + with pytest.raises(DittoError, match="502: upstream unavailable"): + client.get(THING, retry=False) + + +@respx.mock +def test_raise_for_status_false_returns_error_response(client): + respx.get(f"{BASE}{THING}").mock(return_value=httpx.Response(412, json={"status": 412})) + assert client.get(THING, raise_for_status=False).status == 412 + + +@respx.mock +def test_retries_idempotent_requests_honouring_retry_after(client, sleeps): + route = respx.get(f"{BASE}{THING}").mock( + side_effect=[ + httpx.Response(503, headers={"Retry-After": "2"}), + httpx.Response(429), + httpx.Response(200, json={"ok": True}), + ] + ) + assert client.get(THING).body == {"ok": True} + assert route.call_count == 3 + assert sleeps == [2.0, 1.0] # Retry-After, then backoff 0.5 * 2**1 + + +@respx.mock +def test_gives_up_after_max_retries(client, sleeps): + route = respx.get(f"{BASE}{THING}").mock(return_value=httpx.Response(503)) + with pytest.raises(DittoError): + client.get(THING) + assert route.call_count == 4 + assert len(sleeps) == 3 + + +@respx.mock +def test_post_is_not_retried_by_default(client): + route = respx.post(f"{BASE}{THING}/inbox/messages/reboot").mock(return_value=httpx.Response(503)) + with pytest.raises(DittoError): + client.post(f"{THING}/inbox/messages/reboot", json={}) + assert route.call_count == 1 + + +@respx.mock +def test_transport_errors_are_retried_then_reported(client): + route = respx.get(f"{BASE}{THING}").mock(side_effect=httpx.ConnectError("refused")) + with pytest.raises(DittoctlError, match="refused"): + client.get(THING) + assert route.call_count == 4 + + +@respx.mock +def test_401_triggers_one_refresh_and_retry(sleeps): + auth = RefreshingAuth() + route = respx.get(f"{BASE}{THING}").mock(side_effect=[httpx.Response(401), httpx.Response(200, json={})]) + with DittoClient(BASE, auth, sleep=sleeps.append) as client: + client.get(THING) + assert auth.refreshes == 1 + assert [c.request.headers["Authorization"] for c in route.calls] == ["Bearer token-1", "Bearer token-2"] + + +@respx.mock +def test_persistent_401_is_not_refreshed_twice(): + auth = RefreshingAuth() + respx.get(f"{BASE}{THING}").mock(return_value=httpx.Response(401)) + with DittoClient(BASE, auth) as client, pytest.raises(DittoError) as info: + client.get(THING) + assert auth.refreshes == 1 + assert info.value.exit_code == ExitCode.AUTH + + +def test_relative_path_is_rejected(client): + with pytest.raises(DittoctlError, match="must start with"): + client.get("api/2/things") + + +def test_curl_rendering_redacts_credentials(): + request = httpx.Request( + "PATCH", + f"{BASE}{THING}", + headers={"Authorization": "Bearer secret-token", "If-Match": '"rev:1"', "x-ditto-pre-authenticated": "a:b"}, + content=b'{"a":1}', + ) + curl = to_curl(request) + assert "secret-token" not in curl + assert "'Authorization: Bearer ***'" in curl + assert "'x-ditto-pre-authenticated: ***'" in curl + assert "'If-Match: \"rev:1\"'" in curl + assert "--data-raw '{\"a\":1}'" in curl + + +def test_errors_not_from_ditto_name_the_request(): + response = httpx.Response( + 404, + text="404 Not Found", + headers={"content-type": "text/html"}, + request=httpx.Request("GET", "http://ditto.test/status"), + ) + error = DittoError.from_response(response) + assert error.message == "Not Found" + assert error.description.startswith("GET /status was answered without a Ditto error") + assert "may not be exposed" in error.description diff --git a/tests/test_conditions.py b/tests/test_conditions.py new file mode 100644 index 0000000..52ca909 --- /dev/null +++ b/tests/test_conditions.py @@ -0,0 +1,67 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +import json + +import pytest + +from dittoctl.core.conditions import Conditions, IfEqual, LiveTimeoutStrategy, normalize_etag + + +@pytest.mark.parametrize( + ("value", "expected"), + [("rev:5", '"rev:5"'), ('"rev:5"', '"rev:5"'), ("*", "*"), ('W/"rev:5"', '"rev:5"'), (" rev:1 ", '"rev:1"')], +) +def test_normalize_etag(value, expected): + assert normalize_etag(value) == expected + + +def test_empty_conditions_produce_nothing(): + conditions = Conditions() + assert conditions.headers() == {} + assert conditions.params() == {} + assert conditions.is_empty() + + +def test_all_conditions_map_to_headers_and_params(): + conditions = Conditions( + if_match="rev:3", + if_none_match="*", + if_equal=IfEqual.SKIP, + condition='eq(attributes/fw,"1.2")', + patch_conditions={"/features/temp": "exists(features/temp)"}, + live_condition="eq(attributes/online,true)", + live_timeout_strategy=LiveTimeoutStrategy.USE_TWIN, + ) + headers = conditions.headers() + assert headers["If-Match"] == '"rev:3"' + assert headers["If-None-Match"] == "*" + assert headers["If-Equal"] == "skip" + assert json.loads(headers["merge-thing-patch-conditions"]) == {"/features/temp": "exists(features/temp)"} + assert headers["live-channel-timeout-strategy"] == "use-twin" + assert conditions.params() == { + "condition": 'eq(attributes/fw,"1.2")', + "live-channel-condition": "eq(attributes/online,true)", + } + assert not conditions.is_empty() + + +def test_replace_returns_modified_copy(): + original = Conditions(if_equal=IfEqual.SKIP) + changed = original.replace(if_match="rev:1") + assert original.if_match is None + assert changed.if_match == "rev:1" + assert changed.if_equal is IfEqual.SKIP diff --git a/tests/test_config.py b/tests/test_config.py new file mode 100644 index 0000000..1f888d4 --- /dev/null +++ b/tests/test_config.py @@ -0,0 +1,130 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +import stat +import sys +from pathlib import Path + +import pytest + +from dittoctl.auth.store import FileStore +from dittoctl.config import AuthConfig, Config, Context, default_config_path +from dittoctl.errors import ConfigError + + +def assert_private(path: Path) -> None: + """Only the owner may read the file. Windows has no POSIX permission bits, so the mode is checked elsewhere.""" + if sys.platform != "win32": + assert stat.S_IMODE(path.stat().st_mode) == 0o600 + + +def test_missing_config_file_gives_empty_config(): + config = Config.load() + assert config.contexts == {} + assert config.current_context is None + assert config.path == default_config_path() + + +def test_roundtrip_preserves_contexts(tmp_path): + path = tmp_path / "config.toml" + config = Config(path=path) + config.set_context( + Context( + name="prod", + url="https://ditto.example.com", + auth=AuthConfig( + method="oidc", + issuer="https://idp.example.com/realms/iot", + client_id="dittoctl", + flow="device", + scopes=["openid", "offline_access"], + extra_params={"audience": "ditto"}, + use_token="id", + ), + namespaces=["org.example"], + headers={"x-tenant": "a"}, + protected=True, + timeout=10.0, + verify="/etc/ca.pem", + ) + ) + config.set_context(Context(name="local", url="http://localhost:8080", auth=AuthConfig("basic", username="ditto"))) + config.current_context = "local" + config.save() + + assert_private(path) + loaded = Config.load(path) + assert loaded.current_context == "local" + assert loaded.contexts == config.contexts + + +def test_get_context_errors_are_helpful(tmp_path): + config = Config(path=tmp_path / "c.toml") + with pytest.raises(ConfigError, match="no context selected"): + config.get_context() + config.set_context(Context(name="a", url="http://a")) + with pytest.raises(ConfigError, match=r"unknown context 'b' \(known contexts: a\)"): + config.get_context("b") + + +@pytest.mark.parametrize( + ("context", "message"), + [ + (Context(name="x", url="ftp://x"), "url must start"), + (Context(name="x", url="http://x", auth=AuthConfig("kerberos")), "unknown auth method"), + (Context(name="x", url="http://x", auth=AuthConfig("basic")), "requires a username"), + (Context(name="x", url="http://x", auth=AuthConfig("preauth")), "requires a subject"), + (Context(name="x", url="http://x", auth=AuthConfig("oidc", issuer="https://i")), "requires an issuer"), + ( + Context( + name="x", url="http://x", auth=AuthConfig("oidc", issuer="https://i", client_id="c", flow="implicit") + ), + "unknown OIDC flow", + ), + ], +) +def test_validation(context, message): + with pytest.raises(ConfigError, match=message): + context.validate() + + +def test_delete_current_context_unselects_it(tmp_path): + config = Config(path=tmp_path / "c.toml") + config.set_context(Context(name="a", url="http://a")) + config.current_context = "a" + config.delete_context("a") + assert config.current_context is None + assert config.contexts == {} + + +def test_broken_toml_is_reported(tmp_path): + path = tmp_path / "c.toml" + path.write_text("contexts = [", encoding="utf-8") + with pytest.raises(ConfigError, match="cannot read config file"): + Config.load(path) + + +def test_file_store(tmp_path): + store = FileStore(tmp_path / "s" / "secrets.json") + assert store.get("a/password") is None + store.set("a/password", "pw") + store.set("b/token", "t") + assert store.get("a/password") == "pw" + assert_private(store.path) + store.delete("a/password") + store.delete("does-not-exist") + assert store.get("a/password") is None + assert store.get("b/token") == "t" diff --git a/tests/test_formats.py b/tests/test_formats.py new file mode 100644 index 0000000..f24b8c2 --- /dev/null +++ b/tests/test_formats.py @@ -0,0 +1,205 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +import csv +import io +import json +import re +import tracemalloc + +import pytest + +from dittoctl.formats import Columns, write_csv, write_ids, write_items, write_json_array, write_ndjson +from dittoctl.formats.flatten import cell, flatten, get_path, short_headers +from dittoctl.formats.tabular import excel_timestamp + +THING = { + "thingId": "org.example:a", + "attributes": {"location": {"room": "lab", "floor": 2}, "tags": ["x", "y"], "empty": {}}, + "features": {"temp": {"properties": {"value": 21.5}}}, +} + + +def test_flatten(): + assert flatten(THING) == { + "thingId": "org.example:a", + "attributes/location/room": "lab", + "attributes/location/floor": 2, + "attributes/tags": ["x", "y"], + "attributes/empty": {}, + "features/temp/properties/value": 21.5, + } + assert flatten(5) == {"value": 5} + + +def test_get_path(): + assert get_path(THING, "attributes/location") == {"room": "lab", "floor": 2} + assert get_path(THING, "/features/temp/properties/value") == 21.5 + assert get_path(THING, "attributes/missing/x") is None + + +@pytest.mark.parametrize( + ("value", "expected"), + [(None, ""), (True, "true"), (False, "false"), ("s", "s"), (2, "2"), (1.5, "1.5"), (["a", 1], '["a",1]'), + ({"ü": 1}, '{"ü":1}')], +) # fmt: skip +def test_cell(value, expected): + assert cell(value) == expected + + +def test_short_headers(): + paths = ["thingId", "features/temp/properties/value", "features/humidity/properties/value", "attributes/room"] + assert short_headers(paths) == { + "thingId": "thingId", + "features/temp/properties/value": "temp/properties/value", + "features/humidity/properties/value": "humidity/properties/value", + "attributes/room": "room", + } + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("2026-11-06T15:19:54.123456789Z", "2026-11-06 15:19:54"), + ("2026-11-06T17:19:54+02:00", "2026-11-06 15:19:54"), + ("2026-11-06", "2026-11-06"), + ("not a date", "not a date"), + ], +) +def test_excel_timestamp(value, expected): + assert excel_timestamp(value) == expected + + +def read_csv(text: str) -> list[list[str]]: + return list(csv.reader(io.StringIO(text))) + + +def test_csv_discovers_columns_from_first_rows_and_warns_about_later_ones(): + warnings = [] + items = [ + {"thingId": "a", "attributes": {"x": 1}}, + {"thingId": "b", "attributes": {"y": 2}}, + {"thingId": "c", "z": 3}, + ] + out = io.StringIO() + count = write_csv(items, out, columns=Columns(discover_rows=2), warn=warnings.append) + assert count == 3 + assert read_csv(out.getvalue()) == [ + ["thingId", "attributes/x", "attributes/y"], + ["a", "1", ""], + ["b", "", "2"], + ["c", "", ""], + ] + assert len(warnings) == 1 + assert "z" in warnings[0] + + +def test_csv_discover_all_rows(): + items = [{"a": 1}, {"b": 2}] + out = io.StringIO() + write_csv(items, out, columns=Columns(discover_rows=0)) + assert read_csv(out.getvalue())[0] == ["a", "b"] + + +def test_csv_explicit_columns_can_name_parent_objects(): + out = io.StringIO() + write_csv([THING], out, columns=Columns(explicit=["thingId", "attributes/location", "attributes/nope"])) + assert read_csv(out.getvalue()) == [ + ["thingId", "attributes/location", "attributes/nope"], + ["org.example:a", '{"room":"lab","floor":2}', ""], + ] + + +def test_csv_options(): + out = io.StringIO() + items = [{"thingId": "a", "_modified": "2026-11-06T15:19:54Z", "note": "multi\nline"}] + write_csv(items, out, columns=Columns(short=True), delimiter=";", header=False, excel=True) + assert out.getvalue() == 'a;2026-11-06 15:19:54;"multi\nline"\n' + + +def test_csv_memory_stays_flat_for_large_streams(): + def things(n): + for i in range(n): + yield {"thingId": f"org.example:t{i}", "attributes": {"i": i, "name": f"thing {i}"}} + + class Sink(io.TextIOBase): + def write(self, s): + return len(s) + + tracemalloc.start() + write_csv(things(1_000), Sink()) + _, small = tracemalloc.get_traced_memory() + tracemalloc.reset_peak() + write_csv(things(100_000), Sink()) + _, large = tracemalloc.get_traced_memory() + tracemalloc.stop() + # only the discovery window is buffered: 100x the rows must not need noticeably more memory + assert large < small * 2 + 100_000 + + +def test_json_array_streaming(): + out = io.StringIO() + assert write_json_array(iter([{"a": 1}, {"b": [1, 2]}]), out) == 2 + assert json.loads(out.getvalue()) == [{"a": 1}, {"b": [1, 2]}] + empty = io.StringIO() + write_json_array(iter([]), empty) + assert json.loads(empty.getvalue()) == [] + + +def test_ndjson_and_ids(): + out = io.StringIO() + write_ndjson([{"thingId": "a", "ü": 1}, {"thingId": "b"}], out) + assert out.getvalue() == '{"thingId":"a","ü":1}\n{"thingId":"b"}\n' + ids = io.StringIO() + assert write_ids([{"thingId": "a"}, {"other": 1}, {"thingId": "b"}], ids) == 2 + assert ids.getvalue() == "a\nb\n" + + +def test_table_to_non_terminal_does_not_wrap(): + out = io.StringIO() + long_id = "org.example:" + "x" * 150 + write_items([{"thingId": long_id, "attributes": {"n": 1}}], "table", out) + lines = out.getvalue().splitlines() + assert lines[0].split() == ["thingId", "attributes/n"] + assert long_id in lines[1] + + +def test_table_shows_values_literally(): + out = io.StringIO() + write_items([{"thingId": "ns:a:", "note": "[red]alert[/red] :smile:"}], "table", out) + row = out.getvalue().splitlines()[1] + assert "ns:a:" in row + assert "[red]alert[/red] :smile:" in row + + +class Terminal(io.StringIO): + def isatty(self) -> bool: + return True + + +@pytest.mark.parametrize("write", [write_ndjson, write_json_array]) +def test_json_is_highlighted_on_a_terminal_only(write, monkeypatch): + monkeypatch.delenv("NO_COLOR", raising=False) + monkeypatch.setenv("FORCE_COLOR", "1") + items = [{"thingId": "ns:a:", "note": "[bold]x[/bold]", "on": True}] + plain = io.StringIO() + write(items, plain) + terminal = Terminal() + write(items, terminal) + assert "\x1b[" not in plain.getvalue() + assert "\x1b[" in terminal.getvalue() + # only colors are added: no markup, no emoji, the same JSON text + assert re.sub(r"\x1b\[[0-9;]*m", "", terminal.getvalue()) == plain.getvalue() diff --git a/tests/test_headers.py b/tests/test_headers.py new file mode 100644 index 0000000..31aef0d --- /dev/null +++ b/tests/test_headers.py @@ -0,0 +1,60 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +"""Every source file carries the EPL-2.0 header; files largely generated by an AI also carry the AI disclosure. + +Markdown files carry no header: NOTICE.md declares the licences and the use of generative AI for them. +""" + +from __future__ import annotations + +import re +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parent.parent + + +def source_files() -> list[Path]: + files = [ROOT / "pyproject.toml", *(ROOT / ".github" / "workflows").glob("*.yml")] + for directory in ("src", "tests", "scripts"): + files += (ROOT / directory).rglob("*.py") + return sorted(f for f in files if "__pycache__" not in f.parts) + + +def header_of(path: Path) -> str: + lines = [] + for line in path.read_text(encoding="utf-8").splitlines(): + if not line.startswith("#"): + break + lines.append(line.removeprefix("#").strip()) + return "\n".join(lines) + + +@pytest.mark.parametrize("path", source_files(), ids=lambda p: str(p.relative_to(ROOT))) +def test_license_header(path: Path): + header = header_of(path) + assert re.match(r"Copyright \(c\) \d{4} Contributors to the Eclipse Foundation\n", header), "no copyright line" + assert "terms of the Eclipse Public License 2.0" in header + spdx = re.search(r"^SPDX-License-Identifier: (.+)$", header, re.M) + assert spdx, "no SPDX-License-Identifier" + disclosed = "AI Disclosure:" in header + if disclosed: + assert spdx.group(1) == "EPL-2.0 AND CC0-1.0", "AI-generated portions are CC0-1.0" + assert re.search(r"^Assisted-by: \S.+$", header, re.M), "the AI assistant isn't named" + else: + assert spdx.group(1) == "EPL-2.0", "CC0-1.0 only applies to AI-generated portions" diff --git a/tests/test_jsonops.py b/tests/test_jsonops.py new file mode 100644 index 0000000..4435935 --- /dev/null +++ b/tests/test_jsonops.py @@ -0,0 +1,82 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +import pytest + +from dittoctl.core.jsonops import ( + NO_CHANGE, + array_add, + array_remove, + contains_array, + deep_equal, + json_equal, + merge_patch_diff, + nested, +) + + +def test_nested(): + assert nested("/attributes/location/room/", "lab") == {"attributes": {"location": {"room": "lab"}}} + assert nested("", {"a": 1}) == {"a": 1} + + +def test_contains_array(): + assert contains_array([1]) + assert contains_array({"a": {"b": [1]}}) + assert not contains_array({"a": {"b": 1}}) + + +@pytest.mark.parametrize( + ("a", "b", "expected"), + [ + (1, 1.0, True), + (True, 1, False), + (False, 0, False), + ({"a": 1, "b": [1, {"c": 2}]}, {"b": [1, {"c": 2}], "a": 1}, True), + ([1, 2], [2, 1], False), + ("1", 1, False), + (None, None, True), + ({"a": None}, {}, False), + ], +) +def test_deep_equal(a, b, expected): + assert deep_equal(a, b) is expected + + +def test_json_equal_distinguishes_int_and_float(): + assert json_equal({"a": 1, "b": 2}, {"b": 2, "a": 1}) + assert not json_equal(1, 1.0) + + +def test_array_add(): + assert array_add(["a"], ["a", "b"], as_set=False, equal=deep_equal) == ["a", "a", "b"] + assert array_add(["a"], ["a", "b", "b"], as_set=True, equal=deep_equal) == ["a", "b"] + assert array_add(None, [{"x": 1}], as_set=True, equal=deep_equal) == [{"x": 1}] + + +def test_array_remove(): + assert array_remove(["a", "b", "a", 1.0], ["a", 1], equal=deep_equal) == ["b"] + assert array_remove(["a", 1.0], [1], equal=json_equal) == ["a", 1.0] + assert array_remove(None, ["a"], equal=deep_equal) == [] + + +def test_merge_patch_diff(): + old = {"a": 1, "b": {"c": 2, "d": 3}, "e": [1], "gone": True} + new = {"a": 1, "b": {"c": 2, "d": 4}, "e": [1, 2], "added": {"x": 1}} + assert merge_patch_diff(old, new) == {"b": {"d": 4}, "e": [1, 2], "added": {"x": 1}, "gone": None} + assert merge_patch_diff(old, dict(old)) is NO_CHANGE + assert merge_patch_diff(1, 1.0) is NO_CHANGE + assert merge_patch_diff({"a": 1}, "text") == "text" diff --git a/tests/test_m4.py b/tests/test_m4.py new file mode 100644 index 0000000..9615f68 --- /dev/null +++ b/tests/test_m4.py @@ -0,0 +1,231 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +"""DevOps, history, WoT and claim.""" + +import json + +import httpx +import pytest +import respx + +from dittoctl.core.devops import ( + duration_seconds, + health_lines, + purge_results, + purge_succeeded, + reindex_command, + shutdown_namespace_command, +) +from dittoctl.errors import DittoctlError, ExitCode + +URL = "http://ditto.test" + + +@pytest.fixture +def ditto(): + with respx.mock(base_url=URL, assert_all_called=False) as mock: + yield mock + + +@pytest.mark.parametrize(("value", "seconds"), [("10s", 10), ("500ms", 0.5), ("2m", 120), ("1h", 3600), ("7", 7)]) +def test_duration_seconds(value, seconds): + assert duration_seconds(value) == seconds + + +def test_duration_seconds_rejects_garbage(): + with pytest.raises(DittoctlError): + duration_seconds("soon") + + +def test_command_builders(): + assert reindex_command(["a", "b"])["headers"]["namespaces"] == ["a", "b"] + assert "namespaces" not in reindex_command()["headers"] + # Ditto rejects the documented shutdown command without a headers field + assert "headers" in shutdown_namespace_command("ns") + + +PURGE_RESPONSE = { + "?": { + "?": {"type": "namespaces.responses:purgeNamespace", "status": 200, "resourceType": "thing"}, + "?1": {"type": "namespaces.responses:purgeNamespace", "status": 200, "resourceType": "policy"}, + "?2": {"type": "namespaces.responses:purgeNamespace", "status": 500, "resourceType": "thing-search"}, + } +} + + +def test_purge_results(): + results = purge_results(PURGE_RESPONSE) + assert [r["resourceType"] for r in results] == ["thing", "policy", "thing-search"] + assert [purge_succeeded(r) for r in results] == [True, True, False] + assert purge_succeeded({"status": 200, "successful": False}) is False + + +def test_health_lines(): + tree = {"label": "roles", "status": "UP", "children": [{"label": "things", "status": "DOWN", "children": []}]} + assert health_lines(tree) == [(0, "roles", "UP"), (1, "things", "DOWN")] + + +def test_logging_get_and_set(run, ditto): + ditto.get("/devops/logging/things").mock( + return_value=httpx.Response(200, json={"10.0.0.1": {"loggerConfigs": [{"logger": "ROOT", "level": "info"}]}}) + ) + result = run("--url", URL, "devops", "logging", "get", "things") + assert result.stdout.splitlines()[1].split() == ["things", "10.0.0.1", "ROOT", "info"] + route = ditto.put("/devops/logging").mock(return_value=httpx.Response(200, json={})) + run("--url", URL, "devops", "logging", "set", "org.eclipse.ditto", "DEBUG") + assert json.loads(route.calls.last.request.content) == {"logger": "org.eclipse.ditto", "level": "debug"} + + +def test_config_with_path(run, ditto): + route = ditto.get("/devops/config/gateway/pod-1").mock(return_value=httpx.Response(200, json={})) + run("--url", URL, "devops", "config", "gateway", "--instance", "pod-1", "--path", "ditto.gateway") + assert route.calls.last.request.url.params["path"] == "ditto.gateway" + + +def test_piggyback_waits_longer_than_ditto(run, ditto): + route = ditto.post("/devops/piggyback/things").mock(return_value=httpx.Response(200, json={"ok": True})) + result = run("--url", URL, "devops", "piggyback", "things", "-d", '{"targetActorSelection":"/x"}', + "--timeout", "45s") # fmt: skip + assert result.exit_code == 0 + request = route.calls.last.request + assert request.url.params["timeout"] == "45s" + assert request.extensions["timeout"]["read"] == 60.0 + + +def test_reindex(run, ditto): + route = ditto.post("/devops/piggyback/search").mock(return_value=httpx.Response(200)) + run("--url", URL, "devops", "reindex", "-n", "ns1") + assert json.loads(route.calls.last.request.content)["headers"]["namespaces"] == ["ns1"] + run("--url", URL, "devops", "reindex", "--thing", "ns1:a") + body = json.loads(route.calls.last.request.content) + assert body["piggybackCommand"] == {"type": "thing-search.sudo.commands:sudoUpdateThing", "thingId": "ns1:a"} + + +def piggyback_router(purge: httpx.Response): + def handler(request: httpx.Request) -> httpx.Response: + command_type = json.loads(request.content)["piggybackCommand"]["type"] + if command_type == "common.commands:shutdown": + return httpx.Response(408, json={"status": 408, "error": "command.timeout"}) + if command_type == "namespaces.commands:purgeNamespace": + return purge + return httpx.Response(200, json={"status": 200}) + + return handler + + +def test_namespace_erase(run, ditto): + route = ditto.post("/devops/piggyback").mock(side_effect=piggyback_router(httpx.Response(200, json=PURGE_RESPONSE))) + result = run("--url", URL, "devops", "namespace", "erase", "ns1", "--confirm-namespace", "ns1") + commands = [json.loads(c.request.content)["piggybackCommand"]["type"] for c in route.calls] + assert commands == [ + "namespaces.commands:blockNamespace", + "common.commands:shutdown", + "namespaces.commands:purgeNamespace", + "namespaces.commands:unblockNamespace", + ] + # thing-search reported 500 in PURGE_RESPONSE + assert result.exit_code == ExitCode.ERROR + assert "thing-search: FAILED" in result.stderr + + +def test_namespace_erase_unconfirmed_purge_still_unblocks(run, ditto): + timeout = httpx.Response(408, json={"status": 408, "error": "command.timeout", "message": "timeout"}) + route = ditto.post("/devops/piggyback").mock(side_effect=piggyback_router(timeout)) + result = run("--url", URL, "devops", "namespace", "erase", "ns1", "--confirm-namespace", "ns1") + assert result.exit_code == ExitCode.ERROR + assert "didn't confirm the erasure" in result.stderr + assert json.loads(route.calls.last.request.content)["piggybackCommand"]["type"] == ( + "namespaces.commands:unblockNamespace" + ) + + +def test_namespace_erase_needs_confirmation(run, ditto): + route = ditto.post("/devops/piggyback").mock(return_value=httpx.Response(200)) + result = run("--url", URL, "devops", "namespace", "erase", "ns1") + assert result.exit_code == ExitCode.ABORTED + assert route.call_count == 0 + + +def test_status(run, ditto): + ditto.get("/status").mock( + return_value=httpx.Response(200, json={"service-version": "3.9.8", "roles": {"things": {}, "gateway": {}}}) + ) + ditto.get("/status/health").mock( + return_value=httpx.Response(200, json={"label": "roles", "status": "UP", + "children": [{"label": "things", "status": "DOWN"}]}) + ) # fmt: skip + lines = run("--url", URL, "devops", "status", "--health").stdout.splitlines() + assert lines[0].split() == ["service-version:", "3.9.8"] + assert lines[1].endswith("gateway, things") + assert " things: DOWN <--" in lines + + +def test_history(run, ditto): + stream = b'data: {"_revision":1}\n\ndata: {"_revision":2}\n\n' + route = ditto.get("/api/2/things/ns:a").mock(return_value=httpx.Response(200, content=stream)) + result = run("--url", URL, "things", "history", "ns:a", "--from-revision", "-5", "--to-revision", "0", + "--fields", "_revision") # fmt: skip + assert [json.loads(line)["_revision"] for line in result.stdout.splitlines()] == [1, 2] + request = route.calls.last.request + assert request.headers["Accept"] == "text/event-stream" + assert dict(request.url.params) == { + "from-historical-revision": "-5", "to-historical-revision": "0", "fields": "_revision", + } # fmt: skip + assert run("--url", URL, "things", "history", "ns:a").exit_code == ExitCode.ERROR + + +def test_td_and_wot_directory(run, ditto): + td = ditto.get("/api/2/things/ns:a/features/lamp").mock(return_value=httpx.Response(200, json={"title": "Lamp"})) + assert json.loads(run("--url", URL, "things", "td", "ns:a", "--feature", "lamp").stdout) == {"title": "Lamp"} + assert td.calls.last.request.headers["Accept"] == "application/td+json" + ditto.get("/.well-known/wot").mock(return_value=httpx.Response(200, json={"@type": "ThingDirectory"})) + assert json.loads(run("--url", URL, "wot", "directory").stdout) == {"@type": "ThingDirectory"} + + +def test_migrate_definition(run, ditto): + route = ditto.post("/api/2/things/ns:a/migrateDefinition").mock( + return_value=httpx.Response(200, json={"mergeStatus": "DRY_RUN"}) + ) + result = run("--url", URL, "things", "migrate-definition", "ns:a", "--definition", "https://m/lamp-2.tm.jsonld", + "--payload", '{"attributes":{"x":1}}', "--patch-condition", "features/lamp=not(exists(features/lamp))", + "--init-defaults", "--dry-run") # fmt: skip + assert result.exit_code == 0, result.stderr + request = route.calls.last.request + assert request.url.params["dry-run"] == "true" + assert json.loads(request.content) == { + "thingDefinitionUrl": "https://m/lamp-2.tm.jsonld", + "migrationPayload": {"attributes": {"x": 1}}, + "patchConditions": {"thing:/features/lamp": "not(exists(features/lamp))"}, + "initializeMissingPropertiesFromDefaults": True, + } + assert json.loads(result.stdout) == {"mergeStatus": "DRY_RUN"} + + +def test_claim(run, ditto): + route = ditto.post("/api/2/things/ns:a/inbox/claim").mock(return_value=httpx.Response(200, json={"ok": True})) + assert json.loads(run("--url", URL, "messages", "claim", "ns:a", "--timeout", "3").stdout) == {"ok": True} + assert route.calls.last.request.url.params["timeout"] == "3" + + +def test_bulk_failure_reasons_are_shown(run, ditto): + ditto.patch("/api/2/things/ns:a").mock( + return_value=httpx.Response(400, json={"status": 400, "error": "wot:payload.validation.error", + "message": "The provided payload did not conform"}) + ) # fmt: skip + result = run("--url", URL, "things", "set", "attributes/x", "1", "ns:a") + assert result.exit_code == ExitCode.PARTIAL_FAILURE + assert "ns:a: 400 wot:payload.validation.error: The provided payload did not conform" in result.stderr diff --git a/tests/test_oidc.py b/tests/test_oidc.py new file mode 100644 index 0000000..49a757f --- /dev/null +++ b/tests/test_oidc.py @@ -0,0 +1,283 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +import base64 +import json +import threading +import time +import urllib.request +from urllib.parse import parse_qs, urlencode, urlparse + +import httpx +import pytest +import respx + +from dittoctl.auth.oidc import OidcAuth, TokenSet, code_challenge, generate_code_verifier +from dittoctl.auth.store import FileStore +from dittoctl.config import AuthConfig, Context +from dittoctl.errors import AuthError + +ISSUER = "https://idp.test/realms/iot" +TOKEN_URL = f"{ISSUER}/protocol/openid-connect/token" +DEVICE_URL = f"{ISSUER}/protocol/openid-connect/auth/device" +AUTH_URL = f"{ISSUER}/protocol/openid-connect/auth" + + +def make_jwt(claims: dict) -> str: + def b64(data: dict) -> str: + return base64.urlsafe_b64encode(json.dumps(data).encode()).rstrip(b"=").decode() + + return f"{b64({'alg': 'none'})}.{b64(claims)}.sig" + + +@pytest.fixture +def store(tmp_path): + return FileStore(tmp_path / "secrets.json") + + +@pytest.fixture +def discovery(): + with respx.mock(assert_all_called=False) as mock: + mock.get(f"{ISSUER}/.well-known/openid-configuration").mock( + return_value=httpx.Response( + 200, + json={ + "issuer": ISSUER, + "authorization_endpoint": AUTH_URL, + "token_endpoint": TOKEN_URL, + "device_authorization_endpoint": DEVICE_URL, + }, + ) + ) + yield mock + + +def make_auth(store, flow="pkce", messages=None, **kwargs) -> OidcAuth: + context = Context( + name="prod", + url="https://ditto.test", + auth=AuthConfig( + method="oidc", + issuer=ISSUER, + client_id="dittoctl", + flow=flow, + scopes=["openid", "offline_access"], + extra_params={"audience": "ditto"}, + ), + ) + notify = messages.append if messages is not None else (lambda _m: None) + return OidcAuth(context, store, notify=notify, sleep=lambda _s: None, **kwargs) + + +def form(request: httpx.Request) -> dict[str, str]: + return {k: v[0] for k, v in parse_qs(request.content.decode()).items()} + + +def test_code_challenge_matches_rfc7636_appendix_b(): + verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk" + assert code_challenge(verifier) == "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM" + + +def test_code_verifier_is_within_rfc_length(): + assert 43 <= len(generate_code_verifier()) <= 128 + + +def test_client_credentials_login_and_headers(store, discovery): + route = discovery.post(TOKEN_URL).mock( + return_value=httpx.Response(200, json={"access_token": "at-1", "expires_in": 300}) + ) + auth = make_auth(store, flow="client-credentials") + auth.login(secret="s3cret") + assert auth.headers() == {"Authorization": "Bearer at-1"} + sent = form(route.calls.last.request) + assert sent == { + "grant_type": "client_credentials", + "scope": "openid offline_access", + "audience": "ditto", + "client_id": "dittoctl", + "client_secret": "s3cret", + } + assert store.get("prod/client-secret") == "s3cret" + + +def test_client_credentials_requires_secret(store, discovery): + with pytest.raises(AuthError, match="client secret"): + make_auth(store, flow="client-credentials").login() + + +def test_client_credentials_fetches_new_token_when_expired(store, discovery): + discovery.post(TOKEN_URL).mock(return_value=httpx.Response(200, json={"access_token": "at-2", "expires_in": 300})) + auth = make_auth(store, flow="client-credentials") + store.set("prod/client-secret", "s3cret") + store.set( + "prod/oidc-tokens", + TokenSet(access_token="old", issuer=ISSUER, client_id="dittoctl", expires_at=time.time() - 10).to_json(), + ) + assert auth.bearer_token() == "at-2" + + +def test_expired_token_is_refreshed(store, discovery): + route = discovery.post(TOKEN_URL).mock( + return_value=httpx.Response(200, json={"access_token": "at-new", "expires_in": 300}) + ) + store.set( + "prod/oidc-tokens", + TokenSet( + access_token="at-old", + issuer=ISSUER, + client_id="dittoctl", + refresh_token="rt-1", + id_token="id-1", + expires_at=time.time() - 1, + ).to_json(), + ) + auth = make_auth(store) + assert auth.bearer_token() == "at-new" + assert form(route.calls.last.request)["refresh_token"] == "rt-1" + saved = TokenSet.from_json(store.get("prod/oidc-tokens")) + # the provider didn't rotate the refresh token or return a new id token: the old ones are kept + assert saved.refresh_token == "rt-1" + assert saved.id_token == "id-1" + + +def test_valid_token_is_used_without_network(store): + store.set( + "prod/oidc-tokens", + TokenSet(access_token="at", issuer=ISSUER, client_id="dittoctl", expires_at=time.time() + 600).to_json(), + ) + with respx.mock(assert_all_mocked=True): + assert make_auth(store).bearer_token() == "at" + + +def test_tokens_of_another_client_are_ignored(store): + store.set("prod/oidc-tokens", TokenSet(access_token="at", issuer=ISSUER, client_id="other").to_json()) + with pytest.raises(AuthError, match="not logged in"): + make_auth(store).bearer_token() + + +def test_token_expiry_falls_back_to_jwt_exp(store, discovery): + access_token = make_jwt({"sub": "alice", "exp": 2_000_000_000}) + discovery.post(TOKEN_URL).mock(return_value=httpx.Response(200, json={"access_token": access_token})) + store.set("prod/client-secret", "s") + auth = make_auth(store, flow="client-credentials") + auth.login() + status = auth.status() + assert status["expires_at"] == 2_000_000_000 + assert status["claims"]["sub"] == "alice" + + +def test_device_flow_polls_until_authorized(store, discovery): + messages = [] + discovery.post(DEVICE_URL).mock( + return_value=httpx.Response( + 200, + json={ + "device_code": "dc", + "user_code": "ABCD-EFGH", + "verification_uri": "https://idp.test/device", + "verification_uri_complete": "https://idp.test/device?user_code=ABCD-EFGH", + "interval": 0, + "expires_in": 60, + }, + ) + ) + token_route = discovery.post(TOKEN_URL).mock( + side_effect=[ + httpx.Response(400, json={"error": "authorization_pending"}), + httpx.Response(400, json={"error": "slow_down"}), + httpx.Response(200, json={"access_token": "at", "refresh_token": "rt", "expires_in": 300}), + ] + ) + auth = make_auth(store, flow="device", messages=messages) + auth.login() + assert auth.bearer_token() == "at" + assert token_route.call_count == 3 + assert form(token_route.calls.last.request)["grant_type"] == "urn:ietf:params:oauth:grant-type:device_code" + assert "ABCD-EFGH" in messages[0] + + +def test_device_flow_denied(store, discovery): + discovery.post(DEVICE_URL).mock( + return_value=httpx.Response(200, json={"device_code": "dc", "user_code": "X", "interval": 0}) + ) + discovery.post(TOKEN_URL).mock(return_value=httpx.Response(400, json={"error": "access_denied"})) + with pytest.raises(AuthError, match="access_denied"): + make_auth(store, flow="device").login() + + +def _browser(params_override=None): + """A fake browser: follows the authorization URL straight to the redirect URI, like an IdP would.""" + + def open_browser(url: str) -> None: + query = {k: v[0] for k, v in parse_qs(urlparse(url).query).items()} + open_browser.query = query + response = {"code": "the-code", "state": query["state"], **(params_override or {})} + target = f"{query['redirect_uri']}?{urlencode(response)}" + + def call() -> None: + # urllib, not httpx: respx must not intercept the call to the local callback server + with urllib.request.urlopen(target.replace("localhost", "127.0.0.1"), timeout=5) as r: # noqa: S310 + r.read() + + threading.Thread(target=call, daemon=True).start() + + open_browser.query = {} + return open_browser + + +def test_pkce_login_end_to_end(store, discovery): + token_route = discovery.post(TOKEN_URL).mock( + return_value=httpx.Response(200, json={"access_token": "at", "id_token": "it", "expires_in": 300}) + ) + discovery.route(host="127.0.0.1").pass_through() + browser = _browser() + auth = make_auth(store, open_browser=browser) + auth.login() + + query = browser.query + assert query["response_type"] == "code" + assert query["client_id"] == "dittoctl" + assert query["code_challenge_method"] == "S256" + assert query["audience"] == "ditto" + assert query["redirect_uri"].startswith("http://localhost:") + sent = form(token_route.calls.last.request) + assert sent["grant_type"] == "authorization_code" + assert sent["code"] == "the-code" + assert sent["redirect_uri"] == query["redirect_uri"] + assert code_challenge(sent["code_verifier"]) == query["code_challenge"] + assert auth.bearer_token() == "at" + + +def test_pkce_login_rejects_state_mismatch(store, discovery): + discovery.route(host="127.0.0.1").pass_through() + auth = make_auth(store, open_browser=_browser({"state": "forged"})) + with pytest.raises(AuthError, match="state"): + auth.login() + + +def test_pkce_login_reports_idp_error(store, discovery): + discovery.route(host="127.0.0.1").pass_through() + auth = make_auth(store, open_browser=_browser({"error": "access_denied", "error_description": "user said no"})) + with pytest.raises(AuthError, match="user said no"): + auth.login() + + +def test_logout_forgets_tokens_and_secret(store): + store.set("prod/oidc-tokens", "{}") + store.set("prod/client-secret", "s") + make_auth(store).logout() + assert store.get("prod/oidc-tokens") is None + assert store.get("prod/client-secret") is None diff --git a/tests/test_policies_connections.py b/tests/test_policies_connections.py new file mode 100644 index 0000000..6b9bfd2 --- /dev/null +++ b/tests/test_policies_connections.py @@ -0,0 +1,308 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +import json +import re + +import httpx +import pytest +import respx + +from dittoctl.core.bulk import Category +from dittoctl.core.client import DittoClient +from dittoctl.core.connections import connection_path, redact_secrets, redact_uri, send_command +from dittoctl.core.policies import migrate_subjects, policy_path, subject_migration_operation +from dittoctl.core.writes import message_operation +from dittoctl.errors import DittoctlError, ExitCode + +BASE = "http://ditto.test" +U1 = "11111111-1111-4111-8111-111111111111" +POLICY = { + "policyId": "ns:p", + "entries": { + "owner": {"subjects": {"nginx:ditto": {"type": "basic"}}, "resources": {}}, + "users": { + "subjects": { + f"oldidp:{U1}": {"type": "user", "expiry": "2030-01-01T00:00:00Z"}, + "oldidp:role-admins": {"type": "group"}, + }, + "resources": {"thing:/": {"grant": ["READ"], "revoke": []}}, + }, + }, +} +PATTERN = re.compile(r"oldidp:(?P[0-9a-f-]{36})") +TEMPLATE = r"newidp:fed-sub:\g" + + +@pytest.fixture +def client(): + with DittoClient(BASE, sleep=lambda _s: None) as c: + yield c + + +def test_policy_path_encodes_segments(): + assert policy_path("ns:p") == "/api/2/policies/ns:p" + assert policy_path("ns:p", "entries", "my label", "subjects", "a:b/c") == ( + "/api/2/policies/ns:p/entries/my%20label/subjects/a:b%2Fc" + ) + + +def test_migrate_subjects_adds_twins_with_same_value(): + migrated, changes = migrate_subjects(POLICY, PATTERN, TEMPLATE) + subjects = migrated["entries"]["users"]["subjects"] + assert subjects[f"newidp:fed-sub:{U1}"] == {"type": "user", "expiry": "2030-01-01T00:00:00Z"} + assert f"oldidp:{U1}" in subjects + assert "newidp:fed-sub:role-admins" not in subjects # doesn't match the pattern + assert [c.describe() for c in changes] == [f"users: add oldidp:{U1} -> newidp:fed-sub:{U1}"] + assert POLICY["entries"]["users"]["subjects"].keys() == {f"oldidp:{U1}", "oldidp:role-admins"} # not mutated + + +def test_migrate_subjects_is_idempotent_and_can_replace(): + migrated, _ = migrate_subjects(POLICY, PATTERN, TEMPLATE) + assert migrate_subjects(migrated, PATTERN, TEMPLATE)[1] == [] + replaced, changes = migrate_subjects(POLICY, PATTERN, TEMPLATE, remove_old=True) + assert f"oldidp:{U1}" not in replaced["entries"]["users"]["subjects"] + assert changes[0].removed_old + assert migrate_subjects(POLICY, PATTERN, TEMPLATE, labels={"owner"})[1] == [] + + +@respx.mock +def test_subject_migration_operation_writes_with_if_match_and_retries(client): + respx.get(f"{BASE}/api/2/policies/ns:p").mock( + return_value=httpx.Response(200, json=POLICY, headers={"ETag": '"rev:3"'}) + ) + put = respx.put(f"{BASE}/api/2/policies/ns:p").mock( + side_effect=[ + httpx.Response(412, json={"status": 412, "error": "policies:precondition.failed", "message": "x"}), + httpx.Response(204), + ] + ) + operation = subject_migration_operation(client, PATTERN, TEMPLATE, allow_lockout=True) + outcome = operation("ns:p") + assert outcome.category == Category.OK + assert put.call_count == 2 + request = put.calls.last.request + assert request.headers["If-Match"] == '"rev:3"' + assert request.url.params["allow-policy-lockout"] == "true" + assert f"newidp:fed-sub:{U1}" in json.loads(request.content)["entries"]["users"]["subjects"] + + +@respx.mock +def test_subject_migration_dry_run_and_unchanged(client): + respx.get(f"{BASE}/api/2/policies/ns:p").mock(return_value=httpx.Response(200, json=POLICY)) + planned = subject_migration_operation(client, PATTERN, TEMPLATE, dry_run=True)("ns:p") + assert planned.category == Category.PLANNED + assert planned.detail["changes"] == [f"users: add oldidp:{U1} -> newidp:fed-sub:{U1}"] + nothing = subject_migration_operation(client, re.compile("nomatch:.*"), "x")("ns:p") + assert nothing.category == Category.UNCHANGED + + +@pytest.mark.parametrize( + ("uri", "expected"), + [ + ("amqps://user:s3cret@broker:5671/vhost", "amqps://user:***@broker:5671/vhost"), + ("tcp://broker:1883", "tcp://broker:1883"), + ("http://user@host", "http://user@host"), + ], +) +def test_redact_uri(uri, expected): + assert redact_uri(uri) == expected + + +def test_redact_secrets_in_log_messages(): + message = ( + "Message headers: [if-none-match=*, authorization=Basic ZGl0dG86ZGl0dG8=, x-real-ip=1.2.3.4] " + '{"headers":{"Authorization":"Bearer eyJhbGciOi.payload.sig"}} uri=mqtt://u:pw@broker:1883' + ) + redacted = redact_secrets(message) + assert "ZGl0dG86ZGl0dG8" not in redacted + assert "eyJhbGciOi" not in redacted + assert ":pw@" not in redacted + assert "authorization=Basic ***" in redacted + assert '"Authorization":"Bearer ***"' in redacted + assert "mqtt://u:***@broker:1883" in redacted + + +@respx.mock +def test_send_command(client): + route = respx.post(f"{BASE}/api/2/connections/my%2Fconn/command").mock(return_value=httpx.Response(200)) + assert connection_path("my/conn") == "/api/2/connections/my%2Fconn" + send_command(client, "my/conn", "open") + assert route.calls.last.request.content == b"connectivity.commands:openConnection" + assert route.calls.last.request.headers["Content-Type"] == "text/plain" + + +@respx.mock +def test_message_pagination(client): + route = respx.post(f"{BASE}/api/2/things/ns:a/inbox/messages/history").mock( + side_effect=[ + httpx.Response(200, json={"values": [1, 2], "next": "t1"}), + httpx.Response(200, json={"values": [3], "next": "t2"}), + httpx.Response(200, json={"values": [4]}), + ] + ) + operation = message_operation(client, "history", {"from": "2026-11-01"}, timeout=5, paginate=("next", "token")) + outcome = operation("ns:a") + assert outcome.category == Category.OK + assert [page["values"] for page in outcome.detail] == [[1, 2], [3], [4]] + bodies = [json.loads(c.request.content) for c in route.calls] + assert bodies == [ + {"from": "2026-11-01"}, + {"from": "2026-11-01", "token": "t1"}, + {"from": "2026-11-01", "token": "t2"}, + ] + + +@respx.mock +def test_message_pagination_stops_at_max_pages(client): + respx.post(f"{BASE}/api/2/things/ns:a/inbox/messages/history").mock( + return_value=httpx.Response(200, json={"next": "again"}) + ) + outcome = message_operation(client, "history", None, timeout=5, paginate=("next", "next"), max_pages=3)("ns:a") + assert outcome.category == Category.FAILED + assert len(outcome.detail) == 3 + + +def test_message_pagination_needs_object_payload(client): + with pytest.raises(DittoctlError, match="JSON object"): + message_operation(client, "x", [1, 2], paginate=("next", "next")) + + +# --- CLI --------------------------------------------------------------------------------------- + +URL = "http://ditto.test" + + +@pytest.fixture +def ditto(): + with respx.mock(base_url=URL, assert_all_called=False) as mock: + yield mock + + +def test_cli_subjects_add_and_remove(run, ditto): + put = ditto.put("/api/2/policies/ns:p/entries/users/subjects/nginx:bob").mock(return_value=httpx.Response(201)) + delete = ditto.delete("/api/2/policies/ns:p/entries/users/subjects/nginx:bob").mock( + return_value=httpx.Response(204) + ) + run("--url", URL, "policies", "subjects", "add", "ns:p", "users", "nginx:bob", "--expiring-at", "2031-01-01T00:00Z") + assert json.loads(put.calls.last.request.content) == {"type": "added by dittoctl", "expiry": "2031-01-01T00:00Z"} + run("--url", URL, "policies", "subjects", "remove", "ns:p", "users", "nginx:bob", "--allow-lockout") + assert delete.calls.last.request.url.params["allow-policy-lockout"] == "true" + + +def test_cli_policies_list_and_migrate_by_filter(run, ditto): + ditto.get("/api/2/search/things").mock( + return_value=httpx.Response(200, json={"items": [{"policyId": "ns:p"}, {"policyId": "ns:p"}, {"thingId": "x"}]}) + ) + assert run("--url", URL, "policies", "list", "-f", "exists(attributes/x)").stdout == "ns:p\n" + ditto.get("/api/2/policies/ns:p").mock(return_value=httpx.Response(200, json=POLICY, headers={"ETag": '"rev:1"'})) + put = ditto.put("/api/2/policies/ns:p").mock(return_value=httpx.Response(204)) + result = run("--url", URL, "policies", "subjects", "migrate", "-f", "exists(attributes/x)", + "--match", PATTERN.pattern, "--template", TEMPLATE) # fmt: skip + assert result.exit_code == 0, result.stderr + assert "Migrate subjects: 1 of 1 policies" in result.stderr + assert put.call_count == 1 + + +def test_cli_migrate_rejects_bad_regex(run): + result = run("--url", URL, "policies", "subjects", "migrate", "ns:p", "--match", "(", "--template", "x") + assert result.exit_code == ExitCode.ERROR + assert "--match" in result.stderr + + +def test_cli_check_permissions(run, ditto): + route = ditto.post("/api/2/checkPermissions").mock( + return_value=httpx.Response(200, json={"thing:/attributes": True, "policy:/": False}) + ) + result = run("--url", URL, "policies", "check", "ns:t", "--resource", "thing:/attributes", "--resource", "policy:/", + "--permission", "WRITE") # fmt: skip + assert result.exit_code == ExitCode.CHECK_FAILED + assert result.stdout.splitlines() == ["allowed thing:/attributes (WRITE)", "denied policy:/ (WRITE)"] + assert json.loads(route.calls.last.request.content)["policy:/"] == { + "resource": "policy:/", "entityId": "ns:t", "hasPermissions": ["WRITE"], + } # fmt: skip + + +def test_cli_policy_get_resolved(run, ditto): + route = ditto.get("/api/2/policies/ns:p/entries/users").mock(return_value=httpx.Response(200, json={})) + run("--url", URL, "policies", "get", "ns:p", "--path", "entries/users", "--resolved") + assert route.calls.last.request.url.params["policy-view"] == "resolved" + + +def test_cli_token_integration(run, ditto): + route = ditto.post("/api/2/policies/ns:p/entries/users/actions/activateTokenIntegration").mock( + return_value=httpx.Response(204) + ) + assert run("--url", URL, "policies", "activate-token-integration", "ns:p", "--label", "users").exit_code == 0 + assert route.call_count == 1 + + +def test_cli_connections_list_redacts_passwords(run, ditto): + ditto.get("/api/2/connections").mock( + return_value=httpx.Response(200, json=[{"id": "c1", "name": "n", "connectionType": "amqp-091", + "connectionStatus": "open", "uri": "amqp://u:secret@b:5672"}]) + ) # fmt: skip + result = run("--url", URL, "connections", "list") + assert "amqp://u:***@b:5672" in result.stdout + assert "secret" not in result.stdout + assert run("--url", URL, "connections", "list", "-o", "ids").stdout == "c1\n" + + +def test_cli_connection_test_and_commands(run, ditto): + test = ditto.post("/api/2/connections").mock(return_value=httpx.Response(200)) + result = run("--url", URL, "connections", "test", "-d", '{"connectionType":"mqtt"}') + assert "Connection test succeeded" in result.stderr + assert test.calls.last.request.url.params["dry-run"] == "true" + command = ditto.post("/api/2/connections/c1/command").mock(return_value=httpx.Response(200)) + for name, expected in (("open", "openConnection"), ("close", "closeConnection"), + ("reset-metrics", "resetConnectionMetrics")): # fmt: skip + assert run("--url", URL, "connections", name, "c1").exit_code == 0 + assert command.calls.last.request.content.decode() == f"connectivity.commands:{expected}" + + +def test_cli_connection_logs_redacted(run, ditto): + entry = {"timestamp": "2026-11-06T10:00:00Z", "level": "success", "category": "target", "type": "dispatched", + "message": "headers: [authorization=Basic c2VjcmV0]"} # fmt: skip + ditto.get("/api/2/connections/c1/logs").mock( + return_value=httpx.Response(200, json={"connectionId": "c1", "enabledSince": "2026-11-06T09:00:00Z", + "connectionLogs": [entry]}) + ) # fmt: skip + result = run("--url", URL, "connections", "logs", "c1", "-o", "ndjson") + assert json.loads(result.stdout)["message"] == "headers: [authorization=Basic ***]" + assert "not enabled" not in result.stderr + raw = run("--url", URL, "connections", "logs", "c1", "-o", "ndjson", "--no-redact") + assert "c2VjcmV0" in raw.stdout + + +def test_cli_things_get_live(run, ditto): + route = ditto.get("/api/2/things/ns:a").mock(return_value=httpx.Response(200, json={})) + run("--url", URL, "things", "get", "ns:a", "--live", "--live-timeout", "3", "--live-timeout-strategy", "use-twin") + request = route.calls.last.request + assert request.url.params["channel"] == "live" + assert request.url.params["timeout"] == "3s" + assert request.headers["live-channel-timeout-strategy"] == "use-twin" + + +def test_cli_messages_paginate(run, ditto): + ditto.post("/api/2/things/ns:a/inbox/messages/history").mock( + side_effect=[httpx.Response(200, json={"v": 1, "next": "t"}), httpx.Response(200, json={"v": 2})] + ) + result = run("--url", URL, "messages", "send", "history", "ns:a", "-d", "{}", "--paginate", "next:token") + assert result.exit_code == 0, result.stderr + pages = [json.loads(line) for line in result.stdout.splitlines()] + assert [(p["page"], p["response"]["v"]) for p in pages] == [(1, 1), (2, 2)] + refused = run("--url", URL, "messages", "send", "history", "ns:a", "--paginate", "next", "--timeout", "0") + assert refused.exit_code == ExitCode.ERROR diff --git a/tests/test_reference.py b/tests/test_reference.py new file mode 100644 index 0000000..a0a8462 --- /dev/null +++ b/tests/test_reference.py @@ -0,0 +1,64 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +import importlib.util +from pathlib import Path + +SCRIPT = Path(__file__).resolve().parent.parent / "scripts" / "gen_reference.py" + + +def test_reference_is_up_to_date(): + spec = importlib.util.spec_from_file_location("gen_reference", SCRIPT) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + assert module.TARGET.read_text(encoding="utf-8") == module.render(), "run: python scripts/gen_reference.py" + + +def test_short_help_is_not_truncated_mid_sentence(): + import click + + from dittoctl.cli.main import cli + + def walk(command: click.Command, path: str): + if isinstance(command, click.Group): + for name, sub in command.commands.items(): + yield f"{path} {name}", sub.get_short_help_str(limit=500) + yield from walk(sub, f"{path} {name}") + + # click ends the short help at the first ". ", so "e.g." in a first sentence cuts it off + truncated = [f"{name}: {short}" for name, short in walk(cli, "dittoctl") if short.endswith(("e.g.", "i.e."))] + assert truncated == [] + + +def test_every_option_has_help(): + import click + + from dittoctl.cli.main import cli + + def walk(command: click.Command, path: str): + yield path, command + if isinstance(command, click.Group): + for name, sub in command.commands.items(): + yield from walk(sub, f"{path} {name}") + + # people and LLMs alike rely on the help texts; an option without one is a guess + missing = [ + f"{path} {param.opts[0]}" + for path, command in walk(cli, "dittoctl") + for param in command.params + if isinstance(param, click.Option) and not param.help and "--help" not in param.opts + ] + assert missing == [] diff --git a/tests/test_rql.py b/tests/test_rql.py new file mode 100644 index 0000000..213e152 --- /dev/null +++ b/tests/test_rql.py @@ -0,0 +1,115 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +import pytest + +from dittoctl.core import rql + + +@pytest.mark.parametrize( + "expression", + [ + 'eq(attributes/location,"kitchen")', + "ne(attributes/count,-1.5e3)", + "gt(_modified,'2026-11-01T00:00:00Z')", + 'like(attributes/name,"sensor-*")', + 'ilike(attributes/name,"SENSOR-?")', + 'in(attributes/type,"a","b",3,true,null)', + "exists(features/temp/properties/value)", + "empty(attributes/tags)", + "not(exists(attributes/x))", + 'and(eq(a,1),or(eq(b,false),not(eq(c,"x"))))', + 'eq(features/*/properties/status,"on")', + 'eq(attributes/quote,"say \\"hi\\"")', + ], +) +def test_valid_expressions_roundtrip(expression): + assert rql.normalize(expression) == expression + + +def test_whitespace_is_accepted_and_removed(): + text = """ + and( + eq(attributes/a, "x y"), + in(attributes/n, 1, 2) + ) + """ + assert rql.normalize(text) == 'and(eq(attributes/a,"x y"),in(attributes/n,1,2))' + + +def test_parsed_values(): + node = rql.parse('in(p,"s\\"q",1.5,-2,true,false,null)') + assert isinstance(node, rql.Comparison) + assert [v.value for v in node.values] == ['s"q', 1.5, -2, True, False, None] + + +def test_pretty_format(): + node = rql.parse("and(eq(a,1),or(exists(b),not(eq(c,2))))") + assert rql.pretty(node) == "\n".join( + [ + "and(", + " eq(a,1),", + " or(", + " exists(b),", + " not(", + " eq(c,2)", + " )", + " )", + ")", + ] + ) + + +@pytest.mark.parametrize( + ("expression", "message", "position"), + [ + ("", "empty", 0), + ("eq(attributes/x,unquoted)", "expected a value", 16), + ("eq(attributes/x,1abc)", "expected a value", 16), + ("foo(a,1)", "unknown operator 'foo'", 0), + ("EQ(a,1)", "operators are lowercase: 'eq'", 0), + ("eq(a,1", "expected ')'", 6), + ("eq(a,1,2)", "it takes one value", 6), + ("exists(a,1)", "it takes only a property", 8), + ("eq(a,1))", "unexpected input after the end", 7), + ('eq(a,"open)', "unterminated string", 5), + ("and(eq(a,1) eq(b,2))", "expected ')'", 12), + ("eq(,1)", "expected a property path", 3), + ("not(eq(a,1),eq(b,2))", "to close 'not('", 11), + ], +) +def test_errors_report_position(expression, message, position): + with pytest.raises(rql.RqlError) as info: + rql.parse(expression) + assert message in info.value.message + assert info.value.position == position + + +def test_render_points_at_the_error(): + with pytest.raises(rql.RqlError) as info: + rql.parse("and(eq(attributes/a,x),exists(b))") + lines = info.value.render().splitlines() + assert lines[1] == " and(eq(attributes/a,x),exists(b))" + assert lines[2] == " " + " " * 20 + "^" + + +def test_render_shortens_long_expressions(): + expression = "and(" + ",".join(f"eq(attributes/a{i},{i})" for i in range(30)) + ",eq(x,bad))" + with pytest.raises(rql.RqlError) as info: + rql.parse(expression) + snippet, caret = info.value.render(width=40).splitlines()[1:] + assert snippet.startswith(" …") + assert snippet[caret.index("^") :].startswith("bad") diff --git a/tests/test_search_things.py b/tests/test_search_things.py new file mode 100644 index 0000000..1833cb4 --- /dev/null +++ b/tests/test_search_things.py @@ -0,0 +1,334 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +import json +import re +from urllib.parse import parse_qs + +import httpx +import pytest +import respx + +from dittoctl.core.client import DittoClient +from dittoctl.core.search import ( + POST_THRESHOLD, + Transport, + count_things, + find_things, + search_things, + sort_option, + stream_things, +) +from dittoctl.core.sse import SseEvent, iter_sse +from dittoctl.core.things import get_thing, get_things, thing_path, watch_things +from dittoctl.errors import DittoctlError, DittoError + +BASE = "http://ditto.test" + + +def paged_search(total: int): + """A fake search endpoint serving ``total`` things in pages of the requested size, with cursors.""" + + def handler(request: httpx.Request) -> httpx.Response: + params = dict(request.url.params) + if request.method == "POST": + params = {k: v[0] for k, v in parse_qs(request.content.decode()).items()} + option = params["option"] + size = int(re.search(r"size\((\d+)\)", option).group(1)) + cursor = re.search(r"cursor\((\d+)\)", option) + start = int(cursor.group(1)) if cursor else 0 + items = [{"thingId": f"org.example:t{i}"} for i in range(start, min(start + size, total))] + body = {"items": items} + if start + size < total: + body["cursor"] = str(start + size) + return httpx.Response(200, json=body) + + return handler + + +@pytest.fixture +def client(): + with DittoClient(BASE) as c: + yield c + + +@pytest.mark.parametrize( + ("sort", "expected"), + [ + (None, None), + ("-_modified", "sort(-_modified)"), + ("attributes/name,-_modified", "sort(+attributes/name,-_modified)"), + (["+a", "b"], "sort(+a,+b)"), + (" , ", None), + ], +) +def test_sort_option(sort, expected): + assert sort_option(sort) == expected + + +@respx.mock +def test_search_follows_cursor_through_all_pages(client): + route = respx.get(f"{BASE}/api/2/search/things").mock(side_effect=paged_search(450)) + items = list(search_things(client, rql_filter='eq(a,"b")', namespaces=["ns1", "ns2"], fields="thingId")) + assert len(items) == 450 + assert items[-1] == {"thingId": "org.example:t449"} + assert route.call_count == 3 + first, last = route.calls[0].request.url.params, route.calls[-1].request.url.params + assert first["filter"] == 'eq(a,"b")' + assert first["namespaces"] == "ns1,ns2" + assert first["fields"] == "thingId" + assert first["option"] == "size(200)" + assert last["option"] == "size(200),cursor(400)" + + +@respx.mock +def test_search_limit_stops_early_and_shrinks_page_size(client): + route = respx.get(f"{BASE}/api/2/search/things").mock(side_effect=paged_search(1000)) + items = list(search_things(client, limit=50, sort="-_modified")) + assert len(items) == 50 + assert route.call_count == 1 + assert route.calls.last.request.url.params["option"] == "size(50),sort(-_modified)" + + +@respx.mock +def test_search_is_lazy(client): + route = respx.get(f"{BASE}/api/2/search/things").mock(side_effect=paged_search(1000)) + iterator = search_things(client) + next(iterator) + assert route.call_count == 1 + + +@respx.mock +def test_long_filters_use_form_post(client): + route = respx.post(f"{BASE}/api/2/search/things").mock(side_effect=paged_search(5)) + long_filter = "in(thingId," + ",".join(f'"org.example:t{i}"' for i in range(POST_THRESHOLD // 10)) + ")" + assert len(list(search_things(client, rql_filter=long_filter))) == 5 + request = route.calls.last.request + assert request.headers["Content-Type"] == "application/x-www-form-urlencoded" + assert parse_qs(request.content.decode())["filter"] == [long_filter] + + +def test_page_size_is_validated(client): + with pytest.raises(DittoctlError, match="page size"): + list(search_things(client, page_size=201)) + + +@respx.mock +def test_count(client): + route = respx.get(f"{BASE}/api/2/search/things/count").mock(return_value=httpx.Response(200, json=42)) + assert count_things(client, rql_filter="exists(attributes/x)", namespaces=["a"]) == 42 + assert route.calls.last.request.url.params["namespaces"] == "a" + + +@pytest.mark.parametrize( + ("thing_id", "path", "expected"), + [ + ("org.example:a", None, "/api/2/things/org.example:a"), + ("org.example:a", "/", "/api/2/things/org.example:a"), + ("org.example:a b#c", None, "/api/2/things/org.example:a%20b%23c"), + ("org.example:a", "/attributes/location/", "/api/2/things/org.example:a/attributes/location"), + ("org.example:a", "features/my feature", "/api/2/things/org.example:a/features/my%20feature"), + ], +) +def test_thing_path(thing_id, path, expected): + assert thing_path(thing_id, path) == expected + + +@respx.mock +def test_get_thing_sends_historical_headers(client): + route = respx.get(f"{BASE}/api/2/things/org.example:a").mock(return_value=httpx.Response(200, json={})) + get_thing(client, "org.example:a", fields="thingId", at_revision=7, at_timestamp="2026-11-01T00:00:00Z") + request = route.calls.last.request + assert request.headers["at-historical-revision"] == "7" + assert request.headers["at-historical-timestamp"] == "2026-11-01T00:00:00Z" + assert request.url.params["fields"] == "thingId" + + +@respx.mock +def test_get_things_batches_ids(client): + def handler(request: httpx.Request) -> httpx.Response: + ids = request.url.params["ids"].split(",") + return httpx.Response(200, json=[{"thingId": i} for i in ids if not i.endswith("missing")]) + + route = respx.get(f"{BASE}/api/2/things").mock(side_effect=handler) + ids = [f"org.example:thing-with-a-long-name-{i:04d}" for i in range(100)] + ["org.example:missing"] + result = list(get_things(client, ids, fields="thingId")) + assert len(result) == 100 + assert route.call_count > 1 + assert all(len(c.request.url.params["ids"]) <= 1500 for c in route.calls) + + +def test_sse_parser(): + lines = [ + ": keep-alive", + "id: 1", + 'data: {"a":', + "data: 1}", + "", + "event: custom", + "data: x", + "", + "data:", + "", + "data: last", + ] + assert list(iter_sse(lines)) == [ + SseEvent('{"a":\n1}', None, "1"), + # the last event id carries over until a new one arrives (SSE spec "last event ID buffer") + SseEvent("x", "custom", "1"), + SseEvent("", None, "1"), + SseEvent("last", None, "1"), + ] + + +@respx.mock +def test_watch_things_streams_events(client): + stream = ( + b'data: {"thingId":"org.example:a","attributes":{"x":1}}\n\n:\n\ndata:\n\ndata: {"thingId":"org.example:b"}\n\n' + ) + route = respx.get(f"{BASE}/api/2/things").mock( + return_value=httpx.Response(200, content=stream, headers={"Content-Type": "text/event-stream"}) + ) + events = list(watch_things(client, rql_filter="exists(attributes/x)", namespaces=["org.example"], + thing_ids=["org.example:a"], fields="thingId", extra_fields="attributes")) # fmt: skip + assert events == [{"thingId": "org.example:a", "attributes": {"x": 1}}, {"thingId": "org.example:b"}] + request = route.calls.last.request + assert request.headers["Accept"] == "text/event-stream" + assert dict(request.url.params) == { + "filter": "exists(attributes/x)", + "namespaces": "org.example", + "ids": "org.example:a", + "fields": "thingId", + "extraFields": "attributes", + } + + +@respx.mock +def test_watch_reports_errors(client): + respx.get(f"{BASE}/api/2/things").mock( + return_value=httpx.Response(403, json={"status": 403, "error": "things:thing.notallowed", "message": "no"}) + ) + with pytest.raises(DittoctlError, match=r"403 things:thing\.notallowed"): + list(watch_things(client)) + + +class BrokenStream(httpx.SyncByteStream): + """Delivers the given bytes, then fails like a dropped connection.""" + + def __init__(self, data: bytes) -> None: + self.data = data + + def __iter__(self): + yield self.data + raise httpx.ReadError("connection reset") + + +def sse_body(*things: dict) -> bytes: + return b"".join(f"id:{t['thingId']}\ndata:{json.dumps(t)}\n\n".encode() for t in things) + + +@pytest.fixture +def no_sleep_client(): + with DittoClient(BASE, sleep=lambda _s: None) as c: + yield c + + +@respx.mock +def test_stream_things(client): + route = respx.get(f"{BASE}/api/2/search/things").mock( + return_value=httpx.Response(200, content=sse_body({"thingId": "a:1"}, {"thingId": "a:2"}) + b":\n\n") + ) + items = list(stream_things(client, rql_filter="exists(attributes/x)", namespaces=["a"], fields="thingId", + sort="-_modified")) # fmt: skip + assert items == [{"thingId": "a:1"}, {"thingId": "a:2"}] + request = route.calls.last.request + assert request.headers["Accept"] == "text/event-stream" + assert dict(request.url.params) == { + "filter": "exists(attributes/x)", + "namespaces": "a", + "fields": "thingId", + "option": "sort(-_modified)", + } + + +@respx.mock +def test_stream_things_limit(client): + respx.get(f"{BASE}/api/2/search/things").mock( + return_value=httpx.Response(200, content=sse_body(*({"thingId": f"a:{i}"} for i in range(10)))) + ) + assert len(list(stream_things(client, limit=3))) == 3 + + +@respx.mock +def test_stream_things_raises_error_events(client): + error = {"status": 400, "error": "rql.expression.invalid", "message": "Unknown property name: features"} + respx.get(f"{BASE}/api/2/search/things").mock( + return_value=httpx.Response( + 200, content=sse_body({"thingId": "a:1"}) + f"data:{json.dumps(error)}\n\n".encode() + ) + ) + stream = stream_things(client) + assert next(stream) == {"thingId": "a:1"} + with pytest.raises(DittoError) as info: + next(stream) + assert info.value.status == 400 + assert info.value.error == "rql.expression.invalid" + + +@respx.mock +def test_stream_things_resumes_after_dropped_connection(no_sleep_client): + route = respx.get(f"{BASE}/api/2/search/things").mock( + side_effect=[ + httpx.Response(200, stream=BrokenStream(sse_body({"thingId": "a:1"}, {"thingId": "a:2"}))), + httpx.Response(200, content=sse_body({"thingId": "a:3"})), + ] + ) + assert [t["thingId"] for t in stream_things(no_sleep_client)] == ["a:1", "a:2", "a:3"] + assert "Last-Event-ID" not in route.calls[0].request.headers + assert route.calls[1].request.headers["Last-Event-ID"] == "a:2" + + +@respx.mock +def test_stream_things_gives_up_after_max_reconnects(no_sleep_client): + respx.get(f"{BASE}/api/2/search/things").mock(side_effect=lambda _r: httpx.Response(200, stream=BrokenStream(b""))) + with pytest.raises(DittoctlError, match="after 3 reconnects"): + list(stream_things(no_sleep_client)) + + +@pytest.mark.parametrize( + ("fields", "transport", "allowed", "rql_filter", "expected"), + [ + ("thingId", Transport.AUTO, True, None, "sse"), + (" thingId ", Transport.AUTO, True, None, "sse"), + ("thingId,attributes", Transport.AUTO, True, None, "paging"), + (None, Transport.AUTO, True, None, "paging"), + ("thingId", Transport.AUTO, False, None, "paging"), + ("thingId", Transport.AUTO, True, "in(thingId," + ",".join(['"a:1"'] * 500) + ")", "paging"), + ("thingId,attributes", Transport.SSE, False, None, "sse"), + ("thingId", Transport.PAGING, True, None, "paging"), + ], +) +@respx.mock +def test_find_things_picks_transport(client, fields, transport, allowed, rql_filter, expected): + def handler(request: httpx.Request) -> httpx.Response: + if request.headers.get("Accept") == "text/event-stream": + return httpx.Response(200, content=sse_body({"thingId": "via:sse"})) + return httpx.Response(200, json={"items": [{"thingId": "via:paging"}]}) + + respx.route(host="ditto.test").mock(side_effect=handler) + items = list(find_things(client, rql_filter=rql_filter, fields=fields, transport=transport, + streaming_allowed=allowed)) # fmt: skip + assert items == [{"thingId": f"via:{expected}"}] diff --git a/tests/test_selectors_writes.py b/tests/test_selectors_writes.py new file mode 100644 index 0000000..f259ec6 --- /dev/null +++ b/tests/test_selectors_writes.py @@ -0,0 +1,200 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +import json + +import httpx +import pytest +import respx + +from dittoctl.core.bulk import Category +from dittoctl.core.client import DittoClient +from dittoctl.core.conditions import Conditions, IfEqual +from dittoctl.core.jsonops import json_equal +from dittoctl.core.selectors import Selection, read_ids, resolve +from dittoctl.core.writes import array_operation, merge_operation, message_operation, put_operation +from dittoctl.errors import DittoctlError, DittoError + +BASE = "http://ditto.test" +THING = f"{BASE}/api/2/things/org.example:a" + + +@pytest.fixture +def client(): + with DittoClient(BASE, sleep=lambda _s: None) as c: + yield c + + +def test_read_ids_takes_first_column(): + lines = ["# comment", "org.example:a", " org.example:b\t404\tthings:thing.notfound", "", "org.example:c,x"] + assert read_ids(lines) == ["org.example:a", "org.example:b", "org.example:c"] + + +def test_resolve_ids_and_files(client, tmp_path): + ids_file = tmp_path / "ids.txt" + ids_file.write_text("org.example:b\norg.example:c\norg.example:a\n") + exclude = tmp_path / "exclude.txt" + exclude.write_text("org.example:c\n") + selection = Selection(ids=["org.example:a"], ids_file=str(ids_file), exclude_file=str(exclude)) + assert resolve(client, selection) == ["org.example:a", "org.example:b"] + + +@pytest.mark.parametrize( + ("selection", "message"), + [ + (Selection(), "no things selected"), + (Selection(ids=["a:1"], rql_filter="exists(attributes/x)"), "either by id"), + ], +) +def test_resolve_rejects_ambiguous_selections(client, selection, message): + with pytest.raises(DittoctlError, match=message): + resolve(client, selection) + + +@respx.mock +def test_resolve_falls_back_to_paging_when_sse_stream_is_short(client): + def search(request: httpx.Request) -> httpx.Response: + if request.headers.get("Accept") == "text/event-stream": + return httpx.Response(200, content=b'id:a:1\ndata:{"thingId":"a:1"}\n\n') # ends early + return httpx.Response(200, json={"items": [{"thingId": "a:1"}, {"thingId": "a:2"}]}) + + respx.get(f"{BASE}/api/2/search/things").mock(side_effect=search) + respx.get(f"{BASE}/api/2/search/things/count").mock(return_value=httpx.Response(200, json=2)) + warnings = [] + ids = resolve(client, Selection(rql_filter="exists(attributes/x)"), warn=warnings.append) + assert ids == ["a:1", "a:2"] + assert "returned 1 of 2" in warnings[0] + + +@respx.mock +def test_merge_operation(client): + route = respx.patch(f"{THING}/attributes").mock(return_value=httpx.Response(204)) + conditions = Conditions(if_equal=IfEqual.SKIP) + outcome = merge_operation(client, "attributes", {"room": "lab"}, conditions)("org.example:a") + assert outcome.category == Category.OK + assert route.calls.last.request.headers["If-Equal"] == "skip" + assert json.loads(route.calls.last.request.content) == {"room": "lab"} + + planned = merge_operation(client, "attributes", {"room": "lab"}, conditions, dry_run=True)("org.example:a") + assert planned.category == Category.PLANNED + assert planned.detail == { + "method": "PATCH", + "path": "/api/2/things/org.example:a/attributes", + "body": {"room": "lab"}, + "headers": {"If-Equal": "skip"}, + } + assert route.call_count == 1 + + +@respx.mock +def test_put_operation_create_only_reports_existing(client): + respx.put(THING).mock( + return_value=httpx.Response(412, json={"status": 412, "error": "things:precondition.failed", "message": "x"}) + ) + things = {"org.example:a": {"thingId": "org.example:a"}} + outcome = put_operation(client, things, Conditions(if_none_match="*"))("org.example:a") + assert outcome.category == Category.EXISTS + + +@respx.mock +def test_array_add_creates_missing_array_with_if_none_match(client): + respx.get(f"{THING}/attributes/tags").mock( + return_value=httpx.Response(404, json={"status": 404, "error": "things:attribute.notfound"}) + ) + put = respx.put(f"{THING}/attributes/tags").mock(return_value=httpx.Response(201)) + outcome = array_operation(client, "attributes/tags", ["x"])("org.example:a") + assert outcome.category == Category.OK + assert put.calls.last.request.headers["If-None-Match"] == "*" + assert json.loads(put.calls.last.request.content) == ["x"] + + +@respx.mock +def test_array_add_retries_after_concurrent_change(client): + respx.get(f"{THING}/attributes/tags").mock( + side_effect=[ + httpx.Response(200, json=["a"], headers={"ETag": 'W/"hash:1"'}), + httpx.Response(200, json=["a", "z"], headers={"ETag": '"hash:2"'}), + ] + ) + put = respx.put(f"{THING}/attributes/tags").mock( + side_effect=[ + httpx.Response(412, json={"status": 412, "error": "things:precondition.failed", "message": "if-match"}), + httpx.Response(204), + ] + ) + outcome = array_operation(client, "attributes/tags", ["b"], as_set=True)("org.example:a") + assert outcome.category == Category.OK + assert [c.request.headers["If-Match"] for c in put.calls] == ['"hash:1"', '"hash:2"'] + assert json.loads(put.calls.last.request.content) == ["a", "z", "b"] + + +@respx.mock +def test_array_conflict_after_retries(client): + respx.get(f"{THING}/attributes/tags").mock(return_value=httpx.Response(200, json=[], headers={"ETag": '"hash:1"'})) + respx.put(f"{THING}/attributes/tags").mock( + return_value=httpx.Response(412, json={"status": 412, "error": "things:precondition.failed"}) + ) + outcome = array_operation(client, "attributes/tags", ["b"], conflict_retries=2)("org.example:a") + assert outcome.category == Category.CONFLICT + + +@respx.mock +def test_array_unchanged_is_not_written(client): + respx.get(f"{THING}/attributes/tags").mock(return_value=httpx.Response(200, json=["a", 1.0])) + put = respx.put(f"{THING}/attributes/tags").mock(return_value=httpx.Response(204)) + assert ( + array_operation(client, "attributes/tags", ["a"], as_set=True)("org.example:a").category == Category.UNCHANGED + ) + assert ( + array_operation(client, "attributes/tags", ["x"], remove=True)("org.example:a").category == Category.UNCHANGED + ) + # with json equality 1 and 1.0 differ, so nothing matches and nothing is removed either + removal = array_operation(client, "attributes/tags", [1], remove=True, equal=json_equal)("org.example:a") + assert removal.category == Category.UNCHANGED + assert put.call_count == 0 + + +@respx.mock +def test_array_on_non_array_fails(client): + respx.get(f"{THING}/attributes/tags").mock(return_value=httpx.Response(200, json={"not": "an array"})) + with pytest.raises(DittoctlError, match="not an array"): + array_operation(client, "attributes/tags", ["x"])("org.example:a") + + +@respx.mock +def test_message_operation(client): + route = respx.post(f"{THING}/features/lamp/outbox/messages/switched").mock( + return_value=httpx.Response(200, json={"ok": True}) + ) + outcome = message_operation(client, "switched", {"on": True}, feature="lamp", outbox=True, timeout=5)( + "org.example:a" + ) + assert outcome.detail == {"ok": True} + assert route.calls.last.request.url.params["timeout"] == "5" + + text = respx.post(f"{THING}/inbox/messages/say").mock(return_value=httpx.Response(202)) + message_operation(client, "say", "hello", content_type="text/plain", timeout=0)("org.example:a") + assert text.calls.last.request.content == b"hello" + assert text.calls.last.request.headers["Content-Type"] == "text/plain" + + +@respx.mock +def test_errors_propagate_for_classification(client): + respx.patch(f"{THING}/attributes").mock( + return_value=httpx.Response(404, json={"status": 404, "error": "things:thing.notfound"}) + ) + with pytest.raises(DittoError): + merge_operation(client, "attributes", {}, Conditions())("org.example:a") diff --git a/tests/test_wot.py b/tests/test_wot.py new file mode 100644 index 0000000..47e2d35 --- /dev/null +++ b/tests/test_wot.py @@ -0,0 +1,212 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# http://www.eclipse.org/legal/epl-2.0 +# +# AI Disclosure: This file was largely AI-generated. The AI-generated +# portions are made available under CC0-1.0 and not subject to the +# project's licence. The human contributor has reviewed and verified +# that the code is correct. +# +# SPDX-License-Identifier: EPL-2.0 AND CC0-1.0 +# Assisted-by: Anthropic Claude Opus 5.5 (claude-opus-5-5) +from __future__ import annotations + +import json + +import httpx +import pytest +import respx + +from dittoctl.core.wot import compact_td, compact_thing_description, feature_links + +URL = "http://ditto.test" +MODELS = "https://models.example.org" +ERROR_RESPONSE = [{"success": False, "schema": "dittoError"}] + + +def form(op: str, href: str, method: str = "GET") -> dict: + return { + "op": op, + "href": href, + "htv:methodName": method, + "contentType": "application/json", + "additionalResponses": ERROR_RESPONSE, + } + + +def thing_td(*features: str) -> dict: + return { + "@context": ["https://www.w3.org/2022/wot/td/v1.1", {"om2": "http://example.org/om-2/"}], + "@type": "Thing", + "id": "urn:org.example:lamp-1", + "base": f"{URL}/api/2/things/org.example:lamp-1/", + "title": "Floor lamp", + "security": "basic_sc", + "securityDefinitions": {"basic_sc": {"in": "header", "scheme": "basic"}}, + "schemaDefinitions": {"dittoError": {"type": "object"}}, + "forms": [form("readallproperties", "attributes")], + "links": [ + {"rel": "type", "href": f"{MODELS}/floor-lamp-1.0.0.tm.jsonld", "type": "application/tm+json"}, + *({"rel": "item", "href": f"features/{f}", "type": "application/td+json"} for f in features), + ], + "properties": { + "serialNo": { + "title": "Serial number", + "type": "string", + "readOnly": True, + "forms": [form("readproperty", "attributes/serialNo")], + } + }, + "actions": { + "switch-all": { + "title": "Switch all spots", + "input": {"type": "boolean"}, + "forms": [form("invokeaction", "inbox/messages/switch-all", "POST")], + } + }, + } + + +def spot_td(name: str) -> dict: + return { + "@context": ["https://www.w3.org/2022/wot/td/v1.1", {"time": "http://example.org/time#"}], + "@type": "Thing", + "base": f"{URL}/api/2/things/org.example:lamp-1/features/{name}/", + "title": "Spot", + "links": [ + {"rel": "collection", "href": "../../"}, + {"rel": "type", "href": f"{MODELS}/spot-1.0.0.tm.jsonld"}, + ], + "properties": { + "dimmer-level": { + "@type": "om2:Percentage", + "type": "number", + "minimum": 0, + "maximum": 1, + "forms": [ + form("readproperty", "properties/dimmer-level"), + form("writeproperty", "properties/dimmer-level", "PUT"), + ], + } + }, + "events": {"overheated": {"data": {"type": "number"}, "forms": [form("subscribeevent", "outbox/messages/x")]}}, + } + + +def test_feature_links(): + assert feature_links(thing_td("Spot1", "Spot2")) == ["Spot1", "Spot2"] + assert feature_links({"links": [{"rel": "collection", "href": "features/x"}]}) == [] + + +def test_compact_td_keeps_only_what_describes_the_thing(): + assert compact_td(thing_td("Spot1")) == { + "title": "Floor lamp", + "model": f"{MODELS}/floor-lamp-1.0.0.tm.jsonld", + "properties": { + "serialNo": {"path": "attributes/serialNo", "title": "Serial number", "type": "string", "readOnly": True} + }, + "actions": { + "switch-all": { + "path": "inbox/messages/switch-all", + "title": "Switch all spots", + "input": {"type": "boolean"}, + } + }, + } + + +def test_compact_td_keeps_semantic_types_and_own_schemas(): + td = { + **spot_td("Spot1"), + "@type": ["Thing", "saref:LightSwitch"], + "schemaDefinitions": {"dittoError": {}, "rgb": {}}, + } + compact = compact_td(td) + assert compact["@type"] == ["Thing", "saref:LightSwitch"] + assert compact["schemaDefinitions"] == {"rgb": {}} + assert compact["properties"]["dimmer-level"]["@type"] == "om2:Percentage" + + +def test_compact_thing_description_merges_prefixes_and_identical_features(): + td = { + **thing_td("Spot1", "Spot2", "Broken"), + "features": { + "Spot1": spot_td("Spot1"), + "Spot2": spot_td("Spot2"), + "Broken": {"error": "wot:thingmodel.notfound", "message": "not found"}, + }, + } + compact = compact_thing_description(td) + assert compact["prefixes"] == {"om2": "http://example.org/om-2/", "time": "http://example.org/time#"} + assert compact["features"]["Spot1"]["properties"]["dimmer-level"]["path"] == "properties/dimmer-level" + assert compact["features"]["Spot2"] == {"sameAs": "Spot1"} + assert compact["features"]["Broken"] == {"error": "wot:thingmodel.notfound", "message": "not found"} + + +@pytest.fixture +def ditto(): + with respx.mock(base_url=URL, assert_all_called=False) as mock: + yield mock + + +def test_td_with_features(run, ditto): + thing = ditto.get("/api/2/things/org.example:lamp-1").mock( + return_value=httpx.Response(200, json=thing_td("Spot1", "Broken")) + ) + ditto.get("/api/2/things/org.example:lamp-1/features/Spot1").mock( + return_value=httpx.Response(200, json=spot_td("Spot1")) + ) + ditto.get("/api/2/things/org.example:lamp-1/features/Broken").mock( + return_value=httpx.Response( + 404, json={"status": 404, "error": "wot:thingmodel.notfound", "message": "The model was not found."} + ) + ) + result = run("--url", URL, "things", "td", "org.example:lamp-1", "--with-features") + assert result.exit_code == 0, result.stderr + full = json.loads(result.stdout) + assert full["securityDefinitions"] + assert full["features"]["Spot1"]["base"].endswith("/features/Spot1/") + assert full["features"]["Broken"] == {"error": "wot:thingmodel.notfound", "message": "The model was not found."} + assert thing.calls.last.request.headers["Accept"] == "application/td+json" + + result = run("--url", URL, "things", "td", "org.example:lamp-1", "--with-features", "--compact") + assert result.stdout.count("\n") == 1 + compact = json.loads(result.stdout) + assert "forms" not in result.stdout + assert compact["features"]["Spot1"]["events"] == { + "overheated": {"path": "outbox/messages/x", "data": {"type": "number"}} + } + + +def test_td_feature_and_with_features_exclude_each_other(run): + result = run("--url", URL, "things", "td", "org.example:lamp-1", "--feature", "Spot1", "--with-features") + assert result.exit_code == 1 + assert "either --feature or --with-features" in result.stderr + + +def test_compact_refers_to_repeated_schemas(): + transitions = { + "title": "Transitions", + "description": "Start of each transition and the temperature to apply from then on.", + "type": "array", + "items": {"type": "object", "properties": {"minutes": {"type": "integer"}, "celsius": {"type": "number"}}}, + } + days = {day: {"title": day, "type": "object", "properties": {"transitions": transitions}} for day in ("MON", "TUE")} + td = { + "title": "Schedule", + "properties": {"days": {"type": "object", "properties": days, "forms": [form("x", "p")]}}, + } + compact = compact_thing_description(td) + days_out = compact["properties"]["days"]["properties"] + assert days_out["MON"]["properties"]["transitions"] == transitions + assert days_out["TUE"]["properties"]["transitions"] == { + "$ref": "#/properties/days/properties/MON/properties/transitions" + } + + short = compact_thing_description(td, schema_descriptions=False) + assert "description" not in short["properties"]["days"]["properties"]["MON"]["properties"]["transitions"]