mirror of
https://github.com/windmill-labs/windmill.git
synced 2026-12-01 00:08:24 +00:00
feat: load a large result on request, ten render_all elements at a time (#12664)
* feat: show a large result as one placeholder that loads it on request Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: keep other json trees as on main, explain results drawn as json, and drop render_all cards in narrow panes Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: draw loaded images over 5 MB, load a non-list render_all whole, restart Load after reselecting a run Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs: say a large render_all lists up to 100 elements Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
8064fa8fb6
commit
d1abc75fa6
+57
@@ -0,0 +1,57 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "WITH v AS (\n SELECT c.result #> $3 AS r, created_by\n FROM v2_job_completed c JOIN v2_job USING (id)\n WHERE c.id = $1 AND c.workspace_id = $2 AND ($4::text[] IS NULL OR tag = ANY($4))\n )\n SELECT\n created_by AS \"created_by!\",\n jsonb_typeof(r) AS \"type\",\n length(r::text) AS \"length\",\n CASE WHEN jsonb_typeof(r) = 'object' THEN\n ARRAY(SELECT jsonb_object_keys(r) LIMIT $6)\n END AS \"keys\",\n CASE WHEN jsonb_typeof(r) = 'array' THEN jsonb_array_length(r) END AS \"item_count\",\n CASE WHEN jsonb_typeof(r) = 'array' THEN (\n SELECT jsonb_agg(jsonb_build_object(\n 'length', length(e::text),\n 'keys', CASE WHEN jsonb_typeof(e) = 'object' THEN\n to_jsonb(ARRAY(SELECT jsonb_object_keys(e) LIMIT $6))\n END\n ) ORDER BY i)\n FROM jsonb_array_elements(r) WITH ORDINALITY AS t(e, i)\n WHERE i <= $5\n ) END AS \"items: sqlx::types::Json<Vec<ResultShapeItem>>\"\n FROM v",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "created_by!",
|
||||
"type_info": "Varchar"
|
||||
},
|
||||
{
|
||||
"ordinal": 1,
|
||||
"name": "type",
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"ordinal": 2,
|
||||
"name": "length",
|
||||
"type_info": "Int4"
|
||||
},
|
||||
{
|
||||
"ordinal": 3,
|
||||
"name": "keys",
|
||||
"type_info": "TextArray"
|
||||
},
|
||||
{
|
||||
"ordinal": 4,
|
||||
"name": "item_count",
|
||||
"type_info": "Int4"
|
||||
},
|
||||
{
|
||||
"ordinal": 5,
|
||||
"name": "items: sqlx::types::Json<Vec<ResultShapeItem>>",
|
||||
"type_info": "Jsonb"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Uuid",
|
||||
"Text",
|
||||
"TextArray",
|
||||
"TextArray",
|
||||
"Int8",
|
||||
"Int8"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null
|
||||
]
|
||||
},
|
||||
"hash": "8b088d35a98d695c35d0ffe3ee3d104d2e4275bd1e9562927d591650382d510d"
|
||||
}
|
||||
@@ -139,6 +139,10 @@ async fn test_single_job_read_authorization(db: Pool<Postgres>) -> anyhow::Resul
|
||||
"completed/get_result_maybe",
|
||||
format!("completed/get_result_maybe/{VICTIM}"),
|
||||
),
|
||||
(
|
||||
"completed/get_result_shape",
|
||||
format!("completed/get_result_shape/{VICTIM}"),
|
||||
),
|
||||
("get_args", format!("get_args/{VICTIM}")),
|
||||
("get_logs", format!("get_logs/{VICTIM}")),
|
||||
(
|
||||
@@ -1226,3 +1230,80 @@ async fn test_single_job_read_authorization(db: Pool<Postgres>) -> anyhow::Resul
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `get_result_shape` outlines a result too large to send inline: the viewer draws one row per
|
||||
/// listed element and reads each one through `get_result?json_path=<path>.<index>`, so the cap,
|
||||
/// the element order and the path handling are what it relies on.
|
||||
#[sqlx::test(fixtures("base"))]
|
||||
async fn test_result_shape(db: Pool<Postgres>) -> anyhow::Result<()> {
|
||||
initialize_tracing().await;
|
||||
let job = "99999999-9999-9999-9999-999999999999";
|
||||
sqlx::query(
|
||||
"INSERT INTO v2_job (id, workspace_id, created_by, permissioned_as, permissioned_as_email,
|
||||
kind, script_lang, tag)
|
||||
VALUES ($1::uuid, 'test-workspace', 'test-user', 'u/test-user', 'test@windmill.dev',
|
||||
'script', 'bun', 'bun')",
|
||||
)
|
||||
.bind(job)
|
||||
.execute(&db)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"INSERT INTO v2_job_completed (id, workspace_id, duration_ms, status, result)
|
||||
SELECT $1::uuid, 'test-workspace', 1, 'success'::job_status, jsonb_build_object(
|
||||
'render_all',
|
||||
(SELECT jsonb_agg(CASE WHEN i = 1 THEN jsonb_build_object('png', 'aGVsbG8=')
|
||||
ELSE jsonb_build_object('n', i) END ORDER BY i)
|
||||
FROM generate_series(1, 105) AS i))",
|
||||
)
|
||||
.bind(job)
|
||||
.execute(&db)
|
||||
.await?;
|
||||
|
||||
let server = ApiServer::start(db.clone()).await?;
|
||||
let base = format!(
|
||||
"http://localhost:{}/api/w/test-workspace/jobs_u/completed/get_result_shape/{job}",
|
||||
server.addr.port()
|
||||
);
|
||||
let shape = |query: &'static str| {
|
||||
let url = format!("{base}{query}");
|
||||
async move {
|
||||
let resp = client()
|
||||
.get(url)
|
||||
.header("Authorization", "Bearer SECRET_TOKEN")
|
||||
.send()
|
||||
.await
|
||||
.expect("request");
|
||||
(resp.status(), resp.text().await.expect("body"))
|
||||
}
|
||||
};
|
||||
|
||||
let (status, body) = shape("").await;
|
||||
assert_eq!(status, 200, "{body}");
|
||||
let root: serde_json::Value = serde_json::from_str(&body)?;
|
||||
assert_eq!(root["type"], "object");
|
||||
assert_eq!(root["keys"], serde_json::json!(["render_all"]));
|
||||
assert!(root.get("items").is_none(), "{body}");
|
||||
|
||||
let (status, body) = shape("?json_path=render_all").await;
|
||||
assert_eq!(status, 200, "{body}");
|
||||
let list: serde_json::Value = serde_json::from_str(&body)?;
|
||||
assert_eq!(list["type"], "array");
|
||||
assert_eq!(list["item_count"], 105);
|
||||
let items = list["items"].as_array().expect("items");
|
||||
assert_eq!(items.len(), 100);
|
||||
assert_eq!(items[0]["keys"], serde_json::json!(["png"]));
|
||||
assert_eq!(items[0]["length"], r#"{"png": "aGVsbG8="}"#.len());
|
||||
assert_eq!(items[1]["keys"], serde_json::json!(["n"]));
|
||||
|
||||
let (status, body) = shape("?json_path=render_all.0").await;
|
||||
assert_eq!(status, 200, "{body}");
|
||||
assert_eq!(
|
||||
serde_json::from_str::<serde_json::Value>(&body)?["keys"],
|
||||
serde_json::json!(["png"])
|
||||
);
|
||||
|
||||
let (status, body) = shape("?json_path=missing").await;
|
||||
assert_eq!(status, 404, "{body}");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -367,7 +367,7 @@ fn extract_domain_from_route(
|
||||
/// exports) and credential minting (`job_view_token`) are deliberately absent — those are
|
||||
/// `jobs:read`. Keep by-id read routes here in sync as they are added, or a run token
|
||||
/// loses the ability to follow its own run through them.
|
||||
const RUN_WHITELISTED_GET_PATHS: [&'static str; 34] = [
|
||||
const RUN_WHITELISTED_GET_PATHS: [&'static str; 35] = [
|
||||
"jobs_u/get_flow/",
|
||||
"jobs_u/get_root_job_id/",
|
||||
"jobs_u/get/",
|
||||
@@ -381,6 +381,7 @@ const RUN_WHITELISTED_GET_PATHS: [&'static str; 34] = [
|
||||
"jobs_u/completed/get/",
|
||||
"jobs_u/completed/get_result/",
|
||||
"jobs_u/completed/get_result_maybe/",
|
||||
"jobs_u/completed/get_result_shape/",
|
||||
"jobs_u/completed/get_timing/",
|
||||
"jobs_u/dispatch_events/",
|
||||
"jobs_u/getupdate/",
|
||||
@@ -554,7 +555,7 @@ fn app_embed_job_route_allowed(suffix: &str) -> bool {
|
||||
// `get_root_job_id` is intentionally absent: its handler has no access check at
|
||||
// all (returns any job's root id by id) and the app never calls it, so denying
|
||||
// it costs nothing and avoids leaking a foreign job's flow lineage.
|
||||
const ALLOWED: [&str; 15] = [
|
||||
const ALLOWED: [&str; 16] = [
|
||||
"jobs_u/get/",
|
||||
"jobs_u/getupdate/",
|
||||
"jobs_u/getupdate_sse/",
|
||||
@@ -568,6 +569,7 @@ fn app_embed_job_route_allowed(suffix: &str) -> bool {
|
||||
"jobs_u/completed/get/",
|
||||
"jobs_u/completed/get_result/",
|
||||
"jobs_u/completed/get_result_maybe/",
|
||||
"jobs_u/completed/get_result_shape/",
|
||||
"jobs_u/completed/get_timing/",
|
||||
"jobs_u/queue/cancel/",
|
||||
];
|
||||
@@ -595,7 +597,7 @@ fn resource_metadata_route_allowed(suffix: &str) -> bool {
|
||||
/// a direct `require_job_within_read_scope`. `jobs/result_by_id/` is absent because it
|
||||
/// resolves a node up through the enclosing flows, past the job the check admitted.
|
||||
/// A route added here without that check serves a path-scoped token every job.
|
||||
const READ_PATH_SCOPED_BY_ID_PATHS: [&'static str; 27] = [
|
||||
const READ_PATH_SCOPED_BY_ID_PATHS: [&'static str; 28] = [
|
||||
"jobs_u/get/",
|
||||
"jobs_u/get_logs/",
|
||||
"jobs_u/get_completed_logs_tail/",
|
||||
@@ -607,6 +609,7 @@ const READ_PATH_SCOPED_BY_ID_PATHS: [&'static str; 27] = [
|
||||
"jobs_u/completed/get/",
|
||||
"jobs_u/completed/get_result/",
|
||||
"jobs_u/completed/get_result_maybe/",
|
||||
"jobs_u/completed/get_result_shape/",
|
||||
"jobs_u/completed/get_timing/",
|
||||
"jobs_u/dispatch_events/",
|
||||
"jobs_u/getupdate/",
|
||||
@@ -1364,13 +1367,17 @@ mod tests {
|
||||
#[test]
|
||||
fn jobs_run_reads_are_limited_to_the_by_id_poll_routes() {
|
||||
let job = "/api/w/test/jobs_u/completed/get_result/019ff012-6b1e-0d6b-fc0d-0c85d34d9cec";
|
||||
let shape =
|
||||
"/api/w/test/jobs_u/completed/get_result_shape/019ff012-6b1e-0d6b-fc0d-0c85d34d9cec";
|
||||
let list = "/api/w/test/jobs/list";
|
||||
for scope in ["jobs:run", "jobs:run:scripts:u/admin/script"] {
|
||||
// Following the run it started stays available...
|
||||
assert!(
|
||||
check_route_access(&[scope.to_string()], job, "GET").is_ok(),
|
||||
"{scope} must reach the by-id job poll routes"
|
||||
);
|
||||
for route in [job, shape] {
|
||||
assert!(
|
||||
check_route_access(&[scope.to_string()], route, "GET").is_ok(),
|
||||
"{scope} must reach the by-id job poll route {route}"
|
||||
);
|
||||
}
|
||||
// ...but a run grant is not a licence to enumerate the workspace's jobs.
|
||||
assert!(
|
||||
check_route_access(&[scope.to_string()], list, "GET").is_err(),
|
||||
@@ -1468,6 +1475,7 @@ mod tests {
|
||||
for route in [
|
||||
format!("jobs_u/get/{id}"),
|
||||
format!("jobs_u/completed/get_result/{id}"),
|
||||
format!("jobs_u/completed/get_result_shape/{id}"),
|
||||
format!("jobs_u/getupdate_sse/{id}"),
|
||||
format!("jobs_u/flow/approval_info/{id}"),
|
||||
"jobs/list".to_string(),
|
||||
|
||||
@@ -20267,6 +20267,64 @@ paths:
|
||||
application/json:
|
||||
schema: {}
|
||||
|
||||
/w/{workspace}/jobs_u/completed/get_result_shape/{id}:
|
||||
get:
|
||||
summary: get the outline of a completed job's result
|
||||
description: |
|
||||
The JSON length and keys of a completed job's result, or of the value at `json_path`
|
||||
in it, and the same for each of the first 100 elements of a list. Lets a viewer offer
|
||||
the parts of a result too large to send inline without reading all of it.
|
||||
operationId: getCompletedJobResultShape
|
||||
tags:
|
||||
- job
|
||||
parameters:
|
||||
- $ref: "#/components/parameters/WorkspaceId"
|
||||
- $ref: "#/components/parameters/JobId"
|
||||
- name: json_path
|
||||
description: dot-separated path into the result, as for getCompletedJobResult
|
||||
in: query
|
||||
schema:
|
||||
type: string
|
||||
responses:
|
||||
"200":
|
||||
description: result outline
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
type:
|
||||
type: string
|
||||
description: the JSON type of the value (object, array, string, ...)
|
||||
length:
|
||||
type: integer
|
||||
description: characters in the value's JSON text
|
||||
keys:
|
||||
type: array
|
||||
description: up to 20 of the keys, for an object
|
||||
items:
|
||||
type: string
|
||||
item_count:
|
||||
type: integer
|
||||
description: the number of elements, for a list
|
||||
items:
|
||||
type: array
|
||||
description: the first 100 elements, for a list
|
||||
items:
|
||||
type: object
|
||||
properties:
|
||||
length:
|
||||
type: integer
|
||||
keys:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
required:
|
||||
- length
|
||||
required:
|
||||
- type
|
||||
- length
|
||||
|
||||
/w/{workspace}/jobs_u/completed/get_result_maybe/{id}:
|
||||
get:
|
||||
summary: get completed job result if job is completed
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -291,7 +291,10 @@ pub fn workspaced_service() -> Router {
|
||||
)
|
||||
.route("/add_batch_jobs/{n}", post(add_batch_jobs))
|
||||
.route("/run/preview_flow", post(run_preview_flow_job))
|
||||
.route("/run/flow_test/{*path}", post(crate::flow_test::run_flow_test))
|
||||
.route(
|
||||
"/run/flow_test/{*path}",
|
||||
post(crate::flow_test::run_flow_test),
|
||||
)
|
||||
.route("/run/agent/{*path}", post(crate::agent_runs::run_agent))
|
||||
.route(
|
||||
"/run_wait_result/preview_flow",
|
||||
@@ -476,6 +479,10 @@ pub fn workspace_unauthed_service() -> Router {
|
||||
.route("/get_flow_debug_info/{id}", get(get_flow_job_debug_info))
|
||||
.route("/completed/get/{id}", get(get_completed_job))
|
||||
.route("/completed/get_result/{id}", get(get_completed_job_result))
|
||||
.route(
|
||||
"/completed/get_result_shape/{id}",
|
||||
get(get_completed_job_result_shape),
|
||||
)
|
||||
.route(
|
||||
"/completed/get_result_maybe/{id}",
|
||||
get(get_completed_job_result_maybe),
|
||||
@@ -11428,7 +11435,8 @@ pub(crate) async fn push_preview_flow_job(
|
||||
"UPDATE v2_job_status SET flow_status = jsonb_set(flow_status, '{test_subflows}', $2)
|
||||
WHERE id = $1",
|
||||
uuid,
|
||||
sqlx::types::Json(test_subflows) as sqlx::types::Json<HashMap<String, serde_json::Value>>
|
||||
sqlx::types::Json(test_subflows)
|
||||
as sqlx::types::Json<HashMap<String, serde_json::Value>>
|
||||
)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
@@ -13067,6 +13075,127 @@ async fn get_completed_job_result(
|
||||
Ok(Json(raw_result.result).into_response())
|
||||
}
|
||||
|
||||
/// Elements listed by `get_result_shape`; the rest of a longer list is counted only.
|
||||
const RESULT_SHAPE_MAX_ITEMS: i64 = 100;
|
||||
/// Keys listed per object by `get_result_shape`.
|
||||
const RESULT_SHAPE_MAX_KEYS: i64 = 20;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct ResultShapeQuery {
|
||||
json_path: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
struct ResultShapeItem {
|
||||
length: i32,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
keys: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct ResultShape {
|
||||
#[serde(rename = "type")]
|
||||
type_: String,
|
||||
length: i32,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
keys: Option<Vec<String>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
item_count: Option<i32>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
items: Option<Vec<ResultShapeItem>>,
|
||||
}
|
||||
|
||||
/// The outline of a result too large to send inline: its JSON length, its keys, and the same
|
||||
/// for each element of a list, so a viewer can offer each part without reading the whole.
|
||||
async fn get_completed_job_result_shape(
|
||||
OptViewToken(view_token): OptViewToken,
|
||||
OptAuthed(opt_authed): OptAuthed,
|
||||
opt_tokened: OptTokened,
|
||||
Extension(db): Extension<DB>,
|
||||
Extension(user_db): Extension<UserDB>,
|
||||
Path((w_id, id)): Path<(String, Uuid)>,
|
||||
Query(ResultShapeQuery { json_path }): Query<ResultShapeQuery>,
|
||||
) -> JsonResult<ResultShape> {
|
||||
let tags = opt_authed
|
||||
.as_ref()
|
||||
.map(|authed| get_scope_tags(authed))
|
||||
.flatten();
|
||||
let path: Vec<&str> = json_path
|
||||
.as_deref()
|
||||
.filter(|p| !p.is_empty())
|
||||
.map(|p| p.split('.').collect())
|
||||
.unwrap_or_default();
|
||||
let row = sqlx::query!(
|
||||
r#"WITH v AS (
|
||||
SELECT c.result #> $3 AS r, created_by
|
||||
FROM v2_job_completed c JOIN v2_job USING (id)
|
||||
WHERE c.id = $1 AND c.workspace_id = $2 AND ($4::text[] IS NULL OR tag = ANY($4))
|
||||
)
|
||||
SELECT
|
||||
created_by AS "created_by!",
|
||||
jsonb_typeof(r) AS "type",
|
||||
length(r::text) AS "length",
|
||||
CASE WHEN jsonb_typeof(r) = 'object' THEN
|
||||
ARRAY(SELECT jsonb_object_keys(r) LIMIT $6)
|
||||
END AS "keys",
|
||||
CASE WHEN jsonb_typeof(r) = 'array' THEN jsonb_array_length(r) END AS "item_count",
|
||||
CASE WHEN jsonb_typeof(r) = 'array' THEN (
|
||||
SELECT jsonb_agg(jsonb_build_object(
|
||||
'length', length(e::text),
|
||||
'keys', CASE WHEN jsonb_typeof(e) = 'object' THEN
|
||||
to_jsonb(ARRAY(SELECT jsonb_object_keys(e) LIMIT $6))
|
||||
END
|
||||
) ORDER BY i)
|
||||
FROM jsonb_array_elements(r) WITH ORDINALITY AS t(e, i)
|
||||
WHERE i <= $5
|
||||
) END AS "items: sqlx::types::Json<Vec<ResultShapeItem>>"
|
||||
FROM v"#,
|
||||
id,
|
||||
&w_id,
|
||||
&path as &[&str],
|
||||
tags.as_ref().map(|v| v.as_slice()) as Option<&[&str]>,
|
||||
RESULT_SHAPE_MAX_ITEMS,
|
||||
RESULT_SHAPE_MAX_KEYS,
|
||||
)
|
||||
.fetch_optional(&db)
|
||||
.await?;
|
||||
let row = not_found_if_none(row, "Completed Job", id.to_string())?;
|
||||
|
||||
require_opt_authed_job_read_access(
|
||||
&db,
|
||||
&user_db,
|
||||
&opt_authed,
|
||||
&w_id,
|
||||
&id,
|
||||
&row.created_by,
|
||||
view_token.as_deref(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
let Some(type_) = row.r#type else {
|
||||
return Err(Error::NotFound(format!(
|
||||
"no value at {} in the result of job {id}",
|
||||
json_path.unwrap_or_default()
|
||||
)));
|
||||
};
|
||||
log_job_view(
|
||||
&db,
|
||||
opt_authed.as_ref(),
|
||||
opt_tokened.token.as_deref(),
|
||||
&w_id,
|
||||
&id,
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(Json(ResultShape {
|
||||
type_,
|
||||
length: row.length.unwrap_or(0),
|
||||
keys: row.keys,
|
||||
item_count: row.item_count,
|
||||
items: row.items.map(|items| items.0),
|
||||
}))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct CountByTagQuery {
|
||||
horizon_secs: Option<i64>,
|
||||
|
||||
Generated
+9
@@ -8763,6 +8763,15 @@ of the shapes below is shown as JSON.
|
||||
Each shape is an object with that one key (plus \`filename\` for a file, and an optional \`storage\` for
|
||||
\`s3\`). A result carrying any other key beside it is shown as JSON.
|
||||
|
||||
## Large results
|
||||
|
||||
A result stored above about 90 KB is not sent with the run: the run page and the editors offer it
|
||||
as a JSON download, with a Load button that draws it on request. A \`render_all\` lists up to 100 of
|
||||
its elements with their type and size, counts the rest, and loads them ten at a time. To have a large result previewed without a
|
||||
click, write the content to the workspace storage and return \`{ "s3": "path/to/key" }\`, which is
|
||||
previewed by type; for a generated image, also keep it small (a JPEG, or fewer pixels) when it only
|
||||
needs to be looked at.
|
||||
|
||||
## Choosing one
|
||||
|
||||
A chart answers a question at a glance: a trend over time (line), a comparison across categories
|
||||
|
||||
@@ -30,11 +30,17 @@
|
||||
PanelRightOpen,
|
||||
Table2,
|
||||
Braces,
|
||||
Brackets,
|
||||
Highlighter,
|
||||
ArrowDownFromLine,
|
||||
Database,
|
||||
Eye,
|
||||
FileImage,
|
||||
FileText,
|
||||
Loader2
|
||||
} from 'lucide-svelte'
|
||||
import Tooltip from './Tooltip.svelte'
|
||||
import MeltTooltip from './meltComponents/Tooltip.svelte'
|
||||
import DataTestsResult from './DataTestsResult.svelte'
|
||||
import Portal from '$lib/components/Portal.svelte'
|
||||
import DisplayResultControlBar from './DisplayResultControlBar.svelte'
|
||||
@@ -61,9 +67,7 @@
|
||||
import MapResult from './MapResult.svelte'
|
||||
import ChartResult from './display/ChartResult.svelte'
|
||||
import { isChartResult } from './display/displayCatalog'
|
||||
import DownloadCsv from './table/DownloadCsv.svelte'
|
||||
import { convertJsonToCsv } from './table/tableUtils'
|
||||
import Tooltip from './Tooltip.svelte'
|
||||
import HighlightTheme from './HighlightTheme.svelte'
|
||||
import type { DisplayResultUi } from './custom_ui'
|
||||
import { getContext, hasContext, createEventDispatcher, onDestroy, untrack } from 'svelte'
|
||||
@@ -298,8 +302,12 @@
|
||||
}
|
||||
$effect(() => {
|
||||
tooBigFilename = undefined
|
||||
tooBigInfo = undefined
|
||||
const apiPath = result === 'WINDMILL_TOO_BIG' ? resultApiPath : undefined
|
||||
if (!apiPath) return
|
||||
// The placeholder is drawn again (the view showed another result, then this one), so the
|
||||
// elements loaded before are no longer shown: Load starts over from the first.
|
||||
if (!untrack(() => tooBigLoaded.loading)) tooBigLoaded = { values: [], loading: false }
|
||||
let stale = false
|
||||
fetchResultAt(apiPath, 'file.filename').then(
|
||||
(name) => {
|
||||
@@ -307,19 +315,173 @@
|
||||
},
|
||||
() => {}
|
||||
)
|
||||
// `nodeId` reads a flow step's collected results, which have no row of their own.
|
||||
if (workspaceId && jobId && !nodeId) {
|
||||
readTooBigShape(workspaceId, jobId).then(
|
||||
(shape) => {
|
||||
if (!stale && shape) tooBigInfo = { apiPath, ...shape }
|
||||
},
|
||||
() => {}
|
||||
)
|
||||
}
|
||||
return () => (stale = true)
|
||||
})
|
||||
type ResultShape = {
|
||||
type: string
|
||||
length: number
|
||||
keys?: string[]
|
||||
item_count?: number
|
||||
items?: { length: number; keys?: string[] }[]
|
||||
}
|
||||
/** A part of a large result: the image of an image result (read under its key and wrapped
|
||||
* back), or an element of a `render_all`. */
|
||||
type TooBigPart = {
|
||||
path: string
|
||||
index?: number
|
||||
length: number
|
||||
imageKind?: string
|
||||
wrap?: string
|
||||
}
|
||||
/** `render_all` elements read per click, and listed before the rest are counted */
|
||||
const TOO_BIG_PAGE_SIZE = 10
|
||||
const TOO_BIG_LISTED = 5
|
||||
type TooBigShape = {
|
||||
length: number
|
||||
/** The image of an image result, or the `render_all` elements the shape lists (the first 100) */
|
||||
parts: TooBigPart[]
|
||||
/** Element count, when the result is a list or a `render_all` */
|
||||
itemCount?: number
|
||||
renderAll?: boolean
|
||||
}
|
||||
let tooBigInfo = $state<({ apiPath: string } & TooBigShape) | undefined>(undefined)
|
||||
// Read only on a click: a view is mounted for every loop iteration stepped through and every
|
||||
// run card of a chat, and each would download the result. Tied to the result it was read
|
||||
// from, so a new result never shows the previous one's elements.
|
||||
type TooBigLoaded = {
|
||||
apiPath?: string
|
||||
shape?: TooBigShape
|
||||
/** The `render_all` elements read so far */
|
||||
values: unknown[]
|
||||
loading: boolean
|
||||
}
|
||||
let tooBigLoaded = $state<TooBigLoaded>({ values: [], loading: false })
|
||||
function imageKindOf(keys: string[] | undefined): string | undefined {
|
||||
return keys?.length === 1 && IMG_KINDS.includes(keys[0]) ? keys[0] : undefined
|
||||
}
|
||||
async function fetchResultShape(
|
||||
workspace: string,
|
||||
id: string,
|
||||
jsonPath?: string
|
||||
): Promise<ResultShape | undefined> {
|
||||
const query = jsonPath ? `?json_path=${jsonPath}` : ''
|
||||
const r = await fetchViaClient(
|
||||
appendViewToken(`/w/${workspace}/jobs_u/completed/get_result_shape/${id}${query}`)
|
||||
)
|
||||
return r.ok ? r.json() : undefined
|
||||
}
|
||||
async function readTooBigShape(workspace: string, id: string): Promise<TooBigShape | undefined> {
|
||||
const root = await fetchResultShape(workspace, id)
|
||||
if (!root) return
|
||||
const rootImage = imageKindOf(root.keys)
|
||||
if (rootImage) {
|
||||
return {
|
||||
length: root.length,
|
||||
parts: [{ path: rootImage, length: root.length, imageKind: rootImage, wrap: rootImage }]
|
||||
}
|
||||
}
|
||||
// Only a `render_all` is split into its elements, as it is drawn element by element when
|
||||
// small. A bare list is drawn as a table, which needs every row, so it loads whole.
|
||||
if (!(root.keys?.length === 1 && root.keys[0] === 'render_all')) {
|
||||
return {
|
||||
length: root.length,
|
||||
parts: [],
|
||||
itemCount: root.type === 'array' ? root.item_count : undefined
|
||||
}
|
||||
}
|
||||
const list = await fetchResultShape(workspace, id, 'render_all')
|
||||
// A `render_all` that is not a list, or a list whose shape could not be read, loads whole
|
||||
if (list?.type !== 'array' || list.item_count === undefined) {
|
||||
return { length: root.length, parts: [] }
|
||||
}
|
||||
const items = list.items ?? []
|
||||
return {
|
||||
length: root.length,
|
||||
itemCount: list.item_count,
|
||||
renderAll: true,
|
||||
parts: items.map((item, index) => ({
|
||||
path: `render_all.${index}`,
|
||||
index,
|
||||
length: item.length,
|
||||
imageKind: imageKindOf(item.keys)
|
||||
}))
|
||||
}
|
||||
}
|
||||
function formatSize(chars: number): string {
|
||||
return chars >= 1_000_000
|
||||
? `${(chars / 1_000_000).toFixed(1)} MB`
|
||||
: `${Math.max(1, Math.round(chars / 1000))} KB`
|
||||
}
|
||||
/** Size of the `render_all` elements `from` to `to`, when the shape lists them all */
|
||||
function tooBigPageSize(shape: TooBigShape, from: number, to: number): number | undefined {
|
||||
if (shape.parts.length < to) return undefined
|
||||
return shape.parts.slice(from, to).reduce((n, p) => n + p.length, 0)
|
||||
}
|
||||
/** Reads the whole result, its image, or the next page of its `render_all`, and draws what was
|
||||
* read in place of the placeholder, as a result under the limit is drawn (Pretty/JSON toggle
|
||||
* included). A new result from the parent wins. */
|
||||
async function loadTooBig(apiPath: string, shape: TooBigShape | undefined) {
|
||||
const current: TooBigLoaded =
|
||||
tooBigLoaded.apiPath === apiPath
|
||||
? tooBigLoaded
|
||||
: { apiPath, shape, values: [], loading: false }
|
||||
if (current.loading) return
|
||||
tooBigLoaded = { ...current, loading: true }
|
||||
try {
|
||||
let next: unknown
|
||||
let values = current.values
|
||||
if (shape?.renderAll && shape.itemCount !== undefined) {
|
||||
const from = values.length
|
||||
const to = Math.min(shape.itemCount, from + TOO_BIG_PAGE_SIZE)
|
||||
const page = await Promise.all(
|
||||
Array.from({ length: to - from }, (_, i) =>
|
||||
fetchResultAt(apiPath, `render_all.${from + i}`)
|
||||
)
|
||||
)
|
||||
values = [...values, ...page]
|
||||
next = { render_all: values }
|
||||
} else {
|
||||
const part = shape?.parts[0]
|
||||
const value = part
|
||||
? await fetchResultAt(apiPath, part.path)
|
||||
: await fetchViaClient(apiPath).then((r) => {
|
||||
if (!r.ok) throw new Error(`${r.status} ${r.statusText}`)
|
||||
return r.json()
|
||||
})
|
||||
next = part?.wrap ? { [part.wrap]: value } : value
|
||||
}
|
||||
if (resultApiPath !== apiPath || tooBigLoaded.apiPath !== apiPath) return
|
||||
tooBigLoaded = { ...tooBigLoaded, values }
|
||||
result = next
|
||||
} catch (e) {
|
||||
sendUserToast(`Could not load the result: ${e instanceof Error ? e.message : e}`, true)
|
||||
} finally {
|
||||
if (tooBigLoaded.apiPath === apiPath) tooBigLoaded = { ...tooBigLoaded, loading: false }
|
||||
}
|
||||
}
|
||||
function base64ToBytes(content: string): Uint8Array<ArrayBuffer> {
|
||||
const bin = atob(content)
|
||||
// Filled byte by byte: a per-character array is several times the file's size
|
||||
const bytes = new Uint8Array(bin.length)
|
||||
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)
|
||||
return bytes
|
||||
}
|
||||
async function downloadTooBigFile(apiPath: string, name: string) {
|
||||
downloadingTooBigFile = true
|
||||
try {
|
||||
const content = await fetchResultAt(apiPath, 'file.content')
|
||||
if (typeof content !== 'string' || !content) throw new Error('the result has no file content')
|
||||
const bin = atob(content)
|
||||
// Filled byte by byte: a per-character array is several times the file's size
|
||||
const bytes = new Uint8Array(bin.length)
|
||||
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)
|
||||
// A blob, not a data: URL, which browsers cap well below a large file's size
|
||||
downloadBlob(new Blob([bytes]), name)
|
||||
downloadBlob(new Blob([base64ToBytes(content)]), name)
|
||||
} catch (e) {
|
||||
sendUserToast(`Download failed: ${e instanceof Error ? e.message : e}`, true)
|
||||
} finally {
|
||||
@@ -354,8 +516,14 @@
|
||||
|
||||
let showMaterializedPreview = $state(true)
|
||||
let is_render_all = $state(false)
|
||||
/** `roughSizeOfObject` of the result: UTF-16 bytes, two per character. */
|
||||
let loadedResultBytes = $state(0)
|
||||
let download_as_csv = $state(false)
|
||||
function inferResultKind(result: any) {
|
||||
// Reset first: the same view is reused across results (the runs page's preview), and the
|
||||
// early returns below would keep a previous `render_all` or table's flags.
|
||||
is_render_all = false
|
||||
download_as_csv = false
|
||||
if (typeof result === 'string' && result.match(/s3:\/\/[^/]*\/.+/)) {
|
||||
largeObject = true
|
||||
return 's3object'
|
||||
@@ -393,7 +561,8 @@
|
||||
// same too-big handling as any other oversized result.
|
||||
if (parseAgentResult(result)) {
|
||||
is_render_all = false
|
||||
largeObject = roughSizeOfObject(result) > DISPLAY_MAX_SIZE
|
||||
loadedResultBytes = roughSizeOfObject(result)
|
||||
largeObject = loadedResultBytes > DISPLAY_MAX_SIZE
|
||||
return 'aiagent'
|
||||
}
|
||||
|
||||
@@ -401,10 +570,15 @@
|
||||
keys.length == 1 && keys.includes('render_all') && Array.isArray(result['render_all'])
|
||||
|
||||
let size = roughSizeOfObject(result)
|
||||
loadedResultBytes = size
|
||||
console.debug('size of object', size)
|
||||
// Otherwise, check if the result is too large (10kb) for json
|
||||
|
||||
if (size > TABLE_MAX_SIZE) {
|
||||
// An image, file, pdf or html result is drawn whatever its size
|
||||
if (
|
||||
size > TABLE_MAX_SIZE &&
|
||||
!(keys.length === 1 && NO_SIZE_LIMIT_KINDS.includes(keys[0]))
|
||||
) {
|
||||
largeObject = true
|
||||
if (Array.isArray(result) && isTableRowObject(result)) {
|
||||
download_as_csv = true
|
||||
@@ -888,37 +1062,79 @@
|
||||
{:else if is_render_all}
|
||||
<div class="flex flex-col w-full gap-2">
|
||||
{#if !noControls}
|
||||
<div class="text-primary text-sm">
|
||||
<ToggleButtonGroup
|
||||
selected={globalForceJson ? 'json' : 'pretty'}
|
||||
on:selected={(ev) => {
|
||||
globalForceJson = ev.detail === 'json'
|
||||
}}
|
||||
>
|
||||
{#snippet children({ item })}
|
||||
<ToggleButton value="pretty" label="Pretty" icon={Highlighter} {item} />
|
||||
<ToggleButton value="json" label="JSON" icon={Braces} {item} />
|
||||
{/snippet}
|
||||
</ToggleButtonGroup>
|
||||
</div>
|
||||
{/if}
|
||||
<div class="flex flex-col w-full gap-10">
|
||||
{#each result['render_all'] as res, i}
|
||||
<DisplayResult
|
||||
{noControls}
|
||||
result={res}
|
||||
resultPath={resultPath ? [...resultPath, 'render_all', i] : null}
|
||||
{markupTrust}
|
||||
<!-- Wraps, so in a narrow pane (a flow step's node panel) the toolbar takes its own line
|
||||
instead of running out of the pane -->
|
||||
<div class="flex flex-row flex-wrap items-center justify-between gap-2">
|
||||
<div class="text-primary text-sm">
|
||||
<ToggleButtonGroup
|
||||
selected={globalForceJson ? 'json' : 'pretty'}
|
||||
on:selected={(ev) => {
|
||||
globalForceJson = ev.detail === 'json'
|
||||
}}
|
||||
>
|
||||
{#snippet children({ item })}
|
||||
<ToggleButton value="pretty" label="Pretty" icon={Highlighter} {item} />
|
||||
<ToggleButton value="json" label="JSON" icon={Braces} {item} />
|
||||
{/snippet}
|
||||
</ToggleButtonGroup>
|
||||
</div>
|
||||
<DisplayResultControlBar
|
||||
{customUi}
|
||||
{filename}
|
||||
{disableExpand}
|
||||
{workspaceId}
|
||||
{jobId}
|
||||
{nodeId}
|
||||
{workspaceId}
|
||||
{appPath}
|
||||
forceJson={globalForceJson}
|
||||
hideAsJson={true}
|
||||
{result}
|
||||
{disableTooltips}
|
||||
{disableExpand}
|
||||
on:open-drawer={() => openDrawer()}
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
<!-- A size container: below 400px (a flow step's node panel) the element cards drop their
|
||||
border and padding, whose width an element as wide as the pane would no longer fit in -->
|
||||
<div class="flex flex-col w-full gap-3 [container-type:inline-size]">
|
||||
{#each result['render_all'] as res, i}
|
||||
<!-- Drops the 160px floor a result pane keeps, so a short element hugs its content -->
|
||||
<div
|
||||
class="min-w-0 [@container(min-width:400px)]:rounded-md [@container(min-width:400px)]:border [@container(min-width:400px)]:p-3 [&>div]:min-h-0 [&>div>div.grow]:overflow-x-auto [&>div>div.grow]:pb-2"
|
||||
>
|
||||
<DisplayResult
|
||||
{noControls}
|
||||
result={res}
|
||||
resultPath={resultPath ? [...resultPath, 'render_all', i] : null}
|
||||
{markupTrust}
|
||||
{filename}
|
||||
{disableExpand}
|
||||
{jobId}
|
||||
{nodeId}
|
||||
{workspaceId}
|
||||
{appPath}
|
||||
forceJson={globalForceJson}
|
||||
hideAsJson={true}
|
||||
/>
|
||||
</div>
|
||||
{/each}
|
||||
{#if tooBigLoaded.apiPath === resultApiPath && tooBigLoaded.shape?.itemCount !== undefined && tooBigLoaded.values.length < tooBigLoaded.shape.itemCount}
|
||||
{@const shape = tooBigLoaded.shape}
|
||||
{@const done = tooBigLoaded.values.length}
|
||||
{@const next = Math.min(shape.itemCount ?? 0, done + TOO_BIG_PAGE_SIZE)}
|
||||
{@const nextSize = tooBigPageSize(shape, done, next)}
|
||||
<div class="flex flex-row flex-wrap items-center justify-center gap-3 py-2">
|
||||
<span class="text-xs text-secondary">{done} of {shape.itemCount} loaded</span>
|
||||
<Button
|
||||
variant="default"
|
||||
unifiedSize="sm"
|
||||
disabled={tooBigLoaded.loading}
|
||||
startIcon={{ icon: tooBigLoaded.loading ? Loader2 : Eye }}
|
||||
onclick={() => {
|
||||
if (resultApiPath) loadTooBig(resultApiPath, shape)
|
||||
}}
|
||||
>
|
||||
Load {next - done} more{nextSize ? ` (${formatSize(nextSize)})` : ''}
|
||||
</Button>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{:else if resultKind === 'nondisplayable'}
|
||||
@@ -1445,50 +1661,206 @@
|
||||
>
|
||||
</div>
|
||||
{:else}
|
||||
{#if tooBigFilename && resultApiPath}
|
||||
<div class="flex">
|
||||
<Button
|
||||
onclick={() => downloadTooBigFile(resultApiPath!, tooBigFilename!)}
|
||||
disabled={downloadingTooBigFile}
|
||||
startIcon={{ icon: Download }}
|
||||
variant="subtle"
|
||||
unifiedSize="sm"
|
||||
>
|
||||
Download {tooBigFilename}
|
||||
</Button>
|
||||
</div>
|
||||
{/if}
|
||||
{#if largeObject}
|
||||
<div class="text-xs text-emphasis"
|
||||
>{#if resultApiPath && shouldDownloadViaClient()}
|
||||
<button onclick={() => downloadViaClient(resultApiPath!, resultDownloadName)}>
|
||||
Download {filename ? '' : 'as JSON'}
|
||||
</button>
|
||||
{@const notSent = result === 'WINDMILL_TOO_BIG'}
|
||||
{@const info = tooBigInfo?.apiPath === resultApiPath ? tooBigInfo : undefined}
|
||||
{@const loaded = tooBigLoaded.apiPath === resultApiPath ? tooBigLoaded : undefined}
|
||||
{@const size = notSent ? info?.length : loadedResultBytes / 2}
|
||||
<!-- Not beside this component's own toolbar, whose download icon saves the same JSON. An
|
||||
external toolbar may have no download (the flow output picker's mock), so it keeps it. -->
|
||||
{@const toolbarDownloads =
|
||||
toolbarLocation === 'self' && customUi?.disableDownload !== true}
|
||||
{#snippet downloadJson(variant: 'default' | 'subtle')}
|
||||
{#if resultApiPath && shouldDownloadViaClient()}
|
||||
<Button
|
||||
onclick={() => downloadViaClient(resultApiPath!, resultDownloadName)}
|
||||
startIcon={{ icon: Download }}
|
||||
{variant}
|
||||
unifiedSize="sm"
|
||||
>
|
||||
Download JSON
|
||||
</Button>
|
||||
{:else}
|
||||
<a download={resultDownloadName} href={resultDownloadHref}>
|
||||
Download {filename ? '' : 'as JSON'}
|
||||
</a>
|
||||
<Button
|
||||
href={resultDownloadHref}
|
||||
download={resultDownloadName}
|
||||
startIcon={{ icon: Download }}
|
||||
{variant}
|
||||
unifiedSize="sm"
|
||||
>
|
||||
Download JSON
|
||||
</Button>
|
||||
{/if}
|
||||
{#if download_as_csv}
|
||||
<DownloadCsv
|
||||
getContent={() => convertJsonToCsv(result)}
|
||||
customText="Download as CSV"
|
||||
/>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div class="mt-1 mb-2">
|
||||
<Alert
|
||||
size="xs"
|
||||
title="Large result detected"
|
||||
type="warning"
|
||||
tooltip="We recommend using persistent object storage for large result. See docs for setting up an object storage service integration using s3 or any other s3 compatible services."
|
||||
documentationLink="https://www.windmill.dev/docs/core_concepts/persistent_storage#object-storage-for-large-data-s3-r2-minio-azure-blob"
|
||||
/>
|
||||
</div>
|
||||
{/snippet}
|
||||
{#if notSent}
|
||||
<!-- One placeholder for any result over the limit: the elements of a `render_all`,
|
||||
or the whole result as one row. Loading draws it as a result under the limit. -->
|
||||
{@const parts = info?.parts ?? []}
|
||||
{@const count = info?.renderAll ? (info.itemCount ?? 0) : 0}
|
||||
{@const firstPage = Math.min(count, TOO_BIG_PAGE_SIZE)}
|
||||
{@const loadSize = info?.renderAll ? tooBigPageSize(info, 0, firstPage) : size}
|
||||
<div
|
||||
class="mt-2 mb-2 rounded-md border border-dashed px-4 py-6 flex flex-col items-center gap-4"
|
||||
>
|
||||
{#snippet partRows(rows: TooBigPart[])}
|
||||
{#each rows as part (part.path)}
|
||||
{@const Icon = part.imageKind ? FileImage : Braces}
|
||||
<li class="flex flex-row items-center gap-2 text-xs whitespace-nowrap">
|
||||
<Icon size={16} class="shrink-0 text-secondary" />
|
||||
<span class="font-medium text-emphasis"
|
||||
>{part.imageKind ? `${part.imageKind.toUpperCase()} image` : 'JSON'}</span
|
||||
>
|
||||
<span class="text-secondary">{formatSize(part.length)}</span>
|
||||
</li>
|
||||
{/each}
|
||||
{/snippet}
|
||||
<ul class="flex flex-col gap-1.5">
|
||||
{#if parts.length}
|
||||
{@render partRows(parts.slice(0, TOO_BIG_LISTED))}
|
||||
{#if Math.max(parts.length, count) > TOO_BIG_LISTED}
|
||||
{@const rest = parts.slice(TOO_BIG_LISTED)}
|
||||
{@const images = rest.filter((p) => p.imageKind).length}
|
||||
{@const json = rest.length - images}
|
||||
<!-- The shape lists the first 100 elements: the rest are only counted -->
|
||||
{@const unlisted = Math.max(
|
||||
0,
|
||||
count - Math.max(parts.length, TOO_BIG_LISTED)
|
||||
)}
|
||||
<li class="text-xs text-secondary pl-6">
|
||||
<MeltTooltip
|
||||
placement="bottom-start"
|
||||
class="underline decoration-dotted cursor-default"
|
||||
customBgClass="bg-surface-secondary w-56"
|
||||
>
|
||||
<!-- A fixed width: a box sized to its rows leaves no room for a scrollbar that
|
||||
takes width, which then wraps or scrolls them sideways -->
|
||||
+{[
|
||||
images ? `${images} ${images === 1 ? 'image' : 'images'}` : '',
|
||||
json ? `${json} JSON` : '',
|
||||
unlisted ? `${unlisted} more` : ''
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(', ')}
|
||||
{#snippet text()}
|
||||
<ul class="flex flex-col gap-1.5">
|
||||
{@render partRows(rest)}
|
||||
</ul>
|
||||
{/snippet}
|
||||
</MeltTooltip>
|
||||
</li>
|
||||
{/if}
|
||||
{:else}
|
||||
{@const Icon = tooBigFilename
|
||||
? FileText
|
||||
: info?.itemCount !== undefined
|
||||
? Brackets
|
||||
: Braces}
|
||||
<li class="flex flex-row items-center gap-2 text-xs whitespace-nowrap">
|
||||
<Icon size={16} class="shrink-0 text-secondary" />
|
||||
<span class="font-medium text-emphasis"
|
||||
>{tooBigFilename ??
|
||||
(info?.itemCount !== undefined
|
||||
? `List of ${info.itemCount} ${info.itemCount === 1 ? 'item' : 'items'}`
|
||||
: 'JSON')}</span
|
||||
>
|
||||
{#if size}
|
||||
<span class="text-secondary">{formatSize(size)}</span>
|
||||
{/if}
|
||||
</li>
|
||||
{/if}
|
||||
</ul>
|
||||
<div class="flex flex-row flex-wrap justify-center gap-2">
|
||||
<Button
|
||||
variant="default"
|
||||
unifiedSize="sm"
|
||||
disabled={!resultApiPath || loaded?.loading}
|
||||
startIcon={{ icon: loaded?.loading ? Loader2 : Eye }}
|
||||
onclick={() => {
|
||||
if (!resultApiPath) return
|
||||
loadTooBig(resultApiPath, info)
|
||||
}}
|
||||
>
|
||||
{count > TOO_BIG_PAGE_SIZE
|
||||
? `Load first ${TOO_BIG_PAGE_SIZE}`
|
||||
: count > 1
|
||||
? 'Load all'
|
||||
: 'Load'}{loadSize ? ` (${formatSize(loadSize)})` : ''}
|
||||
</Button>
|
||||
{#if tooBigFilename && resultApiPath}
|
||||
<Button
|
||||
onclick={() => downloadTooBigFile(resultApiPath!, tooBigFilename!)}
|
||||
disabled={downloadingTooBigFile}
|
||||
startIcon={{ icon: Download }}
|
||||
variant="subtle"
|
||||
unifiedSize="sm"
|
||||
>
|
||||
Download
|
||||
</Button>
|
||||
{/if}
|
||||
{#if !toolbarDownloads}
|
||||
{@render downloadJson('subtle')}
|
||||
{/if}
|
||||
</div>
|
||||
<span class="text-2xs text-secondary">
|
||||
Over the 90 KB display limit
|
||||
<Tooltip
|
||||
small
|
||||
documentationLink="https://www.windmill.dev/docs/core_concepts/persistent_storage#object-storage-for-large-data-s3-r2-minio-azure-blob"
|
||||
>
|
||||
Results over 90 KB are kept with the job but not loaded with it, so they
|
||||
appear here only after you click Load.
|
||||
<br /><br />
|
||||
For large outputs such as images, files or big tables, we recommend workspace object
|
||||
storage (S3): write the file there and return
|
||||
<code>{'{ "s3": "path/to/key" }'}</code>. The job then stores only the path,
|
||||
and the file is previewed right away, by type, with no Load step.
|
||||
</Tooltip>
|
||||
</span>
|
||||
</div>
|
||||
{:else}
|
||||
<!-- Over DISPLAY_MAX_SIZE, a table, chart or document is drawn as this JSON tree
|
||||
instead; the note says why. -->
|
||||
<div class="text-2xs text-secondary mb-2">
|
||||
Shown as JSON: over 50,000 characters
|
||||
<Tooltip
|
||||
small
|
||||
documentationLink="https://www.windmill.dev/docs/core_concepts/persistent_storage#object-storage-for-large-data-s3-r2-minio-azure-blob"
|
||||
>
|
||||
Results over 50,000 characters are shown as JSON rather than as a table, chart
|
||||
or document.
|
||||
<br /><br />
|
||||
For large outputs, we recommend workspace object storage (S3): write the file there
|
||||
and return <code>{'{ "s3": "path/to/key" }'}</code>, and the file is previewed
|
||||
by type.
|
||||
</Tooltip>
|
||||
</div>
|
||||
{/if}
|
||||
{#if !notSent && (download_as_csv || !toolbarDownloads)}
|
||||
<div class="flex flex-row gap-2 mb-2">
|
||||
{#if download_as_csv}
|
||||
<Button
|
||||
onclick={() =>
|
||||
downloadBlob(
|
||||
new Blob([convertJsonToCsv(result)], {
|
||||
type: 'text/csv;charset=utf-8;'
|
||||
}),
|
||||
'data.csv'
|
||||
)}
|
||||
startIcon={{ icon: Download }}
|
||||
variant="default"
|
||||
unifiedSize="sm"
|
||||
>
|
||||
Download CSV
|
||||
</Button>
|
||||
{/if}
|
||||
{#if !toolbarDownloads}
|
||||
{@render downloadJson('subtle')}
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
{/if}
|
||||
{#if result && result != 'WINDMILL_TOO_BIG'}
|
||||
<ObjectViewer json={result} />
|
||||
<ObjectViewer json={result} wideRows />
|
||||
{/if}
|
||||
{/if}
|
||||
{:else if typeof result === 'string' && result.length > 0}
|
||||
@@ -1527,63 +1899,64 @@
|
||||
<div class="text-primary text-xs">No result: {toJsonStr(result)}</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if !disableExpand && !noControls}
|
||||
<Drawer bind:this={jsonViewer} bind:open={drawerOpen} size="900px">
|
||||
<DrawerContent title="Expanded Result" on:close={jsonViewer.closeDrawer}>
|
||||
{#snippet actions()}
|
||||
{#if customUi?.disableDownload !== true}
|
||||
{#if resultApiPath && shouldDownloadViaClient()}
|
||||
<Button
|
||||
on:click={() => downloadViaClient(resultApiPath!, resultDownloadName)}
|
||||
startIcon={{ icon: Download }}
|
||||
variant="subtle"
|
||||
unifiedSize="md"
|
||||
>
|
||||
Download
|
||||
</Button>
|
||||
{:else}
|
||||
<Button
|
||||
download={resultDownloadName}
|
||||
href={resultDownloadHref}
|
||||
startIcon={{ icon: Download }}
|
||||
variant="subtle"
|
||||
unifiedSize="md"
|
||||
>
|
||||
Download
|
||||
</Button>
|
||||
{/if}
|
||||
<!-- Outside the result kinds above, so a `render_all` can expand too -->
|
||||
{#if !disableExpand && !noControls}
|
||||
<Drawer bind:this={jsonViewer} bind:open={drawerOpen} size="900px">
|
||||
<DrawerContent title="Expanded Result" on:close={jsonViewer.closeDrawer}>
|
||||
{#snippet actions()}
|
||||
{#if customUi?.disableDownload !== true}
|
||||
{#if resultApiPath && shouldDownloadViaClient()}
|
||||
<Button
|
||||
on:click={() => downloadViaClient(resultApiPath!, resultDownloadName)}
|
||||
startIcon={{ icon: Download }}
|
||||
variant="subtle"
|
||||
unifiedSize="md"
|
||||
>
|
||||
Download
|
||||
</Button>
|
||||
{:else}
|
||||
<Button
|
||||
download={resultDownloadName}
|
||||
href={resultDownloadHref}
|
||||
startIcon={{ icon: Download }}
|
||||
variant="subtle"
|
||||
unifiedSize="md"
|
||||
>
|
||||
Download
|
||||
</Button>
|
||||
{/if}
|
||||
<Button
|
||||
on:click={() => copyToClipboard(toJsonStr(result))}
|
||||
variant="subtle"
|
||||
unifiedSize="md"
|
||||
startIcon={{
|
||||
icon: ClipboardCopy
|
||||
}}
|
||||
>
|
||||
Copy to clipboard
|
||||
</Button>
|
||||
{/snippet}
|
||||
<DisplayResult
|
||||
{noControls}
|
||||
{result}
|
||||
{resultPath}
|
||||
{markupTrust}
|
||||
{filename}
|
||||
{jobId}
|
||||
{nodeId}
|
||||
{workspaceId}
|
||||
{appPath}
|
||||
{hideAsJson}
|
||||
{forceJson}
|
||||
disableExpand={true}
|
||||
/>
|
||||
</DrawerContent>
|
||||
</Drawer>
|
||||
{/if}
|
||||
<Button
|
||||
on:click={() => copyToClipboard(toJsonStr(result))}
|
||||
variant="subtle"
|
||||
unifiedSize="md"
|
||||
startIcon={{
|
||||
icon: ClipboardCopy
|
||||
}}
|
||||
>
|
||||
Copy to clipboard
|
||||
</Button>
|
||||
{/snippet}
|
||||
<DisplayResult
|
||||
{noControls}
|
||||
{result}
|
||||
{resultPath}
|
||||
{markupTrust}
|
||||
{filename}
|
||||
{jobId}
|
||||
{nodeId}
|
||||
{workspaceId}
|
||||
{appPath}
|
||||
{hideAsJson}
|
||||
{forceJson}
|
||||
disableExpand={true}
|
||||
/>
|
||||
</DrawerContent>
|
||||
</Drawer>
|
||||
|
||||
<Portal name="s3filepicker">
|
||||
<S3FilePicker bind:this={s3FileViewer} readOnlyMode={true} />
|
||||
</Portal>
|
||||
{/if}
|
||||
<Portal name="s3filepicker">
|
||||
<S3FilePicker bind:this={s3FileViewer} readOnlyMode={true} />
|
||||
</Portal>
|
||||
{/if}
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
nodeId?: string | undefined
|
||||
result: any
|
||||
disableTooltips?: boolean
|
||||
disableExpand?: boolean
|
||||
}
|
||||
|
||||
let {
|
||||
@@ -25,7 +26,8 @@
|
||||
jobId = undefined,
|
||||
nodeId = undefined,
|
||||
result,
|
||||
disableTooltips = false
|
||||
disableTooltips = false,
|
||||
disableExpand = false
|
||||
}: Props = $props()
|
||||
|
||||
const dispatch = createEventDispatcher()
|
||||
@@ -86,7 +88,9 @@
|
||||
<button onclick={() => copyToClipboard(toJsonStr(result))}>
|
||||
<ClipboardCopy size={14} />
|
||||
</button>
|
||||
<button onclick={() => dispatch('open-drawer')}>
|
||||
<Expand size={14} />
|
||||
</button>
|
||||
{#if !disableExpand}
|
||||
<button onclick={() => dispatch('open-drawer')}>
|
||||
<Expand size={14} />
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
@@ -51,6 +51,10 @@
|
||||
connecting?: boolean
|
||||
metaData?: Snippet<[any]>
|
||||
editKey?: Snippet<[any]>
|
||||
/** Keep each value on its key's line and widen the tree to its widest row, scrolling
|
||||
* sideways. Off, a long value wraps, which narrow panels (the flow pickers) rely on to
|
||||
* avoid a horizontal scrollbar. */
|
||||
wideRows?: boolean
|
||||
}
|
||||
|
||||
let {
|
||||
@@ -67,7 +71,8 @@
|
||||
expandedEvenOnLevel0 = undefined,
|
||||
connecting = false,
|
||||
metaData,
|
||||
editKey
|
||||
editKey,
|
||||
wideRows = false
|
||||
}: Props = $props()
|
||||
|
||||
let jsonFiltered = $state(untrack(() => json))
|
||||
@@ -281,7 +286,7 @@
|
||||
{/if}
|
||||
|
||||
{#if level == 0}
|
||||
<div class="float-right">
|
||||
{#snippet searchControl()}
|
||||
{#if searchOpen}
|
||||
<div class="px-1 relative">
|
||||
<input
|
||||
@@ -317,7 +322,21 @@
|
||||
}}
|
||||
></Button>
|
||||
{/if}
|
||||
</div>
|
||||
{/snippet}
|
||||
{#if wideRows}
|
||||
<!-- Sticky, so it stays at the right edge when a wide value scrolls the viewer sideways. No
|
||||
height, so it overlays the first line rather than taking room on it, which pushed a long
|
||||
first value onto the next line. -->
|
||||
<div class="float-right sticky right-0 z-[1] h-0 overflow-visible">
|
||||
<div class="bg-surface rounded-md">
|
||||
{@render searchControl()}
|
||||
</div>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="float-right">
|
||||
{@render searchControl()}
|
||||
</div>
|
||||
{/if}
|
||||
{/if}
|
||||
|
||||
{#if keys.length > 0}
|
||||
@@ -475,7 +494,15 @@
|
||||
|
||||
{#if level === 0}
|
||||
<ContextMenu items={menuItems}>
|
||||
{@render viewerContent()}
|
||||
{#if wideRows}
|
||||
<!-- As wide as the widest row, so a long value widens every row (and its hover) instead of
|
||||
running past it, and the sticky search button has the full width to stay in -->
|
||||
<div class="w-max min-w-full">
|
||||
{@render viewerContent()}
|
||||
</div>
|
||||
{:else}
|
||||
{@render viewerContent()}
|
||||
{/if}
|
||||
</ContextMenu>
|
||||
{:else}
|
||||
{@render viewerContent()}
|
||||
|
||||
@@ -1911,6 +1911,15 @@ of the shapes below is shown as JSON.
|
||||
Each shape is an object with that one key (plus \`filename\` for a file, and an optional \`storage\` for
|
||||
\`s3\`). A result carrying any other key beside it is shown as JSON.
|
||||
|
||||
## Large results
|
||||
|
||||
A result stored above about 90 KB is not sent with the run: the run page and the editors offer it
|
||||
as a JSON download, with a Load button that draws it on request. A \`render_all\` lists up to 100 of
|
||||
its elements with their type and size, counts the rest, and loads them ten at a time. To have a large result previewed without a
|
||||
click, write the content to the workspace storage and return \`{ "s3": "path/to/key" }\`, which is
|
||||
previewed by type; for a generated image, also keep it small (a JPEG, or fewer pixels) when it only
|
||||
needs to be looked at.
|
||||
|
||||
## Choosing one
|
||||
|
||||
A chart answers a question at a glance: a trend over time (line), a comparison across categories
|
||||
|
||||
@@ -30,6 +30,15 @@ of the shapes below is shown as JSON.
|
||||
Each shape is an object with that one key (plus `filename` for a file, and an optional `storage` for
|
||||
`s3`). A result carrying any other key beside it is shown as JSON.
|
||||
|
||||
## Large results
|
||||
|
||||
A result stored above about 90 KB is not sent with the run: the run page and the editors offer it
|
||||
as a JSON download, with a Load button that draws it on request. A `render_all` lists up to 100 of
|
||||
its elements with their type and size, counts the rest, and loads them ten at a time. To have a large result previewed without a
|
||||
click, write the content to the workspace storage and return `{ "s3": "path/to/key" }`, which is
|
||||
previewed by type; for a generated image, also keep it small (a JPEG, or fewer pixels) when it only
|
||||
needs to be looked at.
|
||||
|
||||
## Choosing one
|
||||
|
||||
A chart answers a question at a glance: a trend over time (line), a comparison across categories
|
||||
|
||||
@@ -25,6 +25,15 @@ of the shapes below is shown as JSON.
|
||||
Each shape is an object with that one key (plus `filename` for a file, and an optional `storage` for
|
||||
`s3`). A result carrying any other key beside it is shown as JSON.
|
||||
|
||||
## Large results
|
||||
|
||||
A result stored above about 90 KB is not sent with the run: the run page and the editors offer it
|
||||
as a JSON download, with a Load button that draws it on request. A `render_all` lists up to 100 of
|
||||
its elements with their type and size, counts the rest, and loads them ten at a time. To have a large result previewed without a
|
||||
click, write the content to the workspace storage and return `{ "s3": "path/to/key" }`, which is
|
||||
previewed by type; for a generated image, also keep it small (a JPEG, or fewer pixels) when it only
|
||||
needs to be looked at.
|
||||
|
||||
## Choosing one
|
||||
|
||||
A chart answers a question at a glance: a trend over time (line), a comparison across categories
|
||||
|
||||
Reference in New Issue
Block a user