diff --git a/demos/analytics-using-managedcleanroom/README-API.md b/demos/analytics-using-managedcleanroom/README-API.md index b4dd02a..8bcdf57 100644 --- a/demos/analytics-using-managedcleanroom/README-API.md +++ b/demos/analytics-using-managedcleanroom/README-API.md @@ -1,5 +1,9 @@ # Big Data Analytics — REST API (`az rest` + `Invoke-RestMethod`) +For reusable wrappers covering this guide's ARM and frontend operations, see +[Fast Setup Scripts](scripts/README-SCRIPTS.md) and the +[frontend script reference](scripts/frontend/README.md). + This guide uses **`az rest`** for ARM collaboration operations and **`Invoke-RestMethod`** for frontend service operations, with the same helper scripts for Azure resource provisioning. diff --git a/demos/analytics-using-managedcleanroom/README-CLI.md b/demos/analytics-using-managedcleanroom/README-CLI.md index 9591dc1..e8c496f 100644 --- a/demos/analytics-using-managedcleanroom/README-CLI.md +++ b/demos/analytics-using-managedcleanroom/README-CLI.md @@ -6,6 +6,10 @@ and frontend operations, with helper scripts for Azure resource provisioning. For the REST API variant using `Invoke-RestMethod` and `az rest`, see [README-API.md](README-API.md). +For the same workflow through reusable PowerShell/Bicep helpers, including +IP tags, query `ScaleSku`, service dry runs, cancellation, and SPN participants, +see [Fast Setup Scripts](scripts/README-SCRIPTS.md). + --- ## Scenario diff --git a/demos/analytics-using-managedcleanroom/scripts/05-prepare-data.ps1 b/demos/analytics-using-managedcleanroom/scripts/05-prepare-data.ps1 index d7c3be5..7f0fd3d 100644 --- a/demos/analytics-using-managedcleanroom/scripts/05-prepare-data.ps1 +++ b/demos/analytics-using-managedcleanroom/scripts/05-prepare-data.ps1 @@ -9,7 +9,7 @@ For CPK (Client-Provided Keys): 1. Generate a random AES-256 DEK (Data Encryption Key) 2. Upload data with azcopy --cpk-by-value (Azure Storage encrypts server-side) - 3. Save DEK binary file for Phase B (KEK creation in 08-publish-dataset.ps1) + 3. Save DEK binary file for Phase B (KEK creation in 08-prepare-dataset-keys.ps1) Both modes generate datastore metadata for the dataset publish step. diff --git a/demos/analytics-using-managedcleanroom/scripts/07-grant-access.ps1 b/demos/analytics-using-managedcleanroom/scripts/07-grant-access.ps1 index 56aa619..818ca22 100644 --- a/demos/analytics-using-managedcleanroom/scripts/07-grant-access.ps1 +++ b/demos/analytics-using-managedcleanroom/scripts/07-grant-access.ps1 @@ -10,16 +10,16 @@ Prerequisites: - 04-prepare-resources.ps1 must have been run. - - 06-setup-identity.ps1 must have been run (OIDC issuer configured). + - 06-setup-oidc-storage.ps1 must have been run and its issuer registered. .PARAMETER resourceGroup Azure resource group containing the resources. -.PARAMETER collaborationName - Name of the collaboration resource. +.PARAMETER collaborationId + Frontend UUID of the collaboration. .PARAMETER contractId - Contract identifier used to compute the federation subject (default: analytics). + Contract identifier used to compute the federation subject (default: Analytics). .PARAMETER userId User identifier used to compute the federation subject. @@ -75,7 +75,7 @@ $PSNativeCommandUseErrorActionPreference = $true # Read issuer URL. $issuerUrlFile = Join-Path $outDir $resourceGroup "issuer-url.txt" if (-not (Test-Path $issuerUrlFile)) { - Write-Host "ERROR: '$issuerUrlFile' not found. Run 06-setup-identity.ps1 first." -ForegroundColor Red + Write-Host "ERROR: '$issuerUrlFile' not found. Run 06-setup-oidc-storage.ps1 first." -ForegroundColor Red exit 1 } $issuerUrl = (Get-Content $issuerUrlFile -Raw).Trim() diff --git a/demos/analytics-using-managedcleanroom/scripts/08-prepare-dataset-keys.ps1 b/demos/analytics-using-managedcleanroom/scripts/08-prepare-dataset-keys.ps1 index 9dd2f73..3f33e97 100644 --- a/demos/analytics-using-managedcleanroom/scripts/08-prepare-dataset-keys.ps1 +++ b/demos/analytics-using-managedcleanroom/scripts/08-prepare-dataset-keys.ps1 @@ -37,7 +37,8 @@ .PARAMETER TokenFile Token file for frontend authentication. If omitted, uses CLEANROOM_FRONTEND_TOKEN, - then MANAGEDCLEANROOM_ACCESS_TOKEN, then the current Azure CLI ARM access token. + then MANAGEDCLEANROOM_ACCESS_TOKEN, then the per-persona temp token file, + then the current Azure CLI ARM access token. #> param( [Parameter(Mandatory)] @@ -119,6 +120,10 @@ function Get-SkrPolicy { $token = $env:CLEANROOM_FRONTEND_TOKEN.Trim() } elseif ($env:MANAGEDCLEANROOM_ACCESS_TOKEN) { $token = $env:MANAGEDCLEANROOM_ACCESS_TOKEN.Trim() + } elseif (Test-Path -LiteralPath ( + Join-Path ([IO.Path]::GetTempPath()) "msal-idtoken-$persona.txt") -PathType Leaf) { + $token = (Get-Content -LiteralPath ( + Join-Path ([IO.Path]::GetTempPath()) "msal-idtoken-$persona.txt") -Raw).Trim() } else { try { $token = az account get-access-token --resource "https://management.azure.com/" ` diff --git a/demos/analytics-using-managedcleanroom/scripts/README-SCRIPTS.md b/demos/analytics-using-managedcleanroom/scripts/README-SCRIPTS.md index e034a2e..45ee216 100644 --- a/demos/analytics-using-managedcleanroom/scripts/README-SCRIPTS.md +++ b/demos/analytics-using-managedcleanroom/scripts/README-SCRIPTS.md @@ -33,6 +33,14 @@ Choose one scenario: ## Phase 1 — Owner creates the collaboration (control plane) +> **Destructive clean setup:** If the named collaboration already exists, this +> script deletes it, waits until ARM reports it absent, and creates a fresh one. +> It does not reuse or resume the old collaboration. Its existing datasets, +> queries, governance state, and managed infrastructure are not retained. +> A deletion error or timeout stops setup before creation. +> Use `-DryRun` to preview, or `manage-collaboration.ps1` for actions that should +> keep an existing collaboration. + ```powershell $collabName = "collab1" $deployParams = @{ @@ -50,6 +58,27 @@ $deployParams = @{ This is Bicep (declarative collaboration resource) + the ARM *action* steps (`enableWorkload`, `addCollaborator`). Runtime ~35 min. See [scripts/bicep/](bicep/). +ARM uses `2026-09-30-preview`; frontend calls use `2026-03-01-preview`. +The only currently supported sizing is `Standard_D4ds_v5` with **3 nodes**. +Both the script and Bicep reject larger configurations until support is expanded. +Quota and regional capacity remain prerequisites, not guarantees made by these scripts. + +### Timeouts + +`-TimeoutMinutes` defaults to **60 minutes per lifecycle operation**, not for the +entire script. Delete, create, enable/readiness, and each collaborator addition +have separate budgets. A complete clean setup can therefore take over an hour. +The budget starts before submitting each operation; creation uses +`az deployment group create --no-wait` and polls both deployment and collaboration +state, so it does not hide a blocking creation wait before starting the timer. +Recovery tracks the ARM operation URL, not `provisioningState`, which may remain +`Succeeded` while recovery is still in progress. + +The polling deadline is checked between Azure CLI requests; it is not a hard +process-kill timeout on an individual network request. On timeout, Azure work +may still be running: inspect its status before retrying. Fast setup stops before +creation if deletion fails or times out. Query monitoring has its own independent +60-minute default and does not cancel or resubmit a query on timeout. ### Optional target resource configuration @@ -73,19 +102,29 @@ including the case-sensitive `iPTagConfiguration` spelling, not CLI shorthand such as `i-p-tag-configuration`. The script merges this object with `aksSku` and `nodePoolSize`. If those fields -also appear in the object, the object values take precedence; SKU validation -and the node-count range of 3-10 still apply. With the object omitted, existing +also appear in the object, the object values take precedence; they must still +be `Standard_D4ds_v5` and `3`. With the object omitted, existing behavior is unchanged (`Standard_D4ds_v5`, 3 nodes by default). -`-DryRun` prints the effective configuration without deploying; it still reads -the current Azure CLI account. Remove `-DryRun` to create the collaboration. +`-DryRun` prints the effective configuration without deploying; it reads the +current Azure CLI account unless `-Subscription` is supplied. Remove `-DryRun` +to create the collaboration. The script passes the object through a temporary JSON file, which is removed even if deployment fails. Direct Bicep deployments can also supply the optional `targetResourceConfiguration` object parameter. -These settings apply when creating a new collaboration. An existing -collaboration is skipped, not updated. `-DeleteExistingCollab` deletes and -recreates the collaboration; it is not an in-place configuration change. +These settings apply to the freshly created collaboration, including when +replacing an existing one. The script always performs delete -> wait for absence +-> create -> enable Analytics -> wait for health -> add additional collaborators. +If no collaboration exists, it goes directly to creation. +`-DeleteExistingCollab` remains accepted for compatibility but is already true +by default; explicitly passing `-DeleteExistingCollab:$false` is rejected. +After recreation, repeat Phases 2 onward using the new frontend collaboration UUID. + +For creation-time collaborators, pass `-Collaborators @("")`. +`-AdditionalCollaborators` adds participants after the new collaboration is ready. +To add participants without deleting an existing collaboration, use the +standalone management commands below instead of rerunning fast setup. --- @@ -101,7 +140,9 @@ $PSNativeCommandUseErrorActionPreference = $true $persona = "woodgrove" # or "northwind" $personaRg = "cr-e2e-$persona-rg" $collabName = "collab1" # name chosen by the owner in Phase 1 -$suffix = "-v1" # use a new suffix for a new dataset iteration +$EncryptionMode = "SSE" # SSE or CPK +$iteration = 1 # increase for each new dataset iteration +$suffix = if ($EncryptionMode -eq "CPK") { "-cpk-v$iteration" } else { "-v$iteration" } . .\scripts\frontend\Invoke-Frontend.ps1 $fe = Get-FrontendContext -Persona $persona @@ -126,7 +167,8 @@ already active (including the owner). ```powershell .\scripts\04-prepare-resources.ps1 -resourceGroup $personaRg -persona $persona -location westus .\demos\generate-data.ps1 -persona $persona -.\scripts\05-prepare-data.ps1 -resourceGroup $personaRg -variant sse -persona $persona ` +$variant = $EncryptionMode.ToLowerInvariant() +.\scripts\05-prepare-data.ps1 -resourceGroup $personaRg -variant $variant -persona $persona ` -dataDir ".\generated\datasource\$persona\csv" -datasetSuffix $suffix .\scripts\frontend\05-fetch-jwks.ps1 -Persona $persona -CollaborationId $collabId ` -outDir "generated\$personaRg" @@ -143,7 +185,7 @@ $oidcParams = @{ .\scripts\frontend\05-set-issuer-url.ps1 -Persona $persona -CollaborationId $collabId ` -outDir "generated\$personaRg" .\scripts\07-grant-access.ps1 -resourceGroup $personaRg -collaborationId $collabId ` - -contractId "Analytics" -userId $personaOid -EncryptionMode SSE + -contractId "Analytics" -userId $personaOid -EncryptionMode $EncryptionMode if ($persona -eq "woodgrove") { .\scripts\08-build-dataset-body.ps1 -resourceGroup $personaRg -persona $persona ` @@ -153,9 +195,12 @@ if ($persona -eq "woodgrove") { } ``` -For CPK encryption instead, follow the CPK upload, access, and key-preparation -steps in [README-API.md](../README-API.md). Use a distinct dataset suffix for -each iteration and a separate output directory for each query run. +For CPK, install AzCopy first. The upload helper generates the DEKs and uploads +with Azure Storage CPK encryption; do not manually encrypt the input files. +Access setup grants the workload its Key Vault permissions. +Prepare the KEKs **after publishing** in Phase 4, not before. +Use a distinct dataset suffix for each iteration and a separate output directory +for each query run. See README-API.md Appendix C for the key-release architecture. --- @@ -171,8 +216,18 @@ if ($persona -eq "woodgrove") { .\scripts\frontend\06-publish-dataset.ps1 -Persona $persona -CollaborationId $collabId ` -DocumentId "woodgrove-output-csv$suffix" -BodyFile "generated\publish\woodgrove-output-dataset.json" } + +if ($EncryptionMode -eq "CPK") { + .\scripts\08-prepare-dataset-keys.ps1 -resourceGroup $personaRg -persona $persona ` + -collaborationId $collabId -frontendEndpoint $fe.Frontend +} ``` +Key preparation uses the explicit `-TokenFile` when supplied, then the frontend +environment tokens, then the per-persona temp token file. If you used a custom +token-file location for other steps, pass that same file here. +Publish all datasets before retrieving their SKR policies. + --- ## Phase 5 — Owner builds and publishes the chosen query @@ -238,13 +293,13 @@ $queryInfo = Invoke-Frontend -Context $fe -Path "$collabId/analytics/queries/$qu if ($queryInfo.state -ne "Accepted") { throw "Wait for the required query approvals before running." } # Run + wait for completion + print run history/audit -.\scripts\frontend\run-query.ps1 -Persona woodgrove -CollaborationId $collabId ` - -QueryName $queryName -ScaleSku small +$scaleSku = "small" +$jobId = .\scripts\frontend\run-query.ps1 -Persona woodgrove -CollaborationId $collabId ` + -QueryName $queryName -ScaleSku $scaleSku -TimeoutMinutes 60 -# Copy the job ID printed by the orchestrator; isolate this run's output. -$jobId = "" +# The orchestrator returns the job ID; isolate this run's output. .\scripts\11-download-output.ps1 -resourceGroup $personaRg -datasetSuffix $suffix ` - -JobId $jobId -OutputDir ".\generated\output\SSE-$jobId" + -JobId $jobId -OutputDir ".\generated\output\$EncryptionMode-$jobId" ``` Re-run an accepted query by repeating Phase 7 — no re-setup needed. @@ -253,6 +308,12 @@ Both `run-query.ps1` and `09-run-query.ps1` accept `-ScaleSku small` (default), `medium`, or `large`; this controls the Spark execution profile, not the AKS node-pool SKU. They also accept `-StartDate` / `-EndDate`. Check the quota and profile details in README-API.md Step 09 before selecting a larger profile. +`large` remains preview-only, not production-ready. For date filtering: + +```powershell +$jobId = .\scripts\frontend\run-query.ps1 -Persona woodgrove -CollaborationId $collabId ` + -QueryName $queryName -ScaleSku medium -StartDate "2025-09-01" -EndDate "2025-09-02" +``` A failed or submission-failed run causes the monitor and orchestrator to throw. If submission returns no job ID, check run history before retrying rather than @@ -274,16 +335,109 @@ assuming no run was scheduled. ### Local request previews versus service dry runs -Only the frontend step/orchestrator scripts and -`scripts/bicep/deploy-managed-cleanroom.ps1` support `-DryRun`. Their switch -prints planned requests instead of sending them; the ARM wrappers still read -the current Azure CLI account. Resource provisioning, upload, OIDC storage, +The frontend step/orchestrator scripts, Bicep deployment/management wrappers, +and `common/add-app-collaborator.ps1` support `-DryRun`. Their switch prints +planned requests instead of sending them; ARM wrappers read the current Azure +CLI account unless `-Subscription` is supplied. Resource provisioning, upload, OIDC storage, access, body-building, key-preparation, download and Grafana helpers do **not** support this switch. Body builders write local files even though they do not call the service. A local preview does not validate authentication, dataset contents, approval state or effective `skuSettings`; the run helpers return only a `` -placeholder. For an actual service-side dry run, use the -`dryRun: true` request body in README-API.md Step 09; that sends a frontend -request but does not execute the Spark query. +placeholder. For an actual service-side dry run, both query runners accept `-ServiceDryRun`: + +```powershell +$preview = .\scripts\frontend\run-query.ps1 -Persona woodgrove -CollaborationId $collabId ` + -QueryName $queryName -ScaleSku medium -ServiceDryRun +$preview.skuSettings | ConvertTo-Json -Depth 10 +``` + +This sends `dryRun: true` but does not publish, execute, monitor, or fetch results. +It cannot be combined with `-DryRun` or the orchestrator's `-BodyFile`. + +## Inspect, diagnose, cancel, and change consent + +```powershell +$readArgs = @{ Persona = $persona; CollaborationId = $collabId } +.\scripts\frontend\get-frontend-data.ps1 @readArgs -Resource Collaborators +.\scripts\frontend\get-frontend-data.ps1 @readArgs -Resource Datasets +.\scripts\frontend\get-frontend-data.ps1 @readArgs -Resource Dataset ` + -DocumentId "$persona-input-csv$suffix" +.\scripts\frontend\get-frontend-data.ps1 @readArgs -Resource Queries +.\scripts\frontend\get-frontend-data.ps1 @readArgs -Resource Query -QueryName $queryName + +# One detailed snapshot, even for a stuck/failed run: +$result = .\scripts\frontend\10-monitor-query.ps1 @readArgs -JobId $jobId -Once +$result.events | Format-Table type, reason, message, count -Wrap +$result.status.applicationState | ConvertTo-Json -Depth 5 + +# Cancel only a persistent failure/unwanted run, not a single early FailedMount. +.\scripts\frontend\09-cancel-query.ps1 @readArgs -QueryName $queryName -JobId $jobId + +# Enable or disable consent without republishing. +.\scripts\frontend\06-set-consent.ps1 @readArgs ` + -DocumentId "$persona-input-csv$suffix" -ConsentAction disable +``` + +The reader also supports `Collaborations` (`-ActiveOnly`), `Invitations` +(`-PendingOnly`), `OidcKeys`, `Run`, `RunHistory`, and `AuditEvents`. +Polling prints new/updated events, stops on failure/cancellation, and times out +after 60 minutes by default. A timeout **does not cancel or resubmit** the run. +The quota/capacity/network troubleshooting tables in the main guides still apply; +a generic executor failure alone does not establish a capacity problem. + +## Manage an existing collaboration and retrieve diagnostics + +These are ARM operations, using the selected Azure subscription or an explicit +`-Subscription`. Mutations wait by default; `-NoWait` submits only. + +```powershell +$armArgs = @{ ResourceGroup = $collabRg; CollaborationName = $collabName } +$collab = .\scripts\bicep\manage-collaboration.ps1 @armArgs -Action Show +$collab.properties.health | ConvertTo-Json -Depth 10 +.\scripts\bicep\manage-collaboration.ps1 @armArgs -Action EnableWorkload +.\scripts\bicep\manage-collaboration.ps1 @armArgs -Action AddCollaborator ` + -Collaborators @("") + +.\scripts\frontend\12-get-readonly-kubeconfig.ps1 @armArgs -OutFile ".\readonly.kubeconfig" +.\scripts\12-open-grafana-dashboard.ps1 -KubeConfigPath ".\readonly.kubeconfig" +``` + +Use recovery only as a last resort; deletion permanently removes the collaboration +and its associated resources. Neither is an automatic response to a query failure: + +```powershell +.\scripts\bicep\manage-collaboration.ps1 @armArgs -Action Recover -ForceRecover +# Delete only (does NOT recreate): +.\scripts\bicep\manage-collaboration.ps1 @armArgs -Action Delete +``` + +## SPN participants + +Acquire the SPN token with `common/get-sp-token-sni.ps1` as described in the main +guides and extract its JWT `oid` for the FIC subject. ARM operations use the +current Azure CLI login; setting a frontend token does not change that login. +For collaborator registration, use all three identity fields: + +```powershell +$app = @{ + userIdentifier = "" + objectId = "" + tenantId = "" +} +.\scripts\bicep\manage-collaboration.ps1 @armArgs -Action AddCollaborator -Collaborators @($app) +# The same object is accepted by deploy-managed-cleanroom.ps1: +# -Collaborators @($app) at creation, or -AdditionalCollaborators @($app). +``` + +`common/add-app-collaborator.ps1` also accepts `-AppClientId`, `-ObjectId` and +`-TenantId`. SPNs auto-activate and need no invitation acceptance. + +## Offline validation + +These target-configuration tests mock Azure CLI; they do not deploy or run queries: + +```powershell +.\scripts\bicep\tests\test-target-resource-configuration.ps1 +``` diff --git a/demos/analytics-using-managedcleanroom/scripts/bicep/deploy-managed-cleanroom.ps1 b/demos/analytics-using-managedcleanroom/scripts/bicep/deploy-managed-cleanroom.ps1 index eed66ac..cb6ef85 100644 --- a/demos/analytics-using-managedcleanroom/scripts/bicep/deploy-managed-cleanroom.ps1 +++ b/demos/analytics-using-managedcleanroom/scripts/bicep/deploy-managed-cleanroom.ps1 @@ -6,6 +6,9 @@ .DESCRIPTION Run by: Collaboration owner (Woodgrove). + Existing collaborations are deleted first. Setup waits until ARM reports + the old resource absent before creating a fresh one; deletion errors stop setup. + Bicep is declarative and can only create the collaboration *resource* (control-plane PUT). The managed clean-room flow also requires imperative ARM *action* POSTs which have no declarative Bicep equivalent: @@ -36,17 +39,28 @@ iPTagConfiguration. aksSku and nodePoolSize in this object override the corresponding script parameters and retain their validation constraints. +.PARAMETER collaborators + Creation-time collaborators: emails or SPN objects with userIdentifier, + objectId and tenantId. + .PARAMETER additionalCollaborators - Optional list of extra collaborator identifiers to invite via addCollaborator. + Optional extra emails or SPN identity objects to invite via addCollaborator. .PARAMETER deleteExistingCollab - If a collaboration with the same name exists: when set, delete it (and wait - for its resources to vanish) before provisioning a new one; when not set, - skip provisioning and leave the existing collaboration as-is. + Defaults to true. Retained for compatibility; false is rejected because fast + setup always recreates. Use manage-collaboration.ps1 for existing-resource actions. .PARAMETER apiVersion Microsoft.CleanRoom ARM API version (default: 2026-09-30-preview). +.PARAMETER subscription + Optional subscription ID; defaults to the current Azure CLI account. + +.PARAMETER timeoutMinutes + Polling budget per lifecycle operation (default: 60 minutes), starting before + submission. Creation is submitted asynchronously and its deployment is polled. + This is not a whole-script limit or a hard timeout on each Azure CLI request. + .EXAMPLE ./deploy-managed-cleanroom.ps1 ` -resourceGroup cr-collab-rg -collaborationName collab1 ` @@ -68,18 +82,25 @@ param( "westus", "westus2")] [string]$resourceLocation = "westus", - [ValidateSet("Standard_D4ds_v5", "Standard_D8ds_v5", "Standard_D16ds_v5", "Standard_D32ds_v5")] + [ValidateSet("Standard_D4ds_v5")] [string]$aksSku = "Standard_D4ds_v5", - [ValidateRange(3, 10)] + [ValidateRange(3, 3)] [int]$nodePoolSize = 3, - [string[]]$additionalCollaborators = @(), + [object[]]$collaborators = @(), - [switch]$deleteExistingCollab, + [object[]]$additionalCollaborators = @(), + + [switch]$deleteExistingCollab = $true, [string]$apiVersion = "2026-09-30-preview", + [string]$subscription, + + [ValidateRange(1, 1440)] + [int]$timeoutMinutes = 60, + [switch]$dryRun, [ValidateNotNull()] @@ -87,8 +108,14 @@ param( ) $ErrorActionPreference = "Stop" -$armEndpoint = "https://management.azure.com" +. "$PSScriptRoot/../common/Invoke-Collaboration.ps1" +if (-not $deleteExistingCollab) { + throw "Fast setup always deletes and recreates existing collaborations. Use manage-collaboration.ps1 for existing-resource actions." +} +if ($apiVersion -ne "2026-09-30-preview") { + throw "This Bicep template uses 2026-09-30-preview; use the same API version for setup." +} if ($targetResourceConfiguration.ContainsKey("aksSku")) { $aksSku = $targetResourceConfiguration.aksSku } @@ -101,6 +128,13 @@ $effectiveTargetConfiguration = @{ } foreach ($entry in $targetResourceConfiguration.GetEnumerator()) { if ($entry.Key -notin @("aksSku", "nodePoolSize")) { + if ($entry.Key -cne "iPTagConfiguration") { + throw "Unknown target resource property '$($entry.Key)'. Use ARM spelling iPTagConfiguration." + } + if ([string]::IsNullOrWhiteSpace($entry.Value.type) -or + [string]::IsNullOrWhiteSpace($entry.Value.value)) { + throw "iPTagConfiguration requires both type and value." + } $effectiveTargetConfiguration[$entry.Key] = $entry.Value } } @@ -109,39 +143,38 @@ $targetConfigurationJson = $effectiveTargetConfiguration | ConvertTo-Json -Depth # Analytics is currently the only supported workload. $workloadType = "Analytics" -$subscription = (az account show -o json | ConvertFrom-Json).id -$collabArmUrl = "$armEndpoint/subscriptions/$subscription/resourceGroups/$resourceGroup/providers/Microsoft.CleanRoom/Collaborations/$collaborationName" - -function Get-Collab { - az rest --method GET --url "${collabArmUrl}?api-version=$apiVersion" --resource $armEndpoint -o json 2>$null | ConvertFrom-Json +$creationIdentities = @($collaborators | ForEach-Object { ConvertTo-Collaborator -Identity $_ }) +$additionalIdentities = @($additionalCollaborators | ForEach-Object { + ConvertTo-Collaborator -Identity $_ +}) +$context = Get-CollaborationContext -ResourceGroup $resourceGroup ` + -CollaborationName $collaborationName -Subscription $subscription ` + -ApiVersion $apiVersion -DryRun:$dryRun +$actionArgs = @{ + ResourceGroup = $resourceGroup + CollaborationName = $collaborationName + Subscription = $context.Subscription + ApiVersion = $apiVersion + TimeoutMinutes = $timeoutMinutes + DryRun = $dryRun } -# Polls a condition until it returns truthy or the timeout elapses. -function Wait-Until { - param( - [Parameter(Mandatory)][scriptblock]$Condition, - [Parameter(Mandatory)][string]$Description, - [int]$TimeoutMinutes = 20, - [int]$IntervalSeconds = 30 - ) - $deadline = (Get-Date).AddMinutes($TimeoutMinutes) - while (-not (& $Condition)) { - if ((Get-Date) -gt $deadline) { throw "Timed out after $TimeoutMinutes min waiting for: $Description" } - Start-Sleep -Seconds $IntervalSeconds - } +function Get-Collab { + Invoke-Collaboration -Context $context -AllowNotFound } if ($dryRun) { Write-Host "[DRY-RUN] Would ensure resource group '$resourceGroup' ($location) and register providers." - if ($deleteExistingCollab) { - Write-Host "[DRY-RUN] Would delete an existing '$collaborationName' (if present) and wait for it to vanish." - } - Write-Host "[DRY-RUN] Would deploy Bicep: $PSScriptRoot/managed-cleanroom.bicep (owner from caller token)" + Write-Host "[DRY-RUN] Would delete an existing '$collaborationName' (if present) and wait for it to vanish." + & "$PSScriptRoot/manage-collaboration.ps1" @actionArgs -Action Delete + Write-Host "[DRY-RUN] Would then create a fresh collaboration via Bicep." Write-Host "[DRY-RUN] collaborationName=$collaborationName location=$location resourceLocation=$resourceLocation aksSku=$aksSku nodePoolSize=$nodePoolSize" Write-Host "[DRY-RUN] targetResourceConfiguration=$targetConfigurationJson" - Write-Host "[DRY-RUN] Would POST $collabArmUrl/enableWorkload body {workloadType=$workloadType}" - foreach ($collaborator in $additionalCollaborators) { - Write-Host "[DRY-RUN] Would POST $collabArmUrl/addCollaborator body {collaborator.userIdentifier=$collaborator}" + Write-Host "[DRY-RUN] collaborators=$($creationIdentities | ConvertTo-Json -Depth 10 -Compress -AsArray)" + & "$PSScriptRoot/manage-collaboration.ps1" @actionArgs -Action EnableWorkload + if ($additionalIdentities.Count) { + & "$PSScriptRoot/manage-collaboration.ps1" @actionArgs -Action AddCollaborator ` + -Collaborators $additionalIdentities } return } @@ -150,116 +183,70 @@ if ($dryRun) { # 0. Ensure resource group + providers # --------------------------------------------------------------------------- Write-Host "Ensuring resource group '$resourceGroup' ($location)..." -az group create --name $resourceGroup --location $location -o none +Invoke-CleanroomAz -Arguments @("group", "create", "--name", $resourceGroup, + "--location", $location, "--subscription", $context.Subscription, "-o", "none") | Out-Null Write-Host "Registering resource providers (idempotent)..." -az provider register --namespace Microsoft.CleanRoom -o none -az provider register --namespace Microsoft.ContainerService -o none +foreach ($provider in @("Microsoft.CleanRoom", "Microsoft.ContainerService")) { + Invoke-CleanroomAz -Arguments @("provider", "register", "--namespace", $provider, + "--subscription", $context.Subscription, "--wait", "-o", "none") | Out-Null +} # --------------------------------------------------------------------------- # 0.5 Handle an existing collaboration of the same name # --------------------------------------------------------------------------- $existing = Get-Collab -if ($existing -and $existing.id) { - if ($deleteExistingCollab) { - Write-Host "Deleting existing collaboration '$collaborationName'..." - az rest --method DELETE --url "${collabArmUrl}?api-version=$apiVersion" --resource $armEndpoint -o none - Wait-Until -Description "existing '$collaborationName' to be deleted" -TimeoutMinutes 30 -Condition { -not (Get-Collab) } - Write-Host "Existing collaboration deleted." - } - else { - Write-Host "Collaboration '$collaborationName' already exists (provisioningState=$($existing.properties.provisioningState)); skipping provisioning." - Write-Host "Pass -DeleteExistingCollab to delete and recreate it." - return - } +if ($existing) { + Write-Warning "Deleting existing collaboration '$collaborationName' for a clean setup." + & "$PSScriptRoot/manage-collaboration.ps1" @actionArgs -Action Delete + Write-Host "Existing collaboration deleted." } # --------------------------------------------------------------------------- # 1. Deploy the collaboration (declarative -- Bicep) # --------------------------------------------------------------------------- -# The owner is added automatically from the caller's ARM token, so no -# collaborators are passed here. az deployment group create blocks until the -# deployment reaches a terminal state, so no separate provisioning poll is needed. +# The owner is added automatically from the caller's ARM token. Write-Host "Deploying collaboration '$collaborationName' via Bicep (~25 min)..." +$creationDeadline = (Get-Date).AddMinutes($timeoutMinutes) $targetConfigurationFile = [System.IO.Path]::GetTempFileName() try { - [System.IO.File]::WriteAllText($targetConfigurationFile, $targetConfigurationJson) - az deployment group create ` - --resource-group $resourceGroup ` - --name "deploy-$collaborationName" ` - --template-file "$PSScriptRoot/managed-cleanroom.bicep" ` - --parameters ` - collaborationName=$collaborationName ` - location=$location ` - resourceLocation=$resourceLocation ` - aksSku=$aksSku ` - nodePoolSize=$nodePoolSize ` - "targetResourceConfiguration=@$targetConfigurationFile" ` - -o none - if ($LASTEXITCODE -ne 0) { - throw "Bicep deployment failed (az deployment group create exit code $LASTEXITCODE). See the error above." - } + $parameters = @{ + targetResourceConfiguration = @{ value = $effectiveTargetConfiguration } + collaborators = @{ value = $creationIdentities } + } | ConvertTo-Json -Depth 20 + [System.IO.File]::WriteAllText($targetConfigurationFile, $parameters) + Invoke-CleanroomAz -Arguments @("deployment", "group", "create", + "--resource-group", $resourceGroup, "--subscription", $context.Subscription, + "--name", "deploy-$collaborationName", + "--template-file", "$PSScriptRoot/managed-cleanroom.bicep", + "--parameters", "collaborationName=$collaborationName", "location=$location", + "resourceLocation=$resourceLocation", "aksSku=$aksSku", "nodePoolSize=$nodePoolSize", + "@$targetConfigurationFile", "--no-wait", "-o", "none") | Out-Null } finally { - Remove-Item -LiteralPath $targetConfigurationFile -ErrorAction SilentlyContinue + Remove-Item -LiteralPath $targetConfigurationFile -Force } -$collab = Get-Collab -if (-not $collab -or -not $collab.id) { - throw "Collaboration '$collaborationName' was not found after deployment. Aborting." -} +$collab = Wait-Collaboration -Context $context -Description "collaboration provisioning" ` + -TimeoutMinutes $timeoutMinutes -Deadline $creationDeadline ` + -DeploymentName "deploy-$collaborationName" -AllowNotFound ` + -Condition { param($c) $c.properties.provisioningState -eq "Succeeded" } Write-Host "Collaboration resource ready: $($collab.id)" # --------------------------------------------------------------------------- # 2. Enable the workload (ARM *action* -- no Bicep equivalent) # --------------------------------------------------------------------------- Write-Host "Enabling '$workloadType' workload (~7 min)..." -$bodyFile = Join-Path $PSScriptRoot "body.json" -[System.IO.File]::WriteAllText($bodyFile, (@{ workloadType = $workloadType } | ConvertTo-Json)) -az rest --method POST ` - --url "$collabArmUrl/enableWorkload?api-version=$apiVersion" ` - --resource $armEndpoint ` - --headers "Content-Type=application/json" ` - --body "@$bodyFile" -o none - -# az rest does not surface the Azure-AsyncOperation header, so poll the resource -# for the workload endpoint and health, each guarded by a timeout. -Wait-Until -Description "'$workloadType' workload endpoint" -TimeoutMinutes 15 -Condition { - $c = Get-Collab - if ($c.properties.provisioningState -eq "Failed") { throw "Workload enablement failed." } - $wl = $c.properties.workloads | Where-Object { $_.workloadType -eq $workloadType } | Select-Object -First 1 - [bool]$wl.endpoint -} -Wait-Until -Description "collaboration healthState=Ok" -TimeoutMinutes 15 -Condition { - $c = Get-Collab - if ($c.properties.health.healthIssues) { - $c.properties.health.healthIssues | ForEach-Object { Write-Host " Issue: $($_ | ConvertTo-Json -Compress)" } - } - $c.properties.health.healthState -eq "Ok" -} +& "$PSScriptRoot/manage-collaboration.ps1" @actionArgs -Action EnableWorkload | Out-Null # --------------------------------------------------------------------------- # 3. Add additional collaborators (ARM *action* -- no Bicep equivalent) # --------------------------------------------------------------------------- -foreach ($collaborator in $additionalCollaborators) { - Write-Host "Adding collaborator '$collaborator'..." - [System.IO.File]::WriteAllText($bodyFile, (@{ collaborator = @{ userIdentifier = $collaborator } } | ConvertTo-Json)) - az rest --method POST ` - --url "$collabArmUrl/addCollaborator?api-version=$apiVersion" ` - --resource $armEndpoint ` - --headers "Content-Type=application/json" ` - --body "@$bodyFile" -o none - - Wait-Until -Description "collaborator '$collaborator' to be added" -TimeoutMinutes 10 -Condition { - (Get-Collab).properties.collaborators.userIdentifier -contains $collaborator - } +if ($additionalIdentities.Count) { + & "$PSScriptRoot/manage-collaboration.ps1" @actionArgs -Action AddCollaborator ` + -Collaborators $additionalIdentities } -Remove-Item $bodyFile -ErrorAction SilentlyContinue - -Write-Host "" -Write-Host "Done. Collaboration '$collaborationName' is provisioned and healthy." - Write-Host "" Write-Host "Done. Collaboration '$collaborationName' is provisioned and healthy." Write-Host "Next: follow README-API.md Steps 03-12 (accept invitation, OIDC," diff --git a/demos/analytics-using-managedcleanroom/scripts/bicep/manage-collaboration.ps1 b/demos/analytics-using-managedcleanroom/scripts/bicep/manage-collaboration.ps1 new file mode 100644 index 0000000..cc8a187 --- /dev/null +++ b/demos/analytics-using-managedcleanroom/scripts/bicep/manage-collaboration.ps1 @@ -0,0 +1,110 @@ +<# +.SYNOPSIS + Shows, enables, adds collaborators to, recovers, or deletes an existing collaboration. +.DESCRIPTION + Uses ARM 2026-09-30-preview. Mutations wait for completion unless -NoWait is + supplied. Delete never recreates the collaboration. Recovery is a last resort; + -ForceRecover sends forceRecover=true. -DryRun only previews requests. +.PARAMETER Collaborators + Emails or objects with userIdentifier, objectId and tenantId for SPNs. +.PARAMETER TimeoutMinutes + Polling budget per operation (default: 60 minutes), starting before submission. + Each added collaborator has its own budget. Timeout does not cancel Azure work. +#> +param( + [Parameter(Mandatory)][string]$ResourceGroup, + [Parameter(Mandatory)][string]$CollaborationName, + [Parameter(Mandatory)] + [ValidateSet("Show", "EnableWorkload", "AddCollaborator", "Recover", "Delete")] + [string]$Action, + [object[]]$Collaborators = @(), + [string]$Subscription, + [string]$ApiVersion = "2026-09-30-preview", + [ValidateRange(1, 1440)][int]$TimeoutMinutes = 60, + [switch]$ForceRecover, + [switch]$NoWait, + [switch]$DryRun +) + +$ErrorActionPreference = "Stop" +. "$PSScriptRoot/../common/Invoke-Collaboration.ps1" +if ($ForceRecover -and $Action -ne "Recover") { + throw "-ForceRecover applies only to -Action Recover." +} +if ($Collaborators.Count -and $Action -ne "AddCollaborator") { + throw "-Collaborators applies only to -Action AddCollaborator." +} +if ($Action -eq "AddCollaborator" -and -not $Collaborators.Count) { + throw "-Collaborators is required for AddCollaborator." +} +$identities = @($Collaborators | ForEach-Object { ConvertTo-Collaborator -Identity $_ }) +$context = Get-CollaborationContext -ResourceGroup $ResourceGroup ` + -CollaborationName $CollaborationName -Subscription $Subscription ` + -ApiVersion $ApiVersion -DryRun:$DryRun + +switch ($Action) { + "Show" { return Invoke-Collaboration -Context $context } + "Delete" { + $deadline = (Get-Date).AddMinutes($TimeoutMinutes) + Invoke-Collaboration -Context $context -Method DELETE | Out-Null + if (-not $DryRun -and -not $NoWait) { + Wait-Collaboration -Context $context -Description "collaboration deletion" ` + -TimeoutMinutes $TimeoutMinutes -Deadline $deadline -AllowNotFound ` + -Condition { param($c) $null -eq $c } | Out-Null + } + } + "Recover" { + # Resource provisioningState can stay Succeeded throughout recovery. + Invoke-CollaborationOperation -Context $context -Action recover ` + -Body @{ forceRecover = [bool]$ForceRecover } ` + -TimeoutMinutes $TimeoutMinutes -NoWait:$NoWait + if (-not $DryRun -and -not $NoWait) { + Invoke-Collaboration -Context $context + } + } + "EnableWorkload" { + $deadline = (Get-Date).AddMinutes($TimeoutMinutes) + $existing = if (-not $DryRun) { Invoke-Collaboration -Context $context } + $workload = $existing.properties.workloads | + Where-Object { $_.workloadType -eq "Analytics" } | Select-Object -First 1 + if (-not $workload.endpoint) { + Invoke-Collaboration -Context $context -Method POST -Action enableWorkload ` + -Body @{ workloadType = "Analytics" } | Out-Null + } + if (-not $DryRun -and -not $NoWait) { + Wait-Collaboration -Context $context -Description "Analytics endpoint and healthy collaboration" ` + -TimeoutMinutes $TimeoutMinutes -Deadline $deadline -Condition { + param($c) + $analytics = $c.properties.workloads | + Where-Object { $_.workloadType -eq "Analytics" } | Select-Object -First 1 + $analytics.endpoint -and $c.properties.health.healthState -eq "Ok" + } + } + } + "AddCollaborator" { + foreach ($identity in $identities) { + $deadline = (Get-Date).AddMinutes($TimeoutMinutes) + $existing = if (-not $DryRun) { Invoke-Collaboration -Context $context } + $matches = @($existing.properties.collaborators | Where-Object { + $_.userIdentifier -eq $identity.userIdentifier -or + ($identity.objectId -and $_.objectId -eq $identity.objectId -and + $_.tenantId -eq $identity.tenantId) + }) + if (-not $matches.Count) { + Invoke-Collaboration -Context $context -Method POST -Action addCollaborator ` + -Body @{ collaborator = $identity } | Out-Null + } + if (-not $DryRun -and -not $NoWait) { + Wait-Collaboration -Context $context -Description "collaborator $($identity.userIdentifier)" ` + -TimeoutMinutes $TimeoutMinutes -Deadline $deadline -Condition { + param($c) + @($c.properties.collaborators | Where-Object { + $_.userIdentifier -eq $identity.userIdentifier -or + ($identity.objectId -and $_.objectId -eq $identity.objectId -and + $_.tenantId -eq $identity.tenantId) + }).Count -gt 0 + } | Out-Null + } + } + } +} diff --git a/demos/analytics-using-managedcleanroom/scripts/bicep/managed-cleanroom.bicep b/demos/analytics-using-managedcleanroom/scripts/bicep/managed-cleanroom.bicep index f75d8cc..27fb120 100644 --- a/demos/analytics-using-managedcleanroom/scripts/bicep/managed-cleanroom.bicep +++ b/demos/analytics-using-managedcleanroom/scripts/bicep/managed-cleanroom.bicep @@ -61,19 +61,28 @@ param resourceLocation string = 'westus' @description('Virtual machine SKU for the AKS node pool.') @allowed([ 'Standard_D4ds_v5' - 'Standard_D8ds_v5' - 'Standard_D16ds_v5' - 'Standard_D32ds_v5' ]) param aksSku string = 'Standard_D4ds_v5' @description('Number of nodes in the AKS node pool.') @minValue(3) -@maxValue(10) +@maxValue(3) param nodePoolSize int = 3 +@sealed() +type TargetResourceSettings = { + aksSku: 'Standard_D4ds_v5'? + nodePoolSize: 3? + iPTagConfiguration: { + @minLength(1) + type: string + @minLength(1) + value: string + }? +} + @description('Optional target resource settings using ARM property names (for example iPTagConfiguration). Values override aksSku and nodePoolSize when supplied in this object.') -param targetResourceConfiguration object = {} +param targetResourceConfiguration TargetResourceSettings = {} @description('Optional additional collaborators added at creation time. Each entry is { userIdentifier: "" }. The owner is derived from the caller token automatically. Add further collaborators later via the addCollaborator action (see deploy script).') param collaborators array = [] diff --git a/demos/analytics-using-managedcleanroom/scripts/bicep/tests/test-target-resource-configuration.ps1 b/demos/analytics-using-managedcleanroom/scripts/bicep/tests/test-target-resource-configuration.ps1 index afe4366..8b04580 100644 --- a/demos/analytics-using-managedcleanroom/scripts/bicep/tests/test-target-resource-configuration.ps1 +++ b/demos/analytics-using-managedcleanroom/scripts/bicep/tests/test-target-resource-configuration.ps1 @@ -17,10 +17,15 @@ function Invoke-Scenario { Configuration = $null ParameterFile = $null Deployed = $false + Deleted = $false Error = $null Output = @() + Now = [datetime]::new(2026, 10, 23) } + function Get-Date { return $state.Now } + function Start-Sleep { param([double]$Seconds); $state.Now = $state.Now.AddSeconds($Seconds) } + function az { $command = $args -join " " $state.Calls.Add($command) @@ -30,31 +35,60 @@ function Invoke-Scenario { "group create *" { return } "provider register *" { return } "deployment group create *" { - $parameter = @($args | Where-Object { $_ -like "targetResourceConfiguration=@*" }) + Assert-Equal ($args -contains "--no-wait") $true "Creation is submitted without blocking" + $parameter = @($args | Where-Object { $_ -like "@*" }) Assert-Equal $parameter.Count 1 "Expected one JSON object parameter" - $state.ParameterFile = $parameter[0].Substring("targetResourceConfiguration=@".Length) + $state.ParameterFile = $parameter[0].Substring(1) Assert-Equal (Test-Path -LiteralPath $state.ParameterFile) $true "Parameter file exists during deployment" - $state.Configuration = Get-Content -LiteralPath $state.ParameterFile -Raw | ConvertFrom-Json + $state.Configuration = (Get-Content -LiteralPath $state.ParameterFile -Raw | + ConvertFrom-Json).targetResourceConfiguration.value if ($FailureMode -eq "ExitCode") { $global:LASTEXITCODE = 1; return } if ($FailureMode -eq "Throw") { throw "Simulated deployment exception" } $state.Deployed = $true + if ($FailureMode -eq "SlowSubmission") { + $state.Now = $state.Now.AddMinutes(1) + } + return + } + "deployment group show *" { + if ($FailureMode -eq "DeploymentFailed") { + '{"properties":{"provisioningState":"Failed","error":{"code":"OfflineFailure","message":"offline deployment failed"}}}' + } elseif ($FailureMode -in @("DeploymentTimeout", "SlowSubmission")) { + '{"properties":{"provisioningState":"Running"}}' + } else { + '{"properties":{"provisioningState":"Succeeded"}}' + } return } "rest --method GET *" { - if ($Existing -or $state.Deployed) { - '{"id":"/offline/collaboration","properties":{"workloads":[{"workloadType":"Analytics","endpoint":"https://example.test"}],"health":{"healthState":"Ok"}}}' + if ($FailureMode -eq "AuthorizationFailed") { + $global:LASTEXITCODE = 1 + 'ERROR: Forbidden({"error":{"code":"AuthorizationFailed","message":"offline"}})' + return + } + if (($Existing -and -not $state.Deleted) -or $state.Deployed) { + '{"id":"/offline/collaboration","properties":{"provisioningState":"Succeeded","workloads":[{"workloadType":"Analytics","endpoint":"https://example.test"}],"health":{"healthState":"Ok"}}}' } else { - '{}' + $global:LASTEXITCODE = 1 + if ($FailureMode -in @("ResourceNotFound", "ResourceGroupNotFound")) { + $body = [ordered]@{ error = [ordered]@{ + code = $FailureMode; message = "offline" + } } | ConvertTo-Json -Compress + "ERROR: Not Found($body)" + } else { + '(ResourceNotFound) offline collaboration does not exist' + } } return } + "rest --method DELETE *" { $state.Deleted = $true; return } "rest --method POST */enableWorkload?*" { return } default { throw "Unexpected Azure CLI call: $command" } } } try { - $state.Output = @(& (Join-Path $testDirectory "deploy-managed-cleanroom.ps1") ` + $state.Output = @(& $deploymentScript ` -resourceGroup offline-rg -collaborationName offline-collab @Parameters 6>&1) } catch { $state.Error = $_ @@ -64,14 +98,13 @@ function Invoke-Scenario { try { New-Item -ItemType Directory -Path $testDirectory | Out-Null - Copy-Item -LiteralPath $deploymentScript -Destination $testDirectory $cases = @( @{ Name = "defaults"; Parameters = @{}; Sku = "Standard_D4ds_v5"; Nodes = 3 }, - @{ Name = "legacy sizing"; Parameters = @{ aksSku = "Standard_D16ds_v5"; nodePoolSize = 6 }; Sku = "Standard_D16ds_v5"; Nodes = 6 }, + @{ Name = "explicit supported sizing"; Parameters = @{ aksSku = "Standard_D4ds_v5"; nodePoolSize = 3 }; Sku = "Standard_D4ds_v5"; Nodes = 3 }, @{ Name = "empty object"; Parameters = @{ targetResourceConfiguration = @{} }; Sku = "Standard_D4ds_v5"; Nodes = 3 }, - @{ Name = "IP tags with legacy sizing"; Parameters = @{ aksSku = "Standard_D8ds_v5"; nodePoolSize = 4; targetResourceConfiguration = @{ iPTagConfiguration = @{ type = "FirstPartyUsage"; value = "/AzureCleanRoomsNonProd" } } }; Sku = "Standard_D8ds_v5"; Nodes = 4 }, - @{ Name = "object overrides legacy sizing"; Parameters = @{ aksSku = "Standard_D4ds_v5"; nodePoolSize = 3; targetResourceConfiguration = @{ aksSku = "Standard_D32ds_v5"; nodePoolSize = 10 } }; Sku = "Standard_D32ds_v5"; Nodes = 10 }, - @{ Name = "partial object retains defaults"; Parameters = @{ targetResourceConfiguration = @{ nodePoolSize = 5 } }; Sku = "Standard_D4ds_v5"; Nodes = 5 } + @{ Name = "IP tags with supported sizing"; Parameters = @{ aksSku = "Standard_D4ds_v5"; nodePoolSize = 3; targetResourceConfiguration = @{ iPTagConfiguration = @{ type = "FirstPartyUsage"; value = "/AzureCleanRoomsNonProd" } } }; Sku = "Standard_D4ds_v5"; Nodes = 3 }, + @{ Name = "object sizing"; Parameters = @{ targetResourceConfiguration = @{ aksSku = "Standard_D4ds_v5"; nodePoolSize = 3 } }; Sku = "Standard_D4ds_v5"; Nodes = 3 }, + @{ Name = "partial object retains defaults"; Parameters = @{ targetResourceConfiguration = @{ nodePoolSize = 3 } }; Sku = "Standard_D4ds_v5"; Nodes = 3 } ) foreach ($case in $cases) { $parameters = $case.Parameters.Clone() @@ -93,10 +126,14 @@ try { foreach ($invalid in @( @{ aksSku = "UnsupportedSku" }, + @{ aksSku = "Standard_D8ds_v5" }, @{ aksSku = $null }, @{ nodePoolSize = 2 }, + @{ nodePoolSize = 4 }, @{ nodePoolSize = 11 }, - @{ nodePoolSize = $null } + @{ nodePoolSize = $null }, + @{ ipTagConfiguration = @{ type = "FirstPartyUsage"; value = "/AzureCleanRoomsProd" } }, + @{ iPTagConfiguration = @{ type = "FirstPartyUsage" } } )) { $state = Invoke-Scenario -Parameters @{ targetResourceConfiguration = $invalid; dryRun = $true } if (-not $state.Error) { throw "Invalid configuration was accepted: $($invalid | ConvertTo-Json -Compress)" } @@ -105,7 +142,7 @@ try { } $tagValue = '/tag with spaces, "quotes" and \slashes' - $configuration = @{ aksSku = "Standard_D8ds_v5"; nodePoolSize = 5; iPTagConfiguration = @{ type = "FirstPartyUsage"; value = $tagValue } } + $configuration = @{ aksSku = "Standard_D4ds_v5"; nodePoolSize = 3; iPTagConfiguration = @{ type = "FirstPartyUsage"; value = $tagValue } } foreach ($failureMode in @("", "ExitCode", "Throw")) { $state = Invoke-Scenario -Parameters @{ targetResourceConfiguration = $configuration } -FailureMode $failureMode if ($failureMode -eq "") { @@ -113,11 +150,11 @@ try { Assert-Equal $state.Deployed $true "Successful deployment" } else { if (-not $state.Error) { throw "Deployment failure was not propagated: $failureMode" } - $expectedMessage = if ($failureMode -eq "ExitCode") { "Bicep deployment failed*" } else { "Simulated deployment exception*" } + $expectedMessage = if ($failureMode -eq "ExitCode") { "Azure CLI failed*" } else { "Simulated deployment exception*" } if ($state.Error.Exception.Message -notlike $expectedMessage) { throw $state.Error } } - Assert-Equal $state.Configuration.aksSku "Standard_D8ds_v5" "SKU forwarded in JSON file" - Assert-Equal $state.Configuration.nodePoolSize 5 "Node count forwarded in JSON file" + Assert-Equal $state.Configuration.aksSku "Standard_D4ds_v5" "SKU forwarded in JSON file" + Assert-Equal $state.Configuration.nodePoolSize 3 "Node count forwarded in JSON file" Assert-Equal $state.Configuration.iPTagConfiguration.type "FirstPartyUsage" "IP tag type forwarded in JSON file" Assert-Equal $state.Configuration.iPTagConfiguration.value $tagValue "Special characters round-trip in JSON file" Assert-Equal (Test-Path -LiteralPath $state.ParameterFile) $false "Temporary file removed after deployment" @@ -127,10 +164,38 @@ try { $state = Invoke-Scenario -Parameters @{ targetResourceConfiguration = $configuration } -Existing if ($state.Error) { throw $state.Error } - Assert-Equal $state.Deployed $false "Existing collaboration skipped" - Assert-Equal $state.ParameterFile $null "No parameter file for skipped deployment" - Write-Host "PASS: existing collaboration skipped" - Write-Host "All 15 offline target-resource-configuration tests passed." + Assert-Equal $state.Deleted $true "Existing collaboration deleted" + Assert-Equal $state.Deployed $true "Fresh collaboration deployed" + Assert-Equal $state.Configuration.iPTagConfiguration.value $tagValue "Recreated IP tag" + Assert-Equal (Test-Path -LiteralPath $state.ParameterFile) $false "Parameter file cleaned up" + Write-Host "PASS: existing collaboration deleted and recreated with requested configuration" + foreach ($code in @("ResourceNotFound", "ResourceGroupNotFound")) { + $state = Invoke-Scenario -Parameters @{} -FailureMode $code + if ($state.Error) { throw $state.Error } + Assert-Equal $state.Deployed $true "JSON 404 permits creation" + Write-Host "PASS: az rest JSON $code recognized" + } + $state = Invoke-Scenario -Parameters @{} -FailureMode "AuthorizationFailed" + if (-not $state.Error -or $state.Error.Exception.Message -notlike "*AuthorizationFailed*") { + throw "Authorization failure was not propagated." + } + Assert-Equal $state.Deployed $false "Authorization failure must not trigger creation" + Write-Host "PASS: authorization errors are not treated as absence" + $state = Invoke-Scenario -Parameters @{} -FailureMode "DeploymentFailed" + if (-not $state.Error -or $state.Error.Exception.Message -notlike "*OfflineFailure*") { + throw "ARM deployment failure was not surfaced." + } + Write-Host "PASS: asynchronous deployment failure surfaced" + foreach ($mode in @("DeploymentTimeout", "SlowSubmission")) { + $state = Invoke-Scenario -Parameters @{ timeoutMinutes = 2 } -FailureMode $mode + if (-not $state.Error -or $state.Error.Exception.Message -notlike "*Timed out*") { + throw "Deployment did not time out: $mode" + } + Assert-Equal ($state.Now - [datetime]::new(2026, 10, 23)).TotalSeconds 120 ` + "Timeout includes submission time and stops at the requested deadline" + Write-Host "PASS: bounded creation timeout ($mode)" + } + Write-Host "All 25 offline target-resource-configuration tests passed." } finally { Remove-Item -LiteralPath $testDirectory -Recurse -Force -ErrorAction SilentlyContinue diff --git a/demos/analytics-using-managedcleanroom/scripts/common/Invoke-Collaboration.ps1 b/demos/analytics-using-managedcleanroom/scripts/common/Invoke-Collaboration.ps1 new file mode 100644 index 0000000..9562492 --- /dev/null +++ b/demos/analytics-using-managedcleanroom/scripts/common/Invoke-Collaboration.ps1 @@ -0,0 +1,255 @@ +function Invoke-CleanroomAz { + [CmdletBinding()] + param( + [Parameter(Mandatory)][string[]]$Arguments, + [switch]$AllowNotFound + ) + + $PSNativeCommandUseErrorActionPreference = $false + $output = & az @Arguments 2>&1 + $exitCode = $LASTEXITCODE + $text = ($output | ForEach-Object { "$_" }) -join "`n" + if ($exitCode -ne 0) { + # az rest wraps its JSON error in "Not Found(...)", unlike other az commands. + $notFoundPattern = '\((ResourceNotFound|ResourceGroupNotFound)\)|' + + 'Not Found\(\s*\{\s*"error"\s*:\s*\{\s*"code"\s*:\s*' + + '"(ResourceNotFound|ResourceGroupNotFound)"' + if ($AllowNotFound -and $text -match $notFoundPattern) { + return $null + } + throw "Azure CLI failed (exit $exitCode): $text" + } + return $text +} + +function Get-CollaborationContext { + [CmdletBinding()] + param( + [Parameter(Mandatory)][string]$ResourceGroup, + [Parameter(Mandatory)][string]$CollaborationName, + [string]$Subscription, + [string]$ApiVersion = "2026-09-30-preview", + [switch]$DryRun + ) + + if (-not $Subscription) { + $account = Invoke-CleanroomAz -Arguments @("account", "show", "-o", "json") | + ConvertFrom-Json + $Subscription = $account.id + } + if ([string]::IsNullOrWhiteSpace($Subscription)) { + throw "No Azure subscription selected. Run az login or pass -Subscription." + } + $armEndpoint = "https://management.azure.com" + $resourceId = "/subscriptions/$Subscription/resourceGroups/$ResourceGroup" + + "/providers/Microsoft.CleanRoom/Collaborations/$CollaborationName" + return [pscustomobject]@{ + ResourceGroup = $ResourceGroup + CollaborationName = $CollaborationName + Subscription = $Subscription + ArmEndpoint = $armEndpoint + ResourceUri = "$armEndpoint$resourceId" + ApiVersion = $ApiVersion + DryRun = [bool]$DryRun + } +} + +function ConvertTo-Collaborator { + [CmdletBinding()] + param([Parameter(Mandatory)][object]$Identity) + + $identifier = if ($Identity -is [string]) { $Identity } else { $Identity.userIdentifier } + if ([string]::IsNullOrWhiteSpace($identifier)) { + throw "Each collaborator requires a nonempty userIdentifier (email or app client ID)." + } + $result = @{ userIdentifier = $identifier } + $appId = [guid]::Empty + $isApp = [guid]::TryParse($identifier, [ref]$appId) + if ($isApp -or $Identity.objectId -or $Identity.tenantId) { + foreach ($field in @("objectId", "tenantId")) { + $value = [guid]::Empty + if (-not [guid]::TryParse([string]$Identity.$field, [ref]$value) -or + $value -eq [guid]::Empty) { + throw "SPN collaborator '$identifier' requires a valid $field." + } + $result[$field] = [string]$Identity.$field + } + } + return $result +} + +function Invoke-Collaboration { + [CmdletBinding()] + param( + [Parameter(Mandatory)][pscustomobject]$Context, + [ValidateSet("GET", "POST", "DELETE")][string]$Method = "GET", + [string]$Action, + [object]$Body, + [switch]$AllowNotFound + ) + + $url = $Context.ResourceUri + if ($Action) { $url += "/$Action" } + $url += "?api-version=$($Context.ApiVersion)" + $bodyJson = if ($null -ne $Body) { $Body | ConvertTo-Json -Depth 20 -Compress } + if ($Context.DryRun) { + Write-Host "[DRY-RUN] $Method $url" + if ($bodyJson) { Write-Host "[DRY-RUN] body: $bodyJson" } + return + } + $arguments = @("rest", "--method", $Method, "--url", $url, + "--resource", $Context.ArmEndpoint, "-o", "json") + $bodyFile = $null + try { + if ($bodyJson) { + $bodyFile = [IO.Path]::GetTempFileName() + [IO.File]::WriteAllText($bodyFile, $bodyJson) + $arguments += @("--headers", "Content-Type=application/json", "--body", "@$bodyFile") + } + $json = Invoke-CleanroomAz -Arguments $arguments -AllowNotFound:$AllowNotFound + if (-not [string]::IsNullOrWhiteSpace($json)) { return $json | ConvertFrom-Json } + } + finally { + if ($bodyFile) { Remove-Item -LiteralPath $bodyFile -Force } + } +} + +function Invoke-CollaborationOperation { + [CmdletBinding()] + param( + [Parameter(Mandatory)][pscustomobject]$Context, + [Parameter(Mandatory)][string]$Action, + [Parameter(Mandatory)][object]$Body, + [ValidateRange(1, 1440)][int]$TimeoutMinutes = 60, + [switch]$NoWait + ) + + if ($Context.DryRun) { + Invoke-Collaboration -Context $Context -Method POST -Action $Action -Body $Body + return + } + $deadline = (Get-Date).AddMinutes($TimeoutMinutes) + $timeoutMessage = "Timed out waiting for '$Action'. The Azure operation was not cancelled; " + + "inspect its state before retrying." + function Send-OperationRequest { + param([string]$Uri, [string]$Method, [string]$Json) + if ((Get-Date) -ge $deadline) { throw $timeoutMessage } + $auth = Invoke-CleanroomAz -Arguments @("account", "get-access-token", + "--subscription", $Context.Subscription, + "--resource", "$($Context.ArmEndpoint)/", "-o", "json") | ConvertFrom-Json + if (-not $auth.accessToken) { throw "Azure CLI returned no ARM access token." } + $remaining = [Math]::Ceiling(($deadline - (Get-Date)).TotalSeconds) + if ($remaining -le 0) { throw $timeoutMessage } + $parameters = @{ + Uri = $Uri + Method = $Method + Headers = @{ Authorization = "Bearer $($auth.accessToken)" } + TimeoutSec = [Math]::Min(120, $remaining) + MaximumRedirection = 0 + } + if ($Json) { $parameters.Body = $Json; $parameters.ContentType = "application/json" } + $result = Invoke-WebRequest @parameters + if ((Get-Date) -ge $deadline) { throw $timeoutMessage } + return $result + } + + $url = "$($Context.ResourceUri)/${Action}?api-version=$($Context.ApiVersion)" + $response = Send-OperationRequest -Uri $url -Method POST ` + -Json ($Body | ConvertTo-Json -Depth 20 -Compress) + if ($NoWait) { return } + $trackingUrl = [string]@($response.Headers["Azure-AsyncOperation"])[0] + if (-not $trackingUrl) { + $trackingUrl = [string]@($response.Headers["Operation-Location"])[0] + } + $statusEndpoint = -not [string]::IsNullOrWhiteSpace($trackingUrl) + if (-not $trackingUrl) { $trackingUrl = [string]@($response.Headers["Location"])[0] } + if (-not $trackingUrl) { + if ($response.StatusCode -eq 202) { + throw "ARM accepted '$Action' without an operation tracking URL. Inspect state before retrying." + } + return + } + $trackingUri = $null + $armHost = ([Uri]$Context.ArmEndpoint).Host + if (-not [Uri]::TryCreate($trackingUrl, [UriKind]::Absolute, [ref]$trackingUri) -or + $trackingUri.Scheme -ne "https" -or $trackingUri.UserInfo -or $trackingUri.Port -ne 443 -or + ($trackingUri.Host -ne $armHost -and + -not $trackingUri.Host.EndsWith(".management.azure.com", [StringComparison]::OrdinalIgnoreCase))) { + throw "ARM returned an unexpected operation tracking URL." + } + do { + $response = Send-OperationRequest -Uri $trackingUrl -Method GET + if ($statusEndpoint) { + $operation = $response.Content | ConvertFrom-Json + if ([string]::IsNullOrWhiteSpace($operation.status)) { + throw "ARM operation status response has no status." + } + if ($operation.status -eq "Succeeded") { return } + if ($operation.status -in @("Failed", "Canceled", "Cancelled")) { + $details = $operation.error | ConvertTo-Json -Depth 20 -Compress + throw "ARM operation '$Action' ended in state '$($operation.status)': $details" + } + Write-Host "Waiting for $Action (operation status=$($operation.status))..." + } elseif ($response.StatusCode -ne 202) { + return + } + $remaining = ($deadline - (Get-Date)).TotalSeconds + if ($remaining -le 0) { throw $timeoutMessage } + $retryAfter = 30 + $headerDelay = 0 + if ([int]::TryParse([string]@($response.Headers["Retry-After"])[0], [ref]$headerDelay) -and + $headerDelay -gt 0) { $retryAfter = $headerDelay } + Start-Sleep -Seconds ([Math]::Min($retryAfter, $remaining)) + } while ($true) +} + +function Wait-Collaboration { + [CmdletBinding()] + param( + [Parameter(Mandatory)][pscustomobject]$Context, + [Parameter(Mandatory)][scriptblock]$Condition, + [Parameter(Mandatory)][string]$Description, + [ValidateRange(1, 1440)][int]$TimeoutMinutes = 60, + [ValidateRange(1, 3600)][int]$IntervalSeconds = 30, + [switch]$AllowNotFound, + [datetime]$Deadline, + [string]$DeploymentName + ) + + if (-not $PSBoundParameters.ContainsKey("Deadline")) { + $Deadline = (Get-Date).AddMinutes($TimeoutMinutes) + } + $timeoutMessage = "Timed out after $TimeoutMinutes minutes waiting for $Description. " + + "The Azure operation was not cancelled; inspect its state before retrying." + do { + if ((Get-Date) -ge $Deadline) { throw $timeoutMessage } + $deploymentReady = $true + if ($DeploymentName) { + $deployment = Invoke-CleanroomAz -Arguments @("deployment", "group", "show", + "--subscription", $Context.Subscription, "--resource-group", $Context.ResourceGroup, + "--name", $DeploymentName, "-o", "json") | ConvertFrom-Json + $deploymentState = $deployment.properties.provisioningState + if ([string]::IsNullOrWhiteSpace($deploymentState)) { + throw "ARM deployment '$DeploymentName' returned no provisioning state." + } + if ($deploymentState -in @("Failed", "Canceled", "Cancelled")) { + $details = $deployment.properties.error | ConvertTo-Json -Depth 20 -Compress + throw "ARM deployment '$DeploymentName' ended in state '${deploymentState}': $details" + } + $deploymentReady = $deploymentState -eq "Succeeded" + } + $collaboration = Invoke-Collaboration -Context $Context -AllowNotFound:$AllowNotFound + if ($collaboration.properties.provisioningState -in @("Failed", "Canceled", "Cancelled")) { + $details = $collaboration.properties | ConvertTo-Json -Depth 10 -Compress + throw "Failed waiting for ${Description}: $details" + } + if ((Get-Date) -ge $Deadline) { throw $timeoutMessage } + if ($deploymentReady -and (& $Condition $collaboration)) { return $collaboration } + Write-Host "Waiting for $Description (state=$($collaboration.properties.provisioningState))..." + if ($collaboration.properties.health.healthIssues) { + $collaboration.properties.health.healthIssues | ConvertTo-Json -Depth 10 | Out-Host + } + $remainingSeconds = [Math]::Max(0, ($Deadline - (Get-Date)).TotalSeconds) + Start-Sleep -Seconds ([Math]::Min($IntervalSeconds, $remainingSeconds)) + } while ($true) +} diff --git a/demos/analytics-using-managedcleanroom/scripts/common/add-app-collaborator.ps1 b/demos/analytics-using-managedcleanroom/scripts/common/add-app-collaborator.ps1 index 19f97d2..d883000 100644 --- a/demos/analytics-using-managedcleanroom/scripts/common/add-app-collaborator.ps1 +++ b/demos/analytics-using-managedcleanroom/scripts/common/add-app-collaborator.ps1 @@ -9,6 +9,8 @@ IMPORTANT: The --user-identifier for an SPN is the Application (client) ID, NOT the Enterprise App object ID or the App Registration object ID. + Supply the Enterprise Application objectId and tenantId as well. + SPNs auto-activate and do not need invitation acceptance. .PARAMETER collaborationName Name of the collaboration. @@ -22,11 +24,23 @@ .PARAMETER appClientId Application (client) ID of the app to add as collaborator. +.PARAMETER objectId + Enterprise Application object ID of the service principal. + +.PARAMETER tenantId + Tenant ID of the service principal. + .PARAMETER apiVersion ARM API version (default: 2026-09-30-preview). +.PARAMETER NoWait + Submit without waiting for the collaborator to appear on the resource. + +.PARAMETER DryRun + Preview the request without changing the collaboration. + .EXAMPLE - ./scripts/common/add-app-collaborator.ps1 -collaborationName -resourceGroup -subscription "" -appClientId "" + ./scripts/common/add-app-collaborator.ps1 -collaborationName -resourceGroup -subscription "" -appClientId "" -objectId "" -tenantId "" #> param( [Parameter(Mandatory)] @@ -41,62 +55,20 @@ param( [Parameter(Mandatory)] [string]$appClientId, - [string]$apiVersion = "2026-09-30-preview" + [Parameter(Mandatory)] + [string]$objectId, + + [Parameter(Mandatory)] + [string]$tenantId, + + [string]$apiVersion = "2026-09-30-preview", + [switch]$NoWait, + [switch]$DryRun ) $ErrorActionPreference = 'Stop' -Write-Host "=== Adding app collaborator to '$collaborationName' ===" -ForegroundColor Cyan -Write-Host " App Client ID: $appClientId" -ForegroundColor Yellow - -# Get a management token from the current az login session -$token = az account get-access-token --resource "https://management.azure.com/" --query accessToken -o tsv -if ($LASTEXITCODE -ne 0 -or -not $token) { - throw "Failed to get management token. Run 'az login' first." -} - -$baseUrl = "https://management.azure.com" -$collabUrl = "$baseUrl/subscriptions/$subscription/resourceGroups/$resourceGroup/providers/Microsoft.CleanRoom/collaborations/$collaborationName" - -# Step 1: Verify the collaboration exists -Write-Host "Verifying collaboration..." -ForegroundColor Cyan -$headers = @{ Authorization = "Bearer $token" } -try { - $collab = Invoke-RestMethod -Method Get -Uri "$($collabUrl)?api-version=$apiVersion" -Headers $headers - Write-Host " Collaboration found: $($collab.name), State: $($collab.properties.provisioningState)" -ForegroundColor Green - Write-Host " Current collaborators:" -ForegroundColor Yellow - foreach ($c in $collab.properties.collaborators) { - Write-Host " - $($c.userIdentifier) (type=$($c.identityType), owner=$($c.isCollaborationOwner))" -ForegroundColor Yellow - } -} catch { - throw "Cannot read collaboration: $_" -} - -# Step 2: Add the app as collaborator -Write-Host "`nAdding app as collaborator..." -ForegroundColor Cyan -$addUrl = "$($collabUrl)/addCollaborator?api-version=$apiVersion" -$body = @{ collaborator = @{ userIdentifier = $appClientId } } | ConvertTo-Json -Depth 3 - -try { - $result = Invoke-RestMethod -Method Post -Uri $addUrl -Headers $headers -Body $body -ContentType "application/json" - Write-Host " Collaborator added successfully!" -ForegroundColor Green -} catch { - $errBody = $_.ErrorDetails.Message - if ($errBody -match "already exists|already added|Conflict") { - Write-Host " App already added as collaborator (idempotent)." -ForegroundColor Yellow - } else { - Write-Host " Failed to add collaborator: $errBody" -ForegroundColor Red - throw "Add collaborator failed: $_" - } -} - -# Step 3: Verify -Write-Host "`nVerifying updated collaborators..." -ForegroundColor Cyan -$collab = Invoke-RestMethod -Method Get -Uri "$($collabUrl)?api-version=$apiVersion" -Headers $headers -foreach ($c in $collab.properties.collaborators) { - $marker = if ($c.userIdentifier -eq $appClientId) { ">>> NEW" } else { " " } - Write-Host " $marker $($c.userIdentifier) (type=$($c.identityType), objId=$($c.objectId))" -ForegroundColor $(if ($c.userIdentifier -eq $appClientId) { "Green" } else { "Yellow" }) -} - -Write-Host "`n=== Done ===" -ForegroundColor Green -Write-Host "Next: The app may need to accept an invitation via the frontend API." -ForegroundColor Yellow +& "$PSScriptRoot/../bicep/manage-collaboration.ps1" -Action AddCollaborator ` + -ResourceGroup $resourceGroup -CollaborationName $collaborationName ` + -Subscription $subscription -ApiVersion $apiVersion -NoWait:$NoWait -DryRun:$DryRun ` + -Collaborators @(@{ userIdentifier = $appClientId; objectId = $objectId; tenantId = $tenantId }) diff --git a/demos/analytics-using-managedcleanroom/scripts/frontend/06-set-consent.ps1 b/demos/analytics-using-managedcleanroom/scripts/frontend/06-set-consent.ps1 new file mode 100644 index 0000000..519a79b --- /dev/null +++ b/demos/analytics-using-managedcleanroom/scripts/frontend/06-set-consent.ps1 @@ -0,0 +1,22 @@ +<# +.SYNOPSIS + Enables or disables execution consent on an existing document without republishing it. +#> +param( + [Parameter(Mandatory)][string]$Persona, + [Parameter(Mandatory)][string]$CollaborationId, + [Parameter(Mandatory)][string]$DocumentId, + [Parameter(Mandatory)][ValidateSet("enable", "disable")][string]$ConsentAction, + [string]$Frontend, + [string]$TokenFile, + [switch]$DryRun +) + +$ErrorActionPreference = "Stop" +. "$PSScriptRoot/Invoke-Frontend.ps1" +$fe = Get-FrontendContext -Persona $Persona -Frontend $Frontend -TokenFile $TokenFile -DryRun:$DryRun +$id = [Uri]::EscapeDataString($CollaborationId) +$document = [Uri]::EscapeDataString($DocumentId) +Invoke-Frontend -Context $fe -Path "$id/consent/$document" -Method PUT ` + -Body @{ consentAction = $ConsentAction.ToLowerInvariant() } +if (-not $DryRun) { Write-Host "Execution consent set to '$ConsentAction' for '$DocumentId'." } diff --git a/demos/analytics-using-managedcleanroom/scripts/frontend/08-approve-query.ps1 b/demos/analytics-using-managedcleanroom/scripts/frontend/08-approve-query.ps1 index 56c4ced..e789ec6 100644 --- a/demos/analytics-using-managedcleanroom/scripts/frontend/08-approve-query.ps1 +++ b/demos/analytics-using-managedcleanroom/scripts/frontend/08-approve-query.ps1 @@ -47,9 +47,7 @@ if (-not $DryRun -and $VoteAction -eq "accept" -and $queryInfo.state -eq "Accept return } if (-not $proposalId -and -not $DryRun) { - # A missing proposal usually means the query is already decided, not unpublished. - Write-Host "Query '$QueryName' has no open proposal (state='$($queryInfo.state)'); nothing to vote on." - return + throw "Cannot vote '$VoteAction': query '$QueryName' has no open proposal (state='$($queryInfo.state)')." } Write-Host "Proposal ID: $proposalId" diff --git a/demos/analytics-using-managedcleanroom/scripts/frontend/09-cancel-query.ps1 b/demos/analytics-using-managedcleanroom/scripts/frontend/09-cancel-query.ps1 new file mode 100644 index 0000000..6ef79a6 --- /dev/null +++ b/demos/analytics-using-managedcleanroom/scripts/frontend/09-cancel-query.ps1 @@ -0,0 +1,24 @@ +<# +.SYNOPSIS + Cancels a non-terminal query using its full cl-spark- job ID. +.DESCRIPTION + Cancel persistent failures or unwanted runs, not a single transient mount warning. + Returns the cancellation response; never submits another run. +#> +param( + [Parameter(Mandatory)][string]$Persona, + [Parameter(Mandatory)][string]$CollaborationId, + [Parameter(Mandatory)][string]$QueryName, + [Parameter(Mandatory)][Alias("RunId")][ValidatePattern("^cl-spark-.+")][string]$JobId, + [string]$Frontend, + [string]$TokenFile, + [switch]$DryRun +) + +$ErrorActionPreference = "Stop" +. "$PSScriptRoot/Invoke-Frontend.ps1" +$fe = Get-FrontendContext -Persona $Persona -Frontend $Frontend -TokenFile $TokenFile -DryRun:$DryRun +$id = [Uri]::EscapeDataString($CollaborationId) +$query = [Uri]::EscapeDataString($QueryName) +$job = [Uri]::EscapeDataString($JobId) +Invoke-Frontend -Context $fe -Path "$id/analytics/queries/$query/runs/$job/cancel" -Method POST diff --git a/demos/analytics-using-managedcleanroom/scripts/frontend/09-run-query.ps1 b/demos/analytics-using-managedcleanroom/scripts/frontend/09-run-query.ps1 index 4c127d3..4b0729b 100644 --- a/demos/analytics-using-managedcleanroom/scripts/frontend/09-run-query.ps1 +++ b/demos/analytics-using-managedcleanroom/scripts/frontend/09-run-query.ps1 @@ -27,6 +27,10 @@ .PARAMETER EndDate Optional dataset date-range upper bound (e.g. "2025-09-02"). +.PARAMETER ServiceDryRun + Sends dryRun=true to the frontend and returns its skuSettings response + without executing a query. Different from the local-only -DryRun preview. + .EXAMPLE ./09-run-query.ps1 -Persona woodgrove -CollaborationId $collabId -QueryName "query1-v1" #> @@ -39,23 +43,34 @@ param( [string]$EndDate, [string]$Frontend, [string]$TokenFile, + [switch]$ServiceDryRun, [switch]$DryRun ) $ErrorActionPreference = "Stop" . "$PSScriptRoot/Invoke-Frontend.ps1" +if ($DryRun -and $ServiceDryRun) { + throw "Choose either -DryRun (local preview) or -ServiceDryRun (frontend validation)." +} $fe = Get-FrontendContext -Persona $Persona -Frontend $Frontend -TokenFile $TokenFile -DryRun:$DryRun $runBody = @{ runId = [guid]::NewGuid().ToString(); scaleSku = $ScaleSku.ToLowerInvariant() } if ($StartDate) { $runBody.startDate = $StartDate } if ($EndDate) { $runBody.endDate = $EndDate } +if ($ServiceDryRun) { $runBody.dryRun = $true } $runResult = Invoke-Frontend -Context $fe -Path "$CollaborationId/analytics/queries/$QueryName/run" -Method POST -Body $runBody if ($DryRun) { Write-Host "[DRY-RUN] No run submitted. Job ID placeholder: " return "" } +if ($ServiceDryRun) { + if (-not $runResult.skuSettings) { + throw "The service dry run returned no skuSettings. Inspect the frontend response/API version." + } + return $runResult +} $jobId = $runResult.id if ([string]::IsNullOrWhiteSpace([string]$jobId)) { throw "Frontend did not return a job ID for query '$QueryName'. Submission may have succeeded; check run history before retrying." diff --git a/demos/analytics-using-managedcleanroom/scripts/frontend/10-monitor-query.ps1 b/demos/analytics-using-managedcleanroom/scripts/frontend/10-monitor-query.ps1 index be93828..46aaf82 100644 --- a/demos/analytics-using-managedcleanroom/scripts/frontend/10-monitor-query.ps1 +++ b/demos/analytics-using-managedcleanroom/scripts/frontend/10-monitor-query.ps1 @@ -3,7 +3,8 @@ Step 10 [ANY] - Monitor a query run until it reaches a terminal state. .DESCRIPTION - Polls the run status until COMPLETED, FAILED, or SUBMISSION_FAILED. + Polls until COMPLETED, FAILED, SUBMISSION_FAILED, cancellation, or timeout. + Prints new/updated events while waiting and returns the detailed result on success. On failure, attempts to print collaboration health issues to aid triage (e.g. CACI capacity shortages, executor pods stuck in init), then throws. A health lookup error does not replace the original terminal run failure. @@ -22,6 +23,14 @@ .PARAMETER IntervalSeconds Poll interval (default: 30). +.PARAMETER Once + Returns one detailed run-result object, including events, without waiting + or throwing for a failed run. Use this to diagnose a stuck query. + +.PARAMETER TimeoutMinutes + Maximum monitoring time (default: 60 minutes). Timing out does not cancel + or resubmit the query. + .EXAMPLE ./10-monitor-query.ps1 -Persona woodgrove -CollaborationId $collabId -JobId $jobId #> @@ -29,7 +38,9 @@ param( [Parameter(Mandatory)][string]$Persona, [Parameter(Mandatory)][string]$CollaborationId, [Parameter(Mandatory)][string]$JobId, - [int]$IntervalSeconds = 30, + [ValidateRange(1, 3600)][int]$IntervalSeconds = 30, + [ValidateRange(1, 1440)][int]$TimeoutMinutes = 60, + [switch]$Once, [string]$Frontend, [string]$TokenFile, [switch]$DryRun @@ -41,28 +52,51 @@ $ErrorActionPreference = "Stop" $fe = Get-FrontendContext -Persona $Persona -Frontend $Frontend -TokenFile $TokenFile -DryRun:$DryRun if ($DryRun) { - Write-Host "[DRY-RUN] Would poll run status for job $JobId until COMPLETED/FAILED/SUBMISSION_FAILED." + Invoke-Frontend -Context $fe -Path "$CollaborationId/analytics/runs/$JobId" | Out-Null + Write-Host "[DRY-RUN] Read once: $Once; monitoring timeout: $TimeoutMinutes minutes." return } +$deadline = (Get-Date).AddMinutes($TimeoutMinutes) +$seenEvents = [System.Collections.Generic.HashSet[string]]::new() +$terminalStates = @("COMPLETED", "FAILED", "SUBMISSION_FAILED", "CANCELLED", "CANCELED") +$timedOut = $false do { $result = Invoke-Frontend -Context $fe -Path "$CollaborationId/analytics/runs/$JobId" + if ($Once) { return $result } $state = $result.status.applicationState.state Write-Host "[$(Get-Date -Format 'HH:mm:ss')] State: $state" - if ($state -notin @("COMPLETED", "FAILED", "SUBMISSION_FAILED")) { Start-Sleep -Seconds $IntervalSeconds } -} while ($state -notin @("COMPLETED", "FAILED", "SUBMISSION_FAILED")) + foreach ($event in $result.events) { + $key = "$($event.reason)|$($event.message)|$($event.count)|$($event.lastTimestamp)" + if ($seenEvents.Add($key)) { + Write-Host " $($event.type) $($event.reason): $($event.message) (count=$($event.count))" + } + } + if ($state -in $terminalStates) { break } + if ((Get-Date) -ge $deadline) { $timedOut = $true; break } + $remainingSeconds = [Math]::Max(0, ($deadline - (Get-Date)).TotalSeconds) + Start-Sleep -Seconds ([Math]::Min($IntervalSeconds, $remainingSeconds)) +} while ($true) Write-Host "" -$result | ConvertTo-Json -Depth 10 +$result | ConvertTo-Json -Depth 20 | Out-Host -if ($state -ne "COMPLETED") { - Write-Warning "Run ended in state '$state'. Checking collaboration health for pod-level/capacity issues..." +if ($timedOut -or $state -ne "COMPLETED") { + Write-Warning "Monitoring stopped in state '$state'. Checking collaboration health..." try { $collabs = (Invoke-Frontend -Context $fe -Path "" -Method GET).collaborations $health = ($collabs | Where-Object { $_.collaborationId -eq $CollaborationId }).health - if ($health) { $health | ConvertTo-Json -Depth 5 } + if ($health) { + $health | ConvertTo-Json -Depth 5 | Out-Host + } else { + Write-Warning "Frontend returned no health details. Use manage-collaboration.ps1 -Action Show and inspect properties.health." + } } catch { Write-Warning "Could not retrieve collaboration health: $($_.Exception.Message)" } + if ($timedOut) { + throw "Timed out monitoring '$JobId' (state='$state'). The run was NOT cancelled. Inspect with -Once or cancel explicitly." + } throw "Query run '$JobId' ended in state '$state'." } +return $result diff --git a/demos/analytics-using-managedcleanroom/scripts/frontend/12-get-readonly-kubeconfig.ps1 b/demos/analytics-using-managedcleanroom/scripts/frontend/12-get-readonly-kubeconfig.ps1 index 1cc680b..a961e5b 100644 --- a/demos/analytics-using-managedcleanroom/scripts/frontend/12-get-readonly-kubeconfig.ps1 +++ b/demos/analytics-using-managedcleanroom/scripts/frontend/12-get-readonly-kubeconfig.ps1 @@ -32,25 +32,25 @@ param( [Parameter(Mandatory)][string]$resourceGroup, [Parameter(Mandatory)][string]$collaborationName, [string]$OutFile = "./readonly.kubeconfig", + [string]$Subscription, [string]$apiVersion = "2026-09-30-preview", [switch]$DryRun ) $ErrorActionPreference = "Stop" -$armEndpoint = "https://management.azure.com" - -$subscription = (az account show -o json | ConvertFrom-Json).id -$collabArmUrl = "$armEndpoint/subscriptions/$subscription/resourceGroups/$resourceGroup/providers/Microsoft.CleanRoom/Collaborations/$collaborationName" +. "$PSScriptRoot/../common/Invoke-Collaboration.ps1" +$context = Get-CollaborationContext -ResourceGroup $resourceGroup ` + -CollaborationName $collaborationName -Subscription $Subscription ` + -ApiVersion $apiVersion -DryRun:$DryRun +$kc = Invoke-Collaboration -Context $context -Method POST -Action getReadonlyKubeConfig if ($DryRun) { - Write-Host "[DRY-RUN] POST $collabArmUrl/getReadonlyKubeConfig?api-version=$apiVersion" Write-Host "[DRY-RUN] Would decode kubeconfig and write to $OutFile" return } - -$kc = az rest --method POST ` - --url "$collabArmUrl/getReadonlyKubeConfig`?api-version=$apiVersion" ` - --resource $armEndpoint -o json | ConvertFrom-Json +if ([string]::IsNullOrWhiteSpace($kc.kubeconfig)) { + throw "ARM returned no read-only kubeconfig." +} $bytes = [Convert]::FromBase64String($kc.kubeconfig) [System.Text.Encoding]::UTF8.GetString($bytes) | Out-File $OutFile -Encoding utf8 diff --git a/demos/analytics-using-managedcleanroom/scripts/frontend/Invoke-Frontend.ps1 b/demos/analytics-using-managedcleanroom/scripts/frontend/Invoke-Frontend.ps1 index 9ebc321..6cf7025 100644 --- a/demos/analytics-using-managedcleanroom/scripts/frontend/Invoke-Frontend.ps1 +++ b/demos/analytics-using-managedcleanroom/scripts/frontend/Invoke-Frontend.ps1 @@ -14,9 +14,10 @@ $collabs = (Invoke-Frontend -Context $fe -Path "" -Method GET).collaborations Token resolution order (first match wins): - 1. $env:CLEANROOM_FRONTEND_TOKEN (SPN / CI, set by setup-local-auth.ps1) - 2. -TokenFile (explicit override) - 3. Temp file msal-idtoken-.txt (per-persona, per README Step 1.5) + 1. -TokenFile (explicit override) + 2. $env:CLEANROOM_FRONTEND_TOKEN (SPN / CI) + 3. $env:MANAGEDCLEANROOM_ACCESS_TOKEN (CLI session) + 4. Temp file msal-idtoken-.txt (per README Step 1.5) Acquire the per-persona token first (README Step 1.5), e.g.: az account get-access-token --resource "https://management.azure.com/" ` @@ -45,15 +46,30 @@ function Get-FrontendContext { if (-not $Frontend) { $Frontend = "https://prod-nonattested.workload-frontendwestus.cleanroom.cloudapp.azure.net" } + $endpoint = $null + if (-not [Uri]::TryCreate($Frontend, [UriKind]::Absolute, [ref]$endpoint) -or + $endpoint.Scheme -ne "https" -or $endpoint.UserInfo -or + $endpoint.Query -or $endpoint.Fragment) { + throw "Frontend must be an absolute HTTPS URL without credentials, query, or fragment." + } # Resolve the bearer token (skipped in dry-run mode). $token = $null if ($DryRun) { $token = "" } + elseif ($TokenFile) { + if (-not (Test-Path -LiteralPath $TokenFile -PathType Leaf)) { + throw "Frontend token file not found: $TokenFile" + } + $token = (Get-Content -LiteralPath $TokenFile -Raw).Trim() + } elseif ($env:CLEANROOM_FRONTEND_TOKEN) { $token = $env:CLEANROOM_FRONTEND_TOKEN.Trim() } + elseif ($env:MANAGEDCLEANROOM_ACCESS_TOKEN) { + $token = $env:MANAGEDCLEANROOM_ACCESS_TOKEN.Trim() + } else { if (-not $TokenFile) { $TokenFile = Join-Path ([System.IO.Path]::GetTempPath()) "msal-idtoken-$Persona.txt" @@ -63,6 +79,9 @@ function Get-FrontendContext { } $token = (Get-Content $TokenFile -Raw).Trim() } + if ([string]::IsNullOrWhiteSpace($token)) { + throw "Frontend token is empty. Supply a valid -TokenFile or frontend token environment variable." + } return [pscustomobject]@{ Persona = $Persona @@ -91,7 +110,8 @@ function Invoke-Frontend { "Content-Type" = "application/json" } - $url = if ($Path) { "$($Context.Frontend)/collaborations/$Path" } else { "$($Context.Frontend)/collaborations" } + $url = "$($Context.Frontend)/collaborations" + if ($Path) { $url += $(if ($Path.StartsWith("?")) { $Path } else { "/$Path" }) } if ($url -notmatch '\?') { $url += "?api-version=$($Context.ApiVersion)" } else { $url += "&api-version=$($Context.ApiVersion)" } @@ -122,7 +142,7 @@ function Invoke-Frontend { function Resolve-CollaborationId { <# .SYNOPSIS - Resolves a frontend collaboration UUID by id, name, or first-visible. + Resolves a UUID by ID, unique name, or the only visible collaboration. #> [CmdletBinding()] param( @@ -141,13 +161,16 @@ function Resolve-CollaborationId { if (-not $collabs) { throw "No collaborations visible to persona '$($Context.Persona)'." } if ($CollaborationName) { - $match = $collabs | Where-Object { $_.collaborationName -eq $CollaborationName } + $match = @($collabs | Where-Object { $_.collaborationName -eq $CollaborationName }) if (-not $match) { throw "No collaboration named '$CollaborationName' visible to '$($Context.Persona)'." } - return @($match)[0].collaborationId + if ($match.Count -ne 1) { + throw "Multiple collaborations named '$CollaborationName'. Pass -CollaborationId." + } + return $match[0].collaborationId } if (@($collabs).Count -gt 1) { - Write-Warning "Multiple collaborations visible; using the first. Pass -CollaborationName or -CollaborationId to disambiguate." + throw "Multiple collaborations visible. Pass -CollaborationName or -CollaborationId." } return @($collabs)[0].collaborationId } diff --git a/demos/analytics-using-managedcleanroom/scripts/frontend/README.md b/demos/analytics-using-managedcleanroom/scripts/frontend/README.md index e2d128f..e075c9e 100644 --- a/demos/analytics-using-managedcleanroom/scripts/frontend/README.md +++ b/demos/analytics-using-managedcleanroom/scripts/frontend/README.md @@ -27,9 +27,10 @@ relative to the demo root. For a complete ordered setup, follow healthy (run `.\scripts\bicep\deploy-managed-cleanroom.ps1` first). 2. Each collaborator is authenticated and has a **frontend token** available. Token resolution order used by `Invoke-Frontend.ps1`: - 1. `$env:CLEANROOM_FRONTEND_TOKEN` (SPN / CI) - 2. `-TokenFile ` - 3. per-persona temp file `msal-idtoken-.txt` + 1. `-TokenFile ` (explicit override) + 2. `$env:CLEANROOM_FRONTEND_TOKEN` (SPN / CI) + 3. `$env:MANAGEDCLEANROOM_ACCESS_TOKEN` (CLI session) + 4. per-persona temp file `msal-idtoken-.txt` Acquire a per-persona token and extract its `oid` as `$personaOid` (README Step 1.5). For the corporate-account token option: @@ -46,15 +47,19 @@ relative to the demo root. For a complete ordered setup, follow | Script | Step | Runs as | |--------|------|---------| | `Invoke-Frontend.ps1` | — | shared helper (dot-sourced) | +| `get-frontend-data.ps1` | 03–11 | ANY authorized collaborator; lists/shows resources | | `run-collaborator.ps1` | 03 + 06 + 08 | EACH collaborator (orchestrator) | +| `run-query.ps1` | 07 + 09–11 | Owner; returns the job ID or service-preview response | | `03-accept-invitation.ps1` | 03 | EACH collaborator | | `05-fetch-jwks.ps1` | 5.1 | EACH collaborator | | `05-set-issuer-url.ps1` | 5.3 | EACH collaborator | | `06-publish-dataset.ps1` | 6.2 / 6.3 | EACH (output = Woodgrove) | +| `06-set-consent.ps1` | 06 | Document owner; enable/disable without republishing | | `07-publish-query.ps1` | 7.2 | Woodgrove | | `08-approve-query.ps1` | 08 | EACH collaborator | | `09-run-query.ps1` | 09 | Woodgrove | -| `10-monitor-query.ps1` | 10 | ANY | +| `09-cancel-query.ps1` | 09 | Woodgrove; full job ID required | +| `10-monitor-query.ps1` | 10 | ANY; bounded polling or `-Once` | | `11-results-audit.ps1` | 11.1 / 11.2 | Woodgrove | | `12-get-readonly-kubeconfig.ps1` | 12.1 | Owner (ARM action) | @@ -78,8 +83,9 @@ $queryName = "" Single-owner `query1` binds Woodgrove's input twice; it needs neither Northwind data nor a Northwind vote. Publication casts Woodgrove's accept vote. -Pass `-CollaborationId` or `-CollaborationName` explicitly to avoid the -orchestrator's first-visible-collaboration fallback. Resource provisioning and +Pass `-CollaborationId` or `-CollaborationName` explicitly. The orchestrators +auto-select only when exactly one collaboration is visible; ambiguous names +or multiple visible collaborations produce an error. Resource provisioning and OIDC are prerequisites and are not run by the orchestrator. Do not defer a query's input-dataset publication until its approval step. @@ -170,18 +176,46 @@ $jobId = .\scripts\frontend\09-run-query.ps1 -Persona woodgrove -CollaborationId ## Notes - Frontend scripts accept optional `-Frontend` and `-TokenFile` overrides; - the ARM-only kubeconfig helper does not. An environment token takes - precedence over `-TokenFile` in the shared frontend helper. -- `06-publish-dataset.ps1 -DisableConsent` toggles execution consent off. + the ARM-only kubeconfig helper does not. An explicit token file takes + precedence over environment tokens. The default frontend is the non-attested + West US endpoint with CA-issued TLS; certificate verification remains enabled. +- `06-publish-dataset.ps1 -DisableConsent` disables execution consent after + publishing. Use `06-set-consent.ps1` to change consent without republishing. - `09-run-query.ps1` and `run-query.ps1` accept `-ScaleSku small` (default), `medium`, or `large`, and `-StartDate` / `-EndDate` for date-range filtering. The Spark execution profile is separate from the collaboration's AKS SKU. - Both run helpers stop if the frontend response has no job ID. Check run history before retrying: the service may already have scheduled the query. -- `10-monitor-query.ps1` throws on `FAILED` or `SUBMISSION_FAILED` after a - best-effort collaboration-health lookup. The orchestrator stops instead of - reporting successful completion. +- `10-monitor-query.ps1` prints new/updated events while waiting and throws on + failure, cancellation, or timeout after a best-effort health lookup. Default + timeout is 60 minutes (`-TimeoutMinutes`); `-Once` returns one detailed result, + including failures, without waiting. Timeout does not cancel or resubmit. - `-DryRun` on these frontend scripts previews requests locally; it does not send the service-side `dryRun: true` request or validate `skuSettings`. Run helpers return `` for a local preview, not an actual submitted run. - The kubeconfig helper still reads the current Azure CLI account. + The kubeconfig helper reads the current Azure CLI account unless + `-Subscription` is supplied. + +## Additional operations + +See [Fast Setup Scripts](../README-SCRIPTS.md) for the complete examples: + +| Capability | Script / option | +|---|---| +| Effective `skuSettings` without executing | Either query runner with `-ServiceDryRun`; accepts `-ScaleSku`, `-StartDate`, `-EndDate` | +| Lists and individual resource inspection | `get-frontend-data.ps1 -Resource ` | +| One detailed run result, including events | `10-monitor-query.ps1 -JobId -Once` | +| Cancel a persistent failure/unwanted run | `09-cancel-query.ps1 -QueryName -JobId ` | +| Consent without republishing | `06-set-consent.ps1 -DocumentId -ConsentAction` with `enable` or `disable` | +| ARM show/health, enable, add, recover, delete-only | `../bicep/manage-collaboration.ps1 -Action ` | + +The reader supports `Collaborations` (`-ActiveOnly`), `Invitations` +(`-PendingOnly`), `Collaborators`, `OidcKeys`, `Datasets`, `Dataset`, `Queries`, +`Query`, `Run`, `RunHistory`, and `AuditEvents`. Supply `-CollaborationId` except +when listing collaborations; individual documents need `-DocumentId` +(`-QueryName` is an alias), and runs need `-JobId`. + +`-ServiceDryRun` cannot be combined with `-DryRun` or the orchestrator's +`-BodyFile`. Real execution returns the job ID; diagnostics go to the host. +`large` remains preview-only. Inspect detailed events before cancelling; +one early `FailedMount` is not a reason to cancel. diff --git a/demos/analytics-using-managedcleanroom/scripts/frontend/get-frontend-data.ps1 b/demos/analytics-using-managedcleanroom/scripts/frontend/get-frontend-data.ps1 new file mode 100644 index 0000000..2208d1d --- /dev/null +++ b/demos/analytics-using-managedcleanroom/scripts/frontend/get-frontend-data.ps1 @@ -0,0 +1,56 @@ +<# +.SYNOPSIS + Lists or inspects frontend resources without changing them. +.DESCRIPTION + Returns objects for filtering, formatting, or saving. Run requires the full + cl-spark- JobId. Dataset and Query require DocumentId. +#> +param( + [Parameter(Mandatory)][string]$Persona, + [Parameter(Mandatory)] + [ValidateSet("Collaborations", "Invitations", "Collaborators", "OidcKeys", + "Datasets", "Dataset", "Queries", "Query", "Run", "RunHistory", "AuditEvents")] + [string]$Resource, + [string]$CollaborationId, + [Alias("QueryName")][string]$DocumentId, + [string]$JobId, + [switch]$PendingOnly, + [switch]$ActiveOnly, + [string]$Frontend, + [string]$TokenFile, + [switch]$DryRun +) + +$ErrorActionPreference = "Stop" +. "$PSScriptRoot/Invoke-Frontend.ps1" +if ($Resource -ne "Collaborations" -and -not $CollaborationId) { + throw "-CollaborationId is required for $Resource." +} +if ($Resource -in @("Dataset", "Query", "RunHistory") -and -not $DocumentId) { + throw "-DocumentId (or -QueryName) is required for $Resource." +} +if ($Resource -eq "Run" -and -not $JobId) { throw "-JobId is required for Run." } +if ($PendingOnly -and $Resource -ne "Invitations") { + throw "-PendingOnly applies only to Invitations." +} +if ($ActiveOnly -and $Resource -ne "Collaborations") { + throw "-ActiveOnly applies only to Collaborations." +} +$id = [Uri]::EscapeDataString($CollaborationId) +$document = [Uri]::EscapeDataString($DocumentId) +$job = [Uri]::EscapeDataString($JobId) +$path = switch ($Resource) { + "Collaborations" { if ($ActiveOnly) { "?activeOnly=true" } else { "" } } + "Invitations" { "$id/invitations" + $(if ($PendingOnly) { "?pendingOnly=true" }) } + "Collaborators" { "$id/collaborators" } + "OidcKeys" { "$id/oidc/keys" } + "Datasets" { "$id/analytics/datasets" } + "Dataset" { "$id/analytics/datasets/$document" } + "Queries" { "$id/analytics/queries" } + "Query" { "$id/analytics/queries/$document" } + "Run" { "$id/analytics/runs/$job" } + "RunHistory" { "$id/analytics/queries/$document/runs" } + "AuditEvents" { "$id/analytics/auditevents" } +} +$fe = Get-FrontendContext -Persona $Persona -Frontend $Frontend -TokenFile $TokenFile -DryRun:$DryRun +Invoke-Frontend -Context $fe -Path $path diff --git a/demos/analytics-using-managedcleanroom/scripts/frontend/run-collaborator.ps1 b/demos/analytics-using-managedcleanroom/scripts/frontend/run-collaborator.ps1 index fc702dd..fe8ee0d 100644 --- a/demos/analytics-using-managedcleanroom/scripts/frontend/run-collaborator.ps1 +++ b/demos/analytics-using-managedcleanroom/scripts/frontend/run-collaborator.ps1 @@ -12,7 +12,7 @@ Steps performed (each skippable): 1. Resolve the collaboration UUID (by -CollaborationId, -CollaborationName, - or first visible collaboration). + or the only visible collaboration). 2. Accept the pending invitation (03). Tolerates "already accepted". 3. (optional) Publish a dataset (06) when -DatasetDocumentId + -DatasetBodyFile are supplied. @@ -32,7 +32,7 @@ .PARAMETER CollaborationId Frontend collaboration UUID. If omitted, resolved via -CollaborationName or - the first visible collaboration. + the only visible collaboration. Ambiguous selection is rejected. .PARAMETER CollaborationName Resolve the collaboration by display name when -CollaborationId is not given. diff --git a/demos/analytics-using-managedcleanroom/scripts/frontend/run-query.ps1 b/demos/analytics-using-managedcleanroom/scripts/frontend/run-query.ps1 index 4fbaf75..afc48c6 100644 --- a/demos/analytics-using-managedcleanroom/scripts/frontend/run-query.ps1 +++ b/demos/analytics-using-managedcleanroom/scripts/frontend/run-query.ps1 @@ -5,8 +5,8 @@ .DESCRIPTION A single entry point that makes a query "easily runnable by scripts" once the - collaboration is set up. Chains the per-step scripts (07, 10, 11) and runs the - query inline to capture the job id. + collaboration is set up. Chains the per-step scripts (07, 09, 10, 11) and + returns the submitted job id. Steps performed (each skippable): 1. Resolve the collaboration UUID. @@ -28,7 +28,7 @@ .PARAMETER CollaborationId Frontend collaboration UUID. If omitted, resolved via -CollaborationName or - the first visible collaboration. + the only visible collaboration. Ambiguous selection is rejected. .PARAMETER CollaborationName Resolve the collaboration by display name when -CollaborationId is not given. @@ -60,6 +60,13 @@ .PARAMETER DryRun Print planned requests without calling the service. +.PARAMETER ServiceDryRun + Return the frontend's effective skuSettings without publishing, executing, + monitoring, or fetching results. Cannot be combined with BodyFile or DryRun. + +.PARAMETER TimeoutMinutes + Maximum time to monitor an executed run (default: 60 minutes). + .EXAMPLE # Run an approved query and wait for results ./run-query.ps1 -Persona woodgrove -QueryName query1-v1 @@ -83,11 +90,16 @@ param( [switch]$SkipResults, [string]$Frontend, [string]$TokenFile, + [ValidateRange(1, 1440)][int]$TimeoutMinutes = 60, + [switch]$ServiceDryRun, [switch]$DryRun ) $ErrorActionPreference = "Stop" . "$PSScriptRoot/Invoke-Frontend.ps1" +if ($ServiceDryRun -and ($DryRun -or $BodyFile)) { + throw "-ServiceDryRun cannot be combined with -DryRun or -BodyFile." +} $fe = Get-FrontendContext -Persona $Persona -Frontend $Frontend -TokenFile $TokenFile -DryRun:$DryRun @@ -105,12 +117,12 @@ Write-Host "==> Collaboration: $CollaborationId" if ($BodyFile) { Write-Host "==> Publishing query '$QueryName'..." & "$PSScriptRoot/07-publish-query.ps1" @childArgs -CollaborationId $CollaborationId ` - -QueryName $QueryName -BodyFile $BodyFile + -QueryName $QueryName -BodyFile $BodyFile | Out-Host Write-Host " (the publisher's vote is automatic; remaining affected collaborators must approve)" } # 3. Check approval before submitting a run. -if (-not $DryRun) { +if (-not $DryRun -and -not $ServiceDryRun) { $queryInfo = Invoke-Frontend -Context $fe -Path "$CollaborationId/analytics/queries/$QueryName" if ($queryInfo.state -ne "Accepted") { throw "Query '$QueryName' is not Accepted (state='$($queryInfo.state)'). Obtain the required approvals, then rerun without -BodyFile." @@ -118,21 +130,23 @@ if (-not $DryRun) { } # Run the query (capture the job id). -Write-Host "==> Running query '$QueryName'..." -$runBody = @{ runId = [guid]::NewGuid().ToString(); scaleSku = $ScaleSku.ToLowerInvariant() } -if ($StartDate) { $runBody.startDate = $StartDate } -if ($EndDate) { $runBody.endDate = $EndDate } -$runResult = Invoke-Frontend -Context $fe -Path "$CollaborationId/analytics/queries/$QueryName/run" -Method POST -Body $runBody -$jobId = if ($DryRun) { "" } else { $runResult.id } -if ([string]::IsNullOrWhiteSpace([string]$jobId)) { - throw "Frontend did not return a job ID for query '$QueryName'. Submission may have succeeded; check run history before retrying." +if ($ServiceDryRun) { + Write-Host "==> Validating execution settings for '$QueryName' (no query execution)..." +} else { + Write-Host "==> Running query '$QueryName'..." } +$runResult = & "$PSScriptRoot/09-run-query.ps1" @childArgs -CollaborationId $CollaborationId ` + -QueryName $QueryName -ScaleSku $ScaleSku -StartDate $StartDate -EndDate $EndDate ` + -ServiceDryRun:$ServiceDryRun +if ($ServiceDryRun) { return $runResult } +$jobId = $runResult Write-Host " Job ID: $jobId" # 4. Monitor (optional). if (-not $SkipMonitor) { Write-Host "==> Monitoring run $jobId..." - & "$PSScriptRoot/10-monitor-query.ps1" @childArgs -CollaborationId $CollaborationId -JobId $jobId + & "$PSScriptRoot/10-monitor-query.ps1" @childArgs -CollaborationId $CollaborationId ` + -JobId $jobId -TimeoutMinutes $TimeoutMinutes | Out-Null } # 5. Results + audit (optional). @@ -141,7 +155,8 @@ if (-not $SkipResults) { if ($DryRun) { & "$PSScriptRoot/11-results-audit.ps1" @childArgs -CollaborationId $CollaborationId -QueryName $QueryName | Out-Null } else { - & "$PSScriptRoot/11-results-audit.ps1" @childArgs -CollaborationId $CollaborationId -QueryName $QueryName + & "$PSScriptRoot/11-results-audit.ps1" @childArgs -CollaborationId $CollaborationId ` + -QueryName $QueryName | Out-Host } } @@ -150,5 +165,10 @@ if ($DryRun) { Write-Host "[DRY-RUN] Workflow preview complete; no query was submitted." return $jobId } -Write-Host "Query workflow complete for '$QueryName' (job $jobId) on collaboration $CollaborationId." +if ($SkipMonitor) { + Write-Host "Query submitted (not monitored): '$QueryName', job $jobId." +} else { + Write-Host "Query completed: '$QueryName', job $jobId." +} Write-Host "From the demo root, download with: .\scripts\11-download-output.ps1 -resourceGroup -datasetSuffix -JobId $jobId" +return $jobId