diff --git a/wiki/cascade-cms-wiki/docs/advanced/cpu-intensive.md b/wiki/cascade-cms-wiki/docs/advanced/cpu-intensive.md index 770cf89..f248e70 100644 --- a/wiki/cascade-cms-wiki/docs/advanced/cpu-intensive.md +++ b/wiki/cascade-cms-wiki/docs/advanced/cpu-intensive.md @@ -6,10 +6,10 @@ By default `.then()` callbacks run on the async event loop, which is fine for I/ ## When to Use `ProcessPoolExecutor` -- Image resizing, compression, or optimization -- Parsing large XML/JSON structures or heavy data transformation -- Running intensive regular expressions across large HTML bodies -- Light callbacks like simple string replacements or metadata dictionary updates do not need it and perform better on the default thread pool or event loop. +- Image resizing, compression, or other pixel-level processing operations +- Heavy data transformations or bulk regex parsing on large HTML bodies +- Complex serialization or cryptographic hashing tasks +- Light callbacks (title string replace, metadata dict update) that don't need it and are faster on the default thread pool or main loop --- @@ -18,18 +18,10 @@ By default `.then()` callbacks run on the async event loop, which is fine for I/ ```python from concurrent.futures import ProcessPoolExecutor from os import cpu_count -from cascade_cms import Cascade -env = {"SERVER": "prod", "API_KEY": "secret", "CASCADE_URL": "https://cascade.example.com"} - -def optimize_image(asset): - # CPU-bound image processing work here - return asset - -with Cascade(env, {}) as cascade: - with ProcessPoolExecutor(max_workers=cpu_count()) as executor: - cascade.operations.read(id).then(optimize_image) - results = cascade.submit_requests(executor=executor) +with ProcessPoolExecutor(max_workers=cpu_count()) as executor: + cascade.operations.read(id).then(optimize_image) + results = cascade.submit_requests(executor=executor) ``` --- @@ -58,12 +50,12 @@ cascade.operations.read(id).then(transform) ## `ProcessPoolExecutor` vs `ThreadPoolExecutor` -`ProcessPoolExecutor` provides true parallelism across multiple CPU cores in separate memory spaces, but requires all callback functions and data to be picklable and incurs inter-process communication overhead. `ThreadPoolExecutor` uses shared memory with minimal overhead and no pickling restrictions, but remains limited by Python's Global Interpreter Lock (GIL) for CPU-bound tasks. Use `ProcessPoolExecutor` for heavy CPU computation, and stick with `ThreadPoolExecutor` (the default) for I/O-bound work. +`ProcessPoolExecutor` provides true parallelism across multiple CPU cores with separate memory spaces, but requires all callback functions and data to be picklable and incurs higher task-dispatch overhead. `ThreadPoolExecutor` (which is the default) shares memory and has lower overhead, but is still bound by the Global Interpreter Lock (GIL) and cannot achieve true parallelism for CPU-bound tasks. Use `ProcessPoolExecutor` for CPU-heavy workflows and `ThreadPoolExecutor` for I/O-bound work. --- ## Performance Considerations -Spawning and managing worker processes carries an initialization overhead, meaning extremely fast callbacks may run slower in a process pool than synchronously due to serialization costs. Additionally, offloading CPU work via the executor does not change the network concurrency rules; the driver's underlying `MAX_REQUESTS` semaphore still governs HTTP request limits. +Spawning worker processes has a measurable startup cost, so for very fast callbacks the inter-process communication and pickling overhead may outweigh the parallel execution benefit. Additionally, the driver's underlying request concurrency semaphore still governs HTTP operations independently of whatever executor is chosen for synchronous callback functions. - + diff --git a/wiki/cascade-cms-wiki/docs/advanced/index.md b/wiki/cascade-cms-wiki/docs/advanced/index.md index 36d9ed5..5d95a06 100644 --- a/wiki/cascade-cms-wiki/docs/advanced/index.md +++ b/wiki/cascade-cms-wiki/docs/advanced/index.md @@ -1,6 +1,6 @@ # Advanced -Welcome to the advanced power user guide for tuning and scaling your application. This section covers configuration and performance topics that go beyond the defaults, including caching behavior, debug logging, and CPU-intensive callback patterns. +Welcome to the advanced section for power users who want to tune their library usage beyond the standard defaults. This guide covers performance optimization for CPU-intensive callbacks and granular configuration for debugging complex workflows. --- @@ -11,4 +11,4 @@ Welcome to the advanced power user guide for tuning and scaling your application | [Logging & Debugging](logging.md) | Enabling debug mode, configuring the debug dict, reading log output, and walking through a sample logfile | | [CPU-Intensive Tasks](cpu-intensive.md) | When to use `ProcessPoolExecutor`, pickling constraints, and performance trade-offs vs `ThreadPoolExecutor` | - + diff --git a/wiki/cascade-cms-wiki/docs/advanced/logging.md b/wiki/cascade-cms-wiki/docs/advanced/logging.md index b93a28f..d5533db 100644 --- a/wiki/cascade-cms-wiki/docs/advanced/logging.md +++ b/wiki/cascade-cms-wiki/docs/advanced/logging.md @@ -1,22 +1,23 @@ -# Logging & Debugging +# Logging & Design -Operation logger owns all console, logfile, and (verbose mode) request/response file output for the cascade_cms library. Two output modes exist: normal mode for everyday use and debug mode for diagnosing failures, controlled solely by whether `debug_config` is `None`. Both produce logfiles; debug mode adds a verbose nested call-chain log alongside a quieter console output. +The `cascade_cms` library provides two distinct logging and execution modes: normal mode for everyday use and debug mode for diagnosing failures. Both produce detailed logfiles, but debug mode adds a verbose nested call-chain log alongside a quieter console output. --- ## Normal Mode Output -Normal mode produces minimal console output and a simple logfile. It logs lifecycle markers such as `[INIT]`, `[RUNNING]`, `[DONE]`, and `[EXIT]`, along with batch tallies and operation progress lines. The normal logfile is named `{SERVER}_{timestamp}.log` and records one line per chain. +Normal mode outputs minimal console messages and a simple logfile. It handles initialization, progress reporting, and cleanup while writing one concise line per completed chain to the logfile. ### Normal Logfile Format ```text -[INIT]: Connecting to myserver.com -[RUNNING]: myscript.py -(uuid_or_path, asset_type) OP1 -> fn_name: Type -> ... -1/1 succeeded -[DONE]: 1 assets processed in 0.5s -[EXIT]: Disconnecting from myserver.com +[INIT]: Connecting to example.com +[LOG]: logs/example.com_2023-10-27T12-00-00-000000_1.log +[RUNNING]: my_script.py +3/3 succeeded +[DONE]: 3 assets processed in 0.5s +0 failed, 3 succeeded +[EXIT]: Disconnecting from example.com ``` --- @@ -24,43 +25,42 @@ Normal mode produces minimal console output and a simple logfile. It logs lifecy ## Enabling Debug Mode ```python -wrapper = CascadeWrapperBase("myserver.com", debug_config={ +debug_config = { "log_dir": "./logs", - "show_network_headers": True -}) + "show_network_headers": True, +} +wrapper = CascadeWrapperBase(server="example.com", debug_config=debug_config) ``` --- ## Debug Configuration Options -Recognized `debug_config` keys control the log directory and network header visibility. - | Key | Type | Default | Description | |-----|------|---------|-------------| -| log_dir | str | "./logs" | Directory for the logfile and (verbose mode) request/response JSON files. | +| log_dir | str / PathLike | "./logs" | Directory for the logfile and (verbose mode) request/response JSON files. | | show_network_headers | bool | False | Verbose mode only: also log request/response HTTP headers. | --- ## Debug Logfile Format -The debug logfile uses the naming convention `{SERVER}_debug_{timestamp}.log`. It features a quiet console, a verbose logfile, and per-request JSON files. There is no longer a separate "log operations vs. callbacks vs. responses" toggle — `_is_debug` is the single on/off switch for verbose behavior. +The debug logfile is named using the pattern `{SERVER}_debug_{timestamp}_{serial}.log`. It contains a quiet console output, a verbose logfile, and per-request JSON files when `debug_config` is provided. ### Sample Debug Log ```text ->>>> START REQUEST <<+ -(uuid_or_path, asset_type) OP1 -> fn_name: Type -> ... -[GET] https://myserver.com/api/v1/read/site/path -1/1 succeeded ->>>> END REQUEST <<<< +>>>> START REQUEST <<^ +(mySite/blog/post-1, page) READ -> read +[GET] https://example.com/api/v1/read/page/mySite/blog/post-1 +3/3 succeeded +>>>> END REQUEST <<^ ``` --- ## Interpreting Errors in Debug Mode -Error lines in debug mode utilize a `v` marker followed by an `!ERROR:` block indicating the failure at the specified step index. Chain-level failures go through `flush_chain_error` which has step-index context. `log_cascade_error` provides a thin wrapper to log a `CascadeError` (API-level failure) outside of chain context, while `log_python_error` logs an unhandled Python exception with traceback, file name, and line number. +When a failure occurs, `OperationLogger` records a `v` marker pointing directly to the column of the failing step, followed by an `!ERROR:` block that includes the error message and the source file and line number (`@{file}:{line}`). For network or library failures, category prefixes such as `[NETWORK]` or `[CASCADE-REST-CMS]` are prepended to the message. - + diff --git a/wiki/cascade-cms-wiki/docs/core-concepts/index.md b/wiki/cascade-cms-wiki/docs/core-concepts/index.md index 4084a01..36f243b 100644 --- a/wiki/cascade-cms-wiki/docs/core-concepts/index.md +++ b/wiki/cascade-cms-wiki/docs/core-concepts/index.md @@ -1,197 +1,89 @@ # Core Concepts -## The `Cascade` class +Building on the quick-start guide, this page explores the library's mental model: the top-level `Cascade` wrapper acts as a context manager coordinating the REST driver and logger, while `cascade.operations` starts fluent builder chains of requests and callbacks that execute concurrently via `submit_requests()`. -`Cascade` is the single entry point for all library interactions. Open a -session with it as a [context manager](https://docs.python.org/3/reference/datamodel.html#context-managers): - -```python -from cascade_cms.wrapper import Cascade, EnvironmentVars - -env: EnvironmentVars = { - "SERVER": "my-site", - "API_KEY": "your-api-key", - "CASCADE_URL": "https://your-cascade-instance.com", -} +--- -with Cascade(env) as cascade: - # queue operations here - ... -``` +## Basic Operation Calls -Previously known as `CascadeWrapperBase`; the alias still works but `Cascade` -is the current name. +Every script follows the same skeleton: open the wrapper as a context manager, queue operations on `cascade.operations`, chain callbacks with `.then()`, then call `submit_requests()` once to execute all chains concurrently. These operations form a singly linked list via `next` where each node carries its prepared requests or wraps a result-processing function. The chain stops at the first failure so results and errors map directly to their exact step. -### Constructor +### Example ```python -Cascade( - environmentVariables: EnvironmentVars, - debug: dict[str, Any] | None = None, - *, - exit_on_failure: bool = True, - log_dir: str | os.PathLike | None = None, -) +with Cascade(env_vars) as cascade: + # Queue a read operation on the operations builder + cascade.operations.read(identifier) + + # Execute all queued chains concurrently and get results + results = cascade.submit_requests(Asset) + + # Each entry in results corresponds to a queued chain + for result in results: + if isinstance(result, CascadeError): + print(f"Error: {result.message}") + else: + print(f"Success: {result}") ``` -`EnvironmentVars` is a `TypedDict` with three required keys: - -| Key | Description | -|---|---| -| `SERVER` | Label used in log output (not a network address) | -| `API_KEY` | Cascade REST API bearer token | -| `CASCADE_URL` | Base URL of your Cascade CMS instance | - -`exit_on_failure=True` (default) ends the script non-zero on any failure. -Pass `False` for long-lived processes like the MCP server. - ---- - -## Operations - -`cascade.operations` is the entry point for all CMS operations. It returns -an `Operations` builder that accepts the first call in a chain: +### Expected Output ```python -with Cascade(env) as cascade: - chain = cascade.operations.read("abc123") +Asset(_asset_type='page', _data={'id': '1234567890abcdef...', 'name': 'index', ...}) ``` -Available operations mirror the Cascade REST API: - -| Operation | Description | -|---|---| -| `.read(id)` | Read one asset | -| `.edit(payload)` | Edit an asset via callback or direct payload | -| `.publish(id)` | Publish an asset | -| `.delete(id)` | Delete an asset | -| `.copy(id, dest)` | Copy an asset | -| `.move(id, dest)` | Move an asset | -| `.checkIn(id)` | Check in an asset | -| `.checkOut(id)` | Check out an asset | -| `.search(query)` | Search assets | -| `.create(asset)` | Create a new asset | - -See the [API Reference](../operations/operations.md) for full signatures. - --- -## Operation chains - -Each operation call returns an `OperationChain`, not a result. Nothing -executes until you call `.submit_requests()`. This design lets you compose -multi-step workflows before any network requests are made: - -```python -from cascade_cms.cmstypes import Asset - -def set_searchable(asset: Asset) -> Asset: - asset.searchable = True - return asset - -with Cascade(env) as cascade: - results = ( - cascade.operations - .read("abc123") - .edit(set_searchable) - .publish("abc123") - .submit_requests(Asset) - ) -``` - -The type argument to `.submit_requests()` is for the type checker. `Asset` -covers most cases; use a more specific type when the operation returns one. - ---- +## Payload Models -## `edit()` and callbacks +Payload models are typed objects (subclasses of `SimplePayload`) that pair with specific operations to ensure the API endpoint receives the expected fields and headers. They provide type safety and structural clarity by wrapping raw data structures in validated Pydantic models before serialization. -`edit()` accepts a callable, a single asset, or a list of assets. The -callable form is the most common in practice: +### Example: `SearchInformation` paired with `search` ```python -def update_keywords(asset: Asset) -> Asset: - asset.keywords = "updated" - return asset - -cascade.operations.edit(update_keywords) -``` - -The callback receives the current asset and must return the modified asset. -The identifier is derived from the asset's own `id`/`path`/`siteName` fields -— there is no separate identifier argument on `edit()` in 3.9.1. - ---- - -## Batch execution and `ChainGroup` - -Passing a list to operations that accept identifiers — `read`, `delete`, -`publish`, etc. — creates one independent `OperationChain` per identifier, -returned as a `ChainGroup`: +from cascade_cms.cmstypes import SearchInformation + +# Construct the payload model specifying search criteria +payload = SearchInformation( + siteName="Default", + searchTerms="blog", + searchFields=["name", "summary"], + searchTypes=["page"] +) -```python -with Cascade(env) as cascade: - results = ( - cascade.operations - .read(["id1", "id2", "id3"]) - .submit_requests(Asset) - ) +with Cascade(env_vars) as cascade: + # Pass the payload model directly to the search operation + cascade.operations.search(payload) + results = cascade.submit_requests() ``` -Failures in one chain do not cancel others. The returned `ChainResults` -covers all chains in the group. +The model enforces required fields and formatting at runtime, preventing invalid requests from hitting the REST API. Other operations follow the exact same typed parameter pattern, such as `deleteParameters`, `auditParameters`, and `copyParameters`. --- -## Result handling +## CPU-Intensive Operations -`.submit_requests()` returns `ChainResults[T]` — a list subclass with -`.success` and `.failed` properties. See [Result Handling](../getting-started/result-handling.md) -for full details. +For operations involving heavy computation in `.then()` callbacks — image processing, data transformation, bulk string manipulation — offload work to a `ProcessPoolExecutor` rather than running it on the async event loop. ```python -results = cascade.operations.read("abc123").submit_requests(Asset) +from concurrent.futures import ProcessPoolExecutor +from os import cpu_count -for asset in results.success: - print(asset.path) - -for failure in results.failed: - print(f"[{failure.category}] {failure.message}") +with ProcessPoolExecutor(max_workers=cpu_count()) as executor: + with Cascade(env_vars) as cascade: + cascade.operations.read(identifier).then(optimize_image) + results = cascade.submit_requests(executor=executor) ``` ---- - -## Script logging - -`script_log.note()` writes annotated log lines from within a script: - -```python -from cascade_cms.utils import script_log - -with Cascade(env) as cascade: - script_log.note("Starting run") - results = cascade.operations.read("abc123").submit_requests(Asset) - script_log.note(f"Done — {len(results.success)} succeeded") -``` +!!! note "Module-level functions only" + Callbacks passed to `ProcessPoolExecutor` must be defined at module level — lambdas and nested functions are not picklable and will raise at runtime. -Calls outside the `with` block drop silently with a `RuntimeWarning`. -API keys are automatically redacted from log output. +See [Advanced: CPU-Intensive Tasks](../advanced/cpu-intensive.md) for full configuration details, performance trade-offs, and `ThreadPoolExecutor` comparison. --- -## Identifiers - -The `utils.identifiers` module (added in 3.8.3) coerces raw Cascade -identifier dicts to `IdentifierType`: - -```python -from cascade_cms.utils.identifiers import to_identifier, to_identifiers - -identifier = to_identifier({"id": "abc123", "type": "page", "path": None}) -identifiers = to_identifiers([{"id": "a"}, {"id": "b"}]) -``` +## Next Steps -Use these when processing raw API responses before passing identifiers to -operations. +Ready to go deeper? The [Advanced](../advanced/index.md) section covers configuration topics for power users: debug logging and CPU-intensive workload patterns. - + diff --git a/wiki/cascade-cms-wiki/docs/examples/administrative-ops.md b/wiki/cascade-cms-wiki/docs/examples/administrative-ops.md index fc148e5..dc88be2 100644 --- a/wiki/cascade-cms-wiki/docs/examples/administrative-ops.md +++ b/wiki/cascade-cms-wiki/docs/examples/administrative-ops.md @@ -13,26 +13,25 @@ skeleton as the main patterns, just applied to two unrelated features. ## Messages: list, mark, delete ```python -from cascade_cms.wrapper import Cascade -from cascade_cms.cmstypes import CascadeSuccess, ListElements - -with Cascade(env) as cascade: - # Phase 1: List inbox messages - listed = cascade.operations.listMessages().submit_requests(ListElements) - - # Pick a message from the list elements - message = listed.success[0].flat[0] - - # Phase 2: Mark as read and then delete - results = ( - cascade.operations - .markMessage(message) - .deleteMessage(message) - .submit_requests(CascadeSuccess) - ) - -for failure in results.failed: - print(f"[{failure.category}] {failure.step_name}: {failure.message}") +from cascade_cms import CascadeCMS +from cascade_cms.cmstypes import CascadeError + +cms = CascadeCMS(url="...", username="...", password="...") + +# Phase 1: List inbox messages +cms.operations.listMessages() +messages_result = cms.submit_requests() + +if isinstance(messages_result, CascadeError): + raise RuntimeError(messages_result.message) + +# Assume we found a message to process +message = messages_result.flat[0] + +# Phase 2: Mark read and delete the message +cms.operations.markMessage(message) +cms.operations.deleteMessage(message) +results = cms.submit_requests() ``` !!! note @@ -44,22 +43,24 @@ for failure in results.failed: ## Preferences: read, edit ```python -from cascade_cms.wrapper import Cascade -from cascade_cms.cmstypes import CascadeSuccess, SimplePayload, preference - -with Cascade(env) as cascade: - # Read current preferences - prefs = cascade.operations.readPreferences().submit_requests(SimplePayload) - - # Update a user preference - results = ( - cascade.operations - .editPreference(preference(name="pref_name", value="new_value")) - .submit_requests(CascadeSuccess) - ) - -for failure in results.failed: - print(f"[{failure.category}] {failure.step_name}: {failure.message}") +from cascade_cms import CascadeCMS +from cascade_cms.cmstypes import CascadeError, preference + +cms = CascadeCMS(url="...", username="...", password="...") + +# Read current preferences +cms.operations.readPreferences() +prefs_result = cms.submit_requests() + +if isinstance(prefs_result, CascadeError): + raise RuntimeError(prefs_result.message) + +# Update a user preference +cms.operations.editPreference(preference(name="my-pref", value="new-value")) +edit_result = cms.submit_requests() + +if isinstance(edit_result, CascadeError): + raise RuntimeError(edit_result.message) ``` !!! note @@ -71,4 +72,4 @@ for failure in results.failed: See [Core Patterns](main-patterns.md) for `read`, `delete`, and `search` — the primary asset-management workflow and response-shape conventions. - + diff --git a/wiki/cascade-cms-wiki/docs/examples/main-patterns.md b/wiki/cascade-cms-wiki/docs/examples/main-patterns.md index b354156..1fd00d2 100644 --- a/wiki/cascade-cms-wiki/docs/examples/main-patterns.md +++ b/wiki/cascade-cms-wiki/docs/examples/main-patterns.md @@ -1,191 +1,133 @@ -# Main Patterns +# Core Patterns: `read`, `delete`, `search` -Common usage patterns for `cascade-cms-rest` 3.9.1. +Every script that uses `cascade_cms` follows the same shape: open the wrapper as +a context manager, queue up one or more operations on `cascade.operations`, then +call `submit_requests()` once to run them all concurrently. -```python -from cascade_cms.wrapper import Cascade, EnvironmentVars -from cascade_cms.cmstypes import Asset - -env: EnvironmentVars = { - "SERVER": "my-site", - "API_KEY": "your-api-key", - "CASCADE_URL": "https://your-cascade-instance.com", -} -``` - ---- - -## Read a single asset +The three examples below use the same skeleton but highlight the **three +distinct response shapes** you'll see across the library: -```python -with Cascade(env) as cascade: - results = cascade.operations.read("abc123").submit_requests(Asset) +| Operation | Returns | Why it's shown | +|-----------|---------|----------------| +| `read` | A large, structured `Asset` object | Most operations that touch an existing asset return this shape | +| `delete` | A simple success object (`CascadeSuccess`) | Mutating operations that don't return data use this minimal shape | +| `search` | A list result, driven by a required `SearchInformation` payload | Shows the "operation needs a payload object" pattern | -if results.success: - asset = results.success[0] - print(asset.path) - print(asset.siteName) -``` +All three also demonstrate the same failure-handling rule: **failures are +returned as values, not raised.** Always check `isinstance(result, CascadeError)` +before using a result. --- -## Edit and save - -Use a callback that receives the current asset and returns the modified one: +## Pattern 1 — `read`: fetching a structured asset ```python -def update_metadata(asset: Asset) -> Asset: - asset.keywords = "cascade, cms, updated" - asset.metaDescription = "Updated via py-cascade-cms" - return asset - -with Cascade(env) as cascade: - results = ( - cascade.operations - .read("abc123") - .edit(update_metadata) - .submit_requests(Asset) - ) - -if results.failed: - for failure in results.failed: - print(f"[{failure.category}] {failure.step_name}: {failure.message}") +with CascadeWrapperBase("config.json") as cascade: + # Build a Path identifier pointing to a page in the default site + identifier = Path(asset_type=AssetTypes.page, path="/index", site_name="default") + + # Queue the read operation + cascade.operations.read(identifier) + + # Submit all queued requests concurrently + results = cascade.submit_requests() + result = results[0] + + # Check if the result is an API-level error + if isinstance(result, CascadeError): + print(f"Error: {result.message}") + else: + # Access structured asset fields + print(result.displayName) + print(result.metadata) ``` -The callback receives the asset after `.read()` completes. The identifier -is derived from the asset's own `id`/`path`/`siteName` fields — no separate -argument on `edit()`. +The `read` operation represents the response shape that most other "fetch" operations follow—such as `readAudits`, `readAccessRights`, and `readWorkflowSettings`—meaning they all return a structured object specific to what was requested rather than raw JSON dictionaries. --- -## Publish - -Chain `.publish()` after editing to write and publish in one batch: +## Pattern 2 — `delete`: a simple success response ```python -with Cascade(env) as cascade: - results = ( - cascade.operations - .read("abc123") - .edit(update_metadata) - .publish("abc123") - .submit_requests(Asset) +with CascadeWrapperBase("config.json") as cascade: + # Build a Path identifier for the asset to delete + identifier = Path(asset_type=AssetTypes.page, path="/old-page", site_name="default") + + # Configure delete parameters + payload = deleteParameters( + doWorkflow=False, + destinations=[], + unpublish=True ) + + # Queue the delete operation with parameters + cascade.operations.delete(identifier, payload=payload) + + # Execute the request queue + results = cascade.submit_requests() + result = results[0] + + if isinstance(result, CascadeError): + print(f"Delete failed: {result.message}") + else: + print("Delete succeeded successfully.") ``` -Or publish without editing: - -```python -with Cascade(env) as cascade: - results = cascade.operations.publish("abc123").submit_requests(Asset) -``` +Mutating operations like `delete`, `copy`, `move`, `publish`, `checkIn`, and `editAccessRights` return confirmation only via a `CascadeSuccess` object rather than the modified asset data. Callers should not expect asset data back from these operations. --- -## Search +## Pattern 3 — `search`: payload-driven, list response ```python -from cascade_cms.cmstypes import SearchInformation, ListElements - -payload = SearchInformation( - searchTerms="annual report", - siteName="site123", -) - -with Cascade(env) as cascade: - results = ( - cascade.operations - .search(payload) - .submit_requests(ListElements) +with CascadeWrapperBase("config.json") as cascade: + # Construct a SearchInformation payload object + payload = SearchInformation( + siteName="default", + searchTerms="news", + searchFields=[FieldsSearchTypes.name], + searchTypes=[AssetTypes.page] ) - -if results.success: - for item in results.success: - print(item) + + # Queue the search operation + cascade.operations.search(payload) + + # Execute requests + results = cascade.submit_requests() + result = results[0] + + if isinstance(result, CascadeError): + print(f"Search failed: {result.message}") + else: + # Iterate over the flat list elements returned in the search response + for item in result.flat: + print(item) ``` -`SearchInformation` is the typed payload; `ListElements` is the return type -from `.search()`. Both are in `cascade_cms.cmstypes`. - ---- - -## Bulk operations - -Pass a list of identifiers. Each gets its own independent chain — failures -in one do not cancel others: - -```python -asset_ids = ["id1", "id2", "id3"] - -def tag_asset(asset: Asset) -> Asset: - asset.tags = [{"name": "bulk-update"}] - return asset - -with Cascade(env) as cascade: - results = ( - cascade.operations - .read(asset_ids) - .edit(tag_asset) - .publish(asset_ids) - .submit_requests(Asset) - ) - -print(f"{len(results.success)} updated, {len(results.failed)} failed") - -for failure in results.failed: - print(f" {failure.identifier}: [{failure.category}] {failure.message}") -``` +The `search` operation requires a strongly-typed payload object (`SearchInformation`) rather than a bare identifier shortcut. Other administrative and query operations follow this exact same pattern by accepting dedicated parameters objects like `auditParameters` for `readAudits`. --- -## Handling failures by category - -`ChainFailure.category` holds the `FailureCategory` value — use it directly: - -```python -from cascade_cms.utils.failures import FailureCategory - -with Cascade(env, exit_on_failure=False) as cascade: - results = cascade.operations.read(asset_ids).submit_requests(Asset) - -network_errors = [] -cascade_errors = [] +## Chaining and Batching -for failure in results.failed: - if failure.category == FailureCategory.NETWORK: - network_errors.append(failure.identifier) - elif failure.category == FailureCategory.CASCADE: - cascade_errors.append(failure.identifier) - -if network_errors: - print(f"Network failures (retry candidates): {network_errors}") -if cascade_errors: - print(f"Cascade errors (check identifiers): {cascade_errors}") -``` - -`exit_on_failure=False` keeps the process alive to inspect failures -programmatically. - ---- - -## Script logging +All three patterns above run a single operation per script. In practice you can +queue multiple chains — even mixing operation types — before calling +`submit_requests()` once: ```python -from cascade_cms.utils import script_log - -with Cascade(env) as cascade: - script_log.note("Starting bulk keyword update") - - results = ( - cascade.operations - .read(asset_ids) - .edit(tag_asset) - .submit_requests(Asset) - ) - - script_log.note(f"Complete: {len(results.success)} updated") +with CascadeWrapperBase("config.json") as cascade: + path_id = Path(asset_type=AssetTypes.page, path="/index", site_name="default") + del_id = Path(asset_type=AssetTypes.page, path="/old-page", site_name="default") + + # Queue three independent chains (read, delete, and search) + cascade.operations.read(path_id) + cascade.operations.delete(del_id, payload=deleteParameters(doWorkflow=False, destinations=[], unpublish=True)) + cascade.operations.search(SearchInformation(siteName="default", searchTerms="test")) + + # All three chains run concurrently; results are returned in creation order + results = cascade.submit_requests() ``` -`script_log.note()` only works inside the `with` block. +See [Administrative Operations](administrative-ops.md) for the `messages` and `preferences` operations. - +