Skip to content
Merged
3 changes: 3 additions & 0 deletions crates/engine/src/cmd/connection_logins.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@ pub(crate) fn resolve_keys(s: &mut Session, keys: &[(&'static str, String)]) {

#[cfg(not(target_arch = "wasm32"))]
fn resolve(s: &mut Session, only: Option<&[(&'static str, String)]>) {
if !s.policy_allows_reserved() {
return;
}
for ((kind, key), layers) in groups(s) {
if let Some(only) = only
&& !only.iter().any(|(k, database)| *k == kind && *database == key)
Expand Down
3 changes: 3 additions & 0 deletions crates/engine/src/cmd/cube.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1111,6 +1111,9 @@ fn trend_cmd(s: &mut Session, p: &Value) -> CmdResult {
// A run the app worked out: added if it is still kept (the last few are), never worked out
// again here, which would block.
if let Some(ran) = p.get("ran").filter(|v| !v.is_null()) {
if !s.policy_user() {
return Err("internal trend results are reserved for the app".into());
}
let id = ran.as_u64().ok_or("ran is the number of a run the app worked out")?;
let at = s.trend_results.iter().position(|(k, ..)| *k == id).ok_or("that trend is no longer kept: run it again")?;
let (_, rasters, dates) = s.trend_results.remove(at);
Expand Down
3 changes: 3 additions & 0 deletions crates/engine/src/cmd/embeddings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -438,6 +438,9 @@ fn series_notes(f: &emb::SeriesFound) -> Vec<String> {

/// Bytes the app read and handed over, by their id (`ran`).
fn handed(s: &mut Session, p: &Value) -> Result<Option<(u64, Vec<u8>)>, String> {
if p.get("ran").is_some_and(|v| !v.is_null()) && !s.policy_user() {
return Err("internal read results are reserved for the app".into());
}
let Some(id) = f(p, "ran").filter(|v| *v >= 0.0 && v.fract() == 0.0).map(|v| v as u64) else { return Ok(None) };
let i = s.downloaded.iter().position(|(d, _)| *d == id).ok_or("no such read (it was dropped when another project opened)")?;
Ok(Some((id, s.downloaded.remove(i).1)))
Expand Down
2 changes: 1 addition & 1 deletion crates/engine/src/cmd/items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,7 @@ pub fn commands() -> Vec<C> {
super::connections::resolve_project(s);
super::connections::note_waiting(s);
Ok(Value::Null)
}).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Replaces).with(crate::policy::Effect::Files))
}).roles(&[crate::ParamRole { key: "text", role: crate::Role::Document(crate::Document::Project) }]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Replaces).with(crate::policy::Effect::Files))
.view()
.params(r#"{"path"?: "*.rgistemplate", "text"?: template JSON, "data"?: base64 file, "name"?: new project name}"#),
// Packages.
Expand Down
3 changes: 3 additions & 0 deletions crates/engine/src/cmd/layer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4471,6 +4471,9 @@ fn add_sql(s: &mut Session, p: &Value) -> CmdResult {
let full = database.as_ref().map(|d| d.label());
// A result the app ran off the frame (the SQL pane), taken only for the query and database
// it came from (the layer saves them); or the query run now.
if p.get("ran").is_some_and(|v| !v.is_null()) && !s.policy_user() {
return Err("internal query results are reserved for the app".into());
}
let ran = p.get("ran").and_then(Value::as_u64);
let out = match ran {
Some(id) => {
Expand Down
6 changes: 5 additions & 1 deletion crates/engine/src/cmd/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -831,7 +831,11 @@ fn open_text(s: &mut Session, p: &Value) -> CmdResult {
super::connections::clear_active();
// What it names is held within this as it is read, before anything it names is read.
let reach = s.file_reach(p);
let proj = if package { Project::from_import_json_within(text, None, reach) } else { Project::from_json_within(text, reach) };
let proj = if package || !s.policy_user() {
Project::from_import_json_within(text, None, reach)
} else {
Project::from_json_within(text, reach)
};
let (proj, named) = match proj {
Ok(proj) => proj,
Err(error) => {
Expand Down
36 changes: 30 additions & 6 deletions crates/engine/src/cmd/s3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,35 @@ fn target(p: &Value) -> Result<(Option<String>, String), String> {
Ok((bucket, prefix))
}

/// Resolves the bucket listing connection and request URL for `s3.list`. When no signed
/// connection is authorized for this scope, wraps the URL with [`s3::anonymous`] so transport
/// preparation never attaches an implicit bucket or endpoint signer.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn bucket_list_url(
s: &Session,
bucket: &str,
prefix: &str,
token: Option<&str>,
named: Option<&s3::Connection>,
) -> Result<String, String> {
if named.is_some() && !s.policy_allows_reserved() {
return Err("listing through a named S3 connection requires user authorization".into());
}
let allow_implicit = !s.web_logins.is_anonymous() && s.policy_allows_reserved();
Comment thread
giswqs marked this conversation as resolved.
Resolved
let conn = named.cloned().or_else(|| s3::for_bucket(bucket).filter(|c| allow_implicit || c.credentials.is_none()));
Comment thread
giswqs marked this conversation as resolved.
Resolved
let url = s3::list_url(bucket, prefix, token, conn.as_ref());
match &conn {
Some(c) if c.credentials.is_some() => match s3::binding_of(&c.name) {
Some(_) => {
let binding = owned_saved_binding(s, c).ok_or_else(|| format!("no S3 connection named '{}'", c.name))?;
s3::bound_url(&binding, &url)
}
None => Ok(url),
},
_ => Ok(s3::anonymous(&url)),
}
}

pub(super) fn list(s: &mut Session, p: &Value) -> CmdResult {
let (bucket, prefix) = target(p)?;
let named = match ps(p, "connection").map(str::trim).filter(|n| !n.is_empty()) {
Expand Down Expand Up @@ -267,14 +296,9 @@ pub(super) fn list(s: &mut Session, p: &Value) -> CmdResult {
None => s3::grant(&c.name, &bucket),
}
}
let conn = named.or_else(|| s3::for_bucket(&bucket).filter(|c| !s.web_logins.is_anonymous() || c.credentials.is_none()));
let (mut prefixes, mut objects, mut token, mut pages) = (Vec::new(), Vec::new(), None::<String>, 0);
loop {
let url = s3::list_url(&bucket, &prefix, token.as_deref(), conn.as_ref());
let url = match &conn {
Some(c) => through(c, url)?,
None => url,
};
let url = bucket_list_url(s, &bucket, &prefix, token.as_deref(), named.as_ref())?;
let page = s3::parse_list(&fetch(&url)?)?;
prefixes.extend(page.prefixes);
objects.extend(page.objects);
Expand Down
74 changes: 63 additions & 11 deletions crates/engine/src/cmd/sharing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -282,16 +282,27 @@ fn share_bytes_inner(s: &mut Session, kind: &str, p: &Value, out: Output<'_>) ->
let mut m = map_of(s, p)?;
m.layers.iter_mut().filter(|l| shared_layer("webMap", l)).try_for_each(|l| load_whole(s, l, out, &mut held))?;
let mut unplaced = Unplaced::default();
let html = out.file(|w| write_web_map(w, &m, &m.name, &mut unplaced))?;
let mut limited = 0usize;
let html = out.file(|w| write_web_map(w, &m, &m.name, &mut unplaced, &mut limited))?;
unplaced.say(s, "The web map");
if limited > 0 {
s.notify(format!("{limited} feature(s) left out of the web map: the {MAX_FEATURES} feature limit was reached"), false);
}
Ok((m.name.clone(), html, m.name))
}
"webLayer" => {
let mut l = layer_of(s, p)?;
load_whole(s, &mut l, out, &mut held)?;
let mut unplaced = Unplaced::default();
let zip = web_layer_zip(s, &l, &mut unplaced, out)?;
let mut limited = 0usize;
let zip = web_layer_zip(s, &l, &mut unplaced, &mut limited, out)?;
unplaced.say(s, "The web layer");
if limited > 0 {
s.notify(
format!("{limited} feature(s) left out of the web layer's viewer page: the {MAX_FEATURES} feature limit was reached"),
false,
);
}
Ok((l.name.clone(), zip, l.name.clone()))
}
"webStyle" => {
Expand All @@ -304,8 +315,12 @@ fn share_bytes_inner(s: &mut Session, kind: &str, p: &Value, out: Output<'_>) ->
let fields: Option<Vec<String>> =
p.get("fields").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect());
let mut unplaced = Unplaced::default();
let loc = locator(&l, fields.as_deref(), &mut unplaced, out)?;
let mut limited = 0usize;
let loc = locator(&l, fields.as_deref(), &mut unplaced, &mut limited, out)?;
unplaced.say(s, "The locator");
if limited > 0 {
s.notify(format!("{limited} feature(s) left out of the locator: the {MAX_FEATURES} feature limit was reached"), false);
}
Ok((l.name.clone(), out.json(&loc)?, l.name.clone()))
}
"geodataService" => {
Expand Down Expand Up @@ -633,20 +648,35 @@ fn css(c: Rgba) -> String {

/// A layer's visible features as GeoJSON, each with its drawn style: in longitude/latitude,
/// whatever system the layer holds its coordinates in. One with a place that can't be given there
/// is left out, counted in `unplaced`.
/// is left out, counted in `unplaced`; visible features past `budget` are counted in `limited`.
fn styled_features(
l: &Layer,
budget: &mut usize,
unplaced: &mut Unplaced,
limited: &mut usize,
mut each: impl FnMut(Value) -> Result<(), String>,
) -> Result<(), String> {
let rows = l.visible_rows();
// Visible features with a geometry from `from` on: the ones the limit leaves out. Features past
// the limit are never converted, so one that couldn't be placed is counted here too: it is left
// out of the page either way. One pass over the rows, reading no coordinates and without a
// Cancel check, like the rest of this command, which runs on the UI thread (not in
// `exports::IN_BACKGROUND`).
let left_out = |from: usize| {
l.dataset.features.rows().enumerate().skip(from).filter(|(i, ft)| rows.get(*i) == Some(&true) && ft.geometry().is_some()).count()
};
// A layer that can't be given in longitude/latitude fails the page, budget left or not.
let to = l.dataset.lonlat_conversion().map_err(|e| format!("{}: {e}", l.name))?;
if *budget == 0 {
Comment thread
giswqs marked this conversation as resolved.
Resolved
*limited = limited.saturating_add(left_out(0));
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
return Ok(());
}
let opacity = 1.0 - f64::from(l.transparency.clamp(0.0, 100.0)) / 100.0;
// Its symbol by expression (no map scale: the page zooms on its own).
let styler = l.styler(None);
let to = l.dataset.lonlat_conversion().map_err(|e| format!("{}: {e}", l.name))?;
for (row, ft) in l.dataset.features.rows().enumerate() {
if *budget == 0 {
*limited = limited.saturating_add(left_out(row));
break;
}
if rows.get(row) != Some(&true) {
Expand Down Expand Up @@ -674,7 +704,8 @@ fn styled_features(
/// A self-contained web map page: the map's layers (rasters as images) drawn on a canvas in Web
/// Mercator, with pan, zoom, a layer list and pop-ups. No libraries or server. Its layers are
/// written to `page` as they are made, so a page held to a limit stops there.
fn write_web_map(page: &mut dyn std::io::Write, m: &Map, title: &str, unplaced: &mut Unplaced) -> Result<(), String> {
/// Visible features past the page's feature limit are counted in `limited`.
fn write_web_map(page: &mut dyn std::io::Write, m: &Map, title: &str, unplaced: &mut Unplaced, limited: &mut usize) -> Result<(), String> {
let failed = |e: std::io::Error| e.to_string();
let mut budget = MAX_FEATURES;
let mut pictures = 0usize;
Expand Down Expand Up @@ -724,7 +755,7 @@ const L=["#,
// A feature at a time, its members in the order a whole layer's value has them.
write!(page, r#"{separator}{{"features":["#).map_err(failed)?;
let mut between = "";
styled_features(l, &mut budget, unplaced, |feature| {
styled_features(l, &mut budget, unplaced, limited, |feature| {
write!(page, "{between}{}", script_json(&feature)).map_err(failed)?;
between = ",";
Ok(())
Expand Down Expand Up @@ -1036,7 +1067,7 @@ fn ogc_entries(parts: &mut Parts<'_>, title: &str, layers: &[&Dataset], unplaced
}

/// A web layer: the layer as an OGC API Features collection, its style, and a viewer page.
fn web_layer_zip(s: &Session, l: &Layer, unplaced: &mut Unplaced, out: Output<'_>) -> Result<Vec<u8>, String> {
fn web_layer_zip(s: &Session, l: &Layer, unplaced: &mut Unplaced, limited: &mut usize, out: Output<'_>) -> Result<Vec<u8>, String> {
let mut parts = out.parts();
ogc_entries(&mut parts, &l.name, &[&l.dataset], unplaced)?;
parts.make("style.json".into(), |w| serde_json::to_writer_pretty(w, &web_style(l)).map_err(|e| e.to_string()))?;
Expand All @@ -1057,10 +1088,21 @@ fn web_layer_zip(s: &Session, l: &Layer, unplaced: &mut Unplaced, out: Output<'_
m.camera.clamp();
}
// The page's features are the same, already counted by the collection.
parts.make("index.html".into(), |w| write_web_map(w, &m, &l.name, &mut Unplaced::default()))?;
parts.make("index.html".into(), |w| write_web_map(w, &m, &l.name, &mut Unplaced::default(), limited))?;
parts.zip()
}

/// Whether `g` has no coordinates at all (an empty extent), found from its parts without reading
/// every vertex.
fn geometry_is_empty(g: &Geometry) -> bool {
match g {
Geometry::Point(_) => false,
Geometry::MultiPoint(points) => points.is_empty(),
Geometry::Line(parts) => parts.iter().all(Vec::is_empty),
Geometry::Polygon(polygons) => polygons.iter().all(|rings| rings.iter().all(Vec::is_empty)),
}
}

/// A locator: searchable place names and where they are.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Locator {
Expand All @@ -1070,7 +1112,7 @@ pub struct Locator {
pub entries: Vec<(String, f64, f64)>,
}

fn locator(l: &Layer, fields: Option<&[String]>, unplaced: &mut Unplaced, out: Output<'_>) -> Result<Locator, String> {
fn locator(l: &Layer, fields: Option<&[String]>, unplaced: &mut Unplaced, limited: &mut usize, out: Output<'_>) -> Result<Locator, String> {
let ds = &l.dataset;
let fis: Vec<usize> = match fields {
Some(fs) => {
Expand All @@ -1085,7 +1127,16 @@ fn locator(l: &Layer, fields: Option<&[String]>, unplaced: &mut Unplaced, out: O
let mut entries = Vec::new();
// The entries' text so far, less than the file they make comes to.
let mut held = 0usize;
for (row, ft) in ds.features.iter().enumerate().take(MAX_FEATURES) {
let mut taken = 0usize;
for (row, ft) in ds.features.iter().enumerate() {
if taken >= MAX_FEATURES {
// Rows with no geometry or an empty one were never going to be in the locator. Told
// apart by their parts, not their vertices, so this pass stays cheap. It has no Cancel
// check, like the rest of `share.locator`, which runs on the UI thread (not in
// `exports::IN_BACKGROUND`).
*limited = ds.features.rows().skip(row).filter(|ft| ft.geometry().is_some_and(|g| !geometry_is_empty(g))).count();
Comment thread
giswqs marked this conversation as resolved.
Resolved
break;
}
let Some(g) = &ft.geometry else { continue };
let e = g.extent();
if e.is_empty() {
Expand All @@ -1102,6 +1153,7 @@ fn locator(l: &Layer, fields: Option<&[String]>, unplaced: &mut Unplaced, out: O
unplaced.add(&l.name, 1);
continue;
};
taken += 1;
for &fi in &fis {
let t = match ds.value(row, fi) {
rustgis_data::Value::Null => continue,
Expand Down
3 changes: 3 additions & 0 deletions crates/engine/src/cmd/zarr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -505,6 +505,9 @@ pub(crate) fn add(s: &mut Session, p: &Value) -> CmdResult {
Source::Dir(d) | Source::Url(d) => d.clone(),
};
// A slice the app read itself (the web app, or a store by address): its GeoTIFF, handed over.
if p.get("ran").is_some_and(|v| !v.is_null()) && !s.policy_user() {
return Err("internal read results are reserved for the app".into());
}
if let Some(id) = super::f(p, "ran").filter(|v| *v >= 0.0 && v.fract() == 0.0).map(|v| v as u64) {
let i = s.downloaded.iter().position(|(d, _)| *d == id).ok_or("no such read (it was dropped when another project opened)")?;
let (_, tif) = s.downloaded.remove(i);
Expand Down
Loading
Loading