-
Notifications
You must be signed in to change notification settings - Fork 72
Expand file tree
/
Copy pathtypes.rs
More file actions
2891 lines (2599 loc) · 101 KB
/
Copy pathtypes.rs
File metadata and controls
2891 lines (2599 loc) · 101 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation.
// Licensed under the PostgreSQL License.
//! Core types and configuration for pg_durable
use pgrx::{pg_extern, Spi};
use chrono::{DateTime, Utc};
use cron::Schedule as CronSchedule;
use percent_encoding::{utf8_percent_encode, NON_ALPHANUMERIC};
use serde::{Deserialize, Serialize};
use std::borrow::Cow;
use std::ffi::{CStr, CString};
use std::str::FromStr;
use std::sync::{Arc, OnceLock};
use std::time::Duration;
use uuid::Uuid;
// ============================================================================
// Configuration Functions
// ============================================================================
/// Get the worker role from the `pg_durable.worker_role` GUC.
/// Falls back to `"postgres"` if the GUC is not set.
pub fn get_worker_role() -> String {
crate::WORKER_ROLE
.get()
.map(|cs: CString| cs.to_string_lossy().into_owned())
.unwrap_or_else(|| "postgres".to_string())
}
/// Get the database from the `pg_durable.database` GUC.
/// Falls back to `"postgres"` if the GUC is not set.
pub fn get_database() -> String {
crate::DATABASE
.get()
.map(|cs: CString| cs.to_string_lossy().into_owned())
.unwrap_or_else(|| "postgres".to_string())
}
/// Get the maximum number of management pool connections.
pub fn get_max_management_connections() -> u32 {
crate::MAX_MANAGEMENT_CONNECTIONS.get() as u32
}
/// Get the maximum number of duroxide provider pool connections.
pub fn get_max_duroxide_connections() -> u32 {
crate::MAX_DUROXIDE_CONNECTIONS.get() as u32
}
/// Get the maximum number of concurrent user-execution connections.
pub fn get_max_user_connections() -> u32 {
crate::MAX_USER_CONNECTIONS.get() as u32
}
/// Get the maximum number of concurrent transaction_mode => 'new' launch sessions.
pub fn get_max_new_transaction_starts() -> u32 {
crate::MAX_NEW_TRANSACTION_STARTS.get() as u32
}
/// Get the execution acquire timeout as a Duration.
pub fn get_execution_acquire_timeout() -> Duration {
Duration::from_secs(crate::EXECUTION_ACQUIRE_TIMEOUT.get() as u64)
}
/// Get the transaction_mode => 'new' launch-slot timeout as a Duration.
pub fn get_new_transaction_start_timeout() -> Duration {
Duration::from_secs(crate::NEW_TRANSACTION_START_TIMEOUT.get() as u64)
}
/// Days a terminal instance is retained before reconciliation removes it and its
/// engine record; also the age bound for reclaiming orphaned engine records.
pub fn get_retention_days() -> i32 {
crate::RETENTION_DAYS.get()
}
/// Interval between background reconciliation passes. Zero disables reconciliation.
pub fn get_reconcile_interval() -> Duration {
Duration::from_secs(crate::RECONCILE_INTERVAL.get() as u64)
}
/// Returns `true` when superuser-submitted instances are permitted.
pub fn superuser_instances_enabled() -> bool {
crate::ENABLE_SUPERUSER_INSTANCES.get()
}
/// Returns `true` if the role identified by `role_oid` is a PostgreSQL superuser.
/// Runs a SPI query against `pg_catalog.pg_roles`. Must be called from a
/// backend context (not the background worker).
pub fn is_role_superuser_oid(role_oid: pgrx::pg_sys::Oid) -> Result<bool, String> {
match pgrx::Spi::get_one_with_args::<bool>(
"SELECT rolsuper FROM pg_catalog.pg_roles WHERE oid = $1",
&[role_oid.into()],
) {
Ok(Some(v)) => Ok(v),
Ok(None) => Err(format!("role oid {} not found in pg_roles", role_oid)),
Err(e) => Err(format!(
"superuser check failed for role oid {}: {}",
role_oid, e
)),
}
}
/// Returns `true` if the role identified by `role_name` is a PostgreSQL superuser.
/// Issues a single async query against `pg_catalog.pg_roles` using the provided pool.
/// Must be called from an async context (background worker).
pub async fn is_role_superuser_name(pool: &sqlx::PgPool, role_name: &str) -> Result<bool, String> {
sqlx::query_scalar::<_, bool>("SELECT rolsuper FROM pg_catalog.pg_roles WHERE rolname = $1")
.bind(role_name)
.fetch_optional(pool)
.await
.map_err(|e| format!("superuser check failed for role '{}': {}", role_name, e))
.and_then(|opt| opt.ok_or_else(|| format!("role '{}' not found in pg_roles", role_name)))
}
/// Maximum nesting depth for workflow graphs. Bounds recursive graph walkers
/// after opaque child storage removes serde_json's incidental depth limit.
pub const MAX_GRAPH_DEPTH: usize = 256;
/// Maximum number of nodes allowed in a single workflow instance. Prevents
/// unbounded INSERTs and memory exhaustion from extremely large graphs.
pub const MAX_GRAPH_NODES: usize = 10_000;
/// Generate a short 8-character ID from a UUID.
///
/// This serves two distinct uniqueness contracts (#129). Both keep the value
/// `VARCHAR(8)` HEX (the maintainer-requested minimal change):
/// - **Instance IDs** (`df.instances.id`) are global with no scoping column.
/// `df.start()` reserves the ID with `INSERT ... ON CONFLICT (id) DO NOTHING
/// RETURNING id` and re-rolls on collision; the primary key on `df.instances`
/// is the hard guarantee.
/// - **Node IDs** (`df.nodes.id`) only need to be unique per instance. Node
/// IDs are assigned uniquely while the graph is materialized, before parent
/// references are fixed. The composite primary key `(instance_id, id)` is the
/// final database guarantee; an unexpected insert conflict aborts the start.
pub fn short_id() -> String {
let uuid = Uuid::new_v4();
uuid.to_string()
.chars()
.rev()
.take(8)
.collect::<String>()
.chars()
.rev()
.collect()
}
/// PostgreSQL connection string for the background worker and Duroxide runtime
pub fn postgres_connection_string() -> String {
let host = std::env::var("PGHOST").unwrap_or_else(|_| "127.0.0.1".to_string());
let port = unsafe { pgrx::pg_sys::PostPortNumber };
let user = get_worker_role();
let database = get_database();
build_connection_url(&user, &host, port, &database)
}
/// Build the worker's `postgres://` connection URL.
///
/// A Unix-socket `host` (one starting with `/`) is percent-encoded so the URL
/// parser keeps the whole path as the host; sqlx percent-decodes it and
/// connects over the socket. TCP addresses and hostnames are used verbatim.
fn build_connection_url(user: &str, host: &str, port: i32, database: &str) -> String {
if host.starts_with('/') {
let encoded = utf8_percent_encode(host, NON_ALPHANUMERIC).to_string();
format!("postgres://{user}@{encoded}:{port}/{database}")
} else {
format!("postgres://{user}@{host}:{port}/{database}")
}
}
/// Get the PostgreSQL host for connections
pub fn get_host() -> String {
std::env::var("PGHOST").unwrap_or_else(|_| "127.0.0.1".to_string())
}
/// Get the PostgreSQL port for connections
pub fn get_port() -> u16 {
unsafe { pgrx::pg_sys::PostPortNumber as u16 }
}
/// Get the target database name that the background worker will connect to
/// This matches the logic in postgres_connection_string() for database selection
#[pg_extern(immutable, parallel_safe, schema = "df")]
pub fn target_database() -> String {
get_database()
}
fn normalize_role_name_for_connection(user: &str) -> Result<Cow<'_, str>, String> {
if !user.starts_with('"') {
if user.ends_with('"') {
return Err(format!(
"Invalid role name '{}': unexpected trailing double quote in connection username",
user
));
}
return Ok(Cow::Borrowed(user));
}
if !user.ends_with('"') || user.len() < 2 {
return Err(format!(
"Invalid role name '{}': unterminated quoted identifier in connection username",
user
));
}
let inner = &user[1..user.len() - 1];
let mut normalized = String::with_capacity(inner.len());
let mut chars = inner.chars().peekable();
while let Some(ch) = chars.next() {
if ch != '"' {
normalized.push(ch);
continue;
}
if chars.peek() == Some(&'"') {
normalized.push('"');
chars.next();
continue;
}
return Err(format!(
"Invalid quoted role name '{}': expected doubled double quotes inside identifier",
user
));
}
Ok(Cow::Owned(normalized))
}
/// Create a single PostgreSQL connection authenticated as `user`.
pub async fn connect_as_user(
user: &str,
database: Option<&str>,
) -> Result<sqlx::postgres::PgConnection, String> {
use sqlx::postgres::PgConnectOptions;
use sqlx::Connection;
/// Connection timeout for per-user SQL connections (seconds).
const CONNECT_TIMEOUT_SECS: u64 = 30;
let normalized_user = normalize_role_name_for_connection(user)?;
let default_db = target_database();
let db = database.unwrap_or(&default_db);
let mut options = PgConnectOptions::new()
.username(normalized_user.as_ref())
.database(db)
.port(get_port());
let host = get_host();
if !host.is_empty() {
options = options.host(&host);
}
let connect_future = sqlx::postgres::PgConnection::connect_with(&options);
let mut conn = tokio::time::timeout(Duration::from_secs(CONNECT_TIMEOUT_SECS), connect_future)
.await
.map_err(|_| {
format!(
"Connection to database '{}' as '{}' timed out after {}s",
db,
normalized_user.as_ref(),
CONNECT_TIMEOUT_SECS
)
})?
.map_err(|e| {
format!(
"Failed to connect to database '{}' as '{}'. Error: {}",
db,
normalized_user.as_ref(),
e
)
})?;
// Mark this connection as running inside a workflow.
// Currently used to prevent variable mutations (setvar/unsetvar/clearvars)
// during execution. Could also be checked in df.start() to prevent
// recursive workflow invocation in a future improvement.
sqlx::query("SET df.in_workflow = 'true'")
.execute(&mut conn)
.await
.map_err(|e| format!("SET df.in_workflow failed: {}", e))?;
Ok(conn)
}
/// Legacy duroxide provider schema name used by installs created before the
/// `df.duroxide_schema()` helper existed (pg_durable ≤ 0.2.2). It is the only
/// fallback when that helper is absent, and the value the upgrade script pins
/// existing clusters to.
pub const LEGACY_DUROXIDE_SCHEMA: &str = "duroxide";
/// Resolve the duroxide provider schema name by calling the extension-owned
/// `df.duroxide_schema()` helper.
///
/// Returns [`LEGACY_DUROXIDE_SCHEMA`] when the helper does not exist (an install
/// that predates it — e.g. a new `.so` deployed against a ≤0.2.2 schema without
/// running `ALTER EXTENSION pg_durable UPDATE`). The presence check uses the
/// catalog rather than catching `42883` so it never aborts the surrounding
/// (sub)transaction in a backend session.
fn resolve_duroxide_schema_spi() -> String {
let helper_exists = Spi::get_one::<bool>(
"SELECT EXISTS(SELECT 1 FROM pg_catalog.pg_proc p \
JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace \
WHERE n.nspname = 'df' AND p.proname = 'duroxide_schema' AND p.pronargs = 0)",
)
.ok()
.flatten()
.unwrap_or(false);
if !helper_exists {
return LEGACY_DUROXIDE_SCHEMA.to_string();
}
match Spi::get_one::<String>("SELECT df.duroxide_schema()") {
Ok(Some(s)) if !s.is_empty() => s,
_ => LEGACY_DUROXIDE_SCHEMA.to_string(),
}
}
/// Resolve the duroxide provider schema for the current backend session,
/// caching it for the session lifetime. The value cannot change without an
/// extension upgrade, which requires a reconnect to observe reliably, so a
/// per-session cache is safe.
pub fn backend_duroxide_schema() -> &'static str {
static SCHEMA: OnceLock<String> = OnceLock::new();
SCHEMA.get_or_init(resolve_duroxide_schema_spi)
}
/// Resolve the duroxide provider schema name from the background worker using an
/// async pool. Mirrors [`resolve_duroxide_schema_spi`] but for the BGW context.
/// The BGW resolves this once per epoch (after the extension is detected) rather
/// than caching for the process lifetime, because drop+recreate can switch the
/// provider schema within a single worker lifetime.
pub async fn resolve_duroxide_schema_pool(pool: &sqlx::PgPool) -> String {
let helper_exists: bool = sqlx::query_scalar(
"SELECT EXISTS(SELECT 1 FROM pg_proc p \
JOIN pg_namespace n ON n.oid = p.pronamespace \
WHERE n.nspname = 'df' AND p.proname = 'duroxide_schema' AND p.pronargs = 0)",
)
.fetch_one(pool)
.await
.unwrap_or(false);
if !helper_exists {
return LEGACY_DUROXIDE_SCHEMA.to_string();
}
match sqlx::query_scalar::<_, String>("SELECT df.duroxide_schema()")
.fetch_one(pool)
.await
{
Ok(s) if !s.is_empty() => s,
_ => LEGACY_DUROXIDE_SCHEMA.to_string(),
}
}
/// Create a `ProviderConfig` for backend (request/response) operations.
///
/// - `VerifyOnly`: never create schema/tables, reject unknown migrations.
/// Backend sessions must not run DDL — the BGW owns schema lifecycle.
pub fn backend_provider_config(
database_url: &str,
schema_name: &str,
) -> duroxide_pg::ProviderConfig {
let mut config = duroxide_pg::ProviderConfig::url(database_url);
config.schema_name = Some(schema_name.to_string());
config.migration_policy = duroxide_pg::MigrationPolicy::VerifyOnly;
config
}
/// Create a backend provider for request/response operations.
pub async fn new_backend_provider(
database_url: &str,
schema_name: &str,
) -> Result<Arc<duroxide_pg::PostgresProvider>, String> {
duroxide_pg::PostgresProvider::new_with_config(backend_provider_config(
database_url,
schema_name,
))
.await
.map(Arc::new)
.map_err(|e| format!("Failed to connect to duroxide store: {e}"))
}
/// Create a `ProviderConfig` for the background worker runtime.
///
/// - `ApplyAll`: applies pending duroxide migrations at startup; creates tables
/// inside the extension-owned provider schema. Safe because the BGW verifies
/// schema ownership via `pg_depend` before calling
/// `PostgresProvider::new_with_config`.
pub fn worker_provider_config(
database_url: &str,
schema_name: &str,
) -> duroxide_pg::ProviderConfig {
let mut config = duroxide_pg::ProviderConfig::url(database_url);
config.schema_name = Some(schema_name.to_string());
config.migration_policy = duroxide_pg::MigrationPolicy::ApplyAll;
config
}
/// Calculate the duration until the next cron schedule match
pub fn calculate_cron_wait(cron_expr: &str) -> Result<Duration, String> {
let cron_with_seconds = format!("0 {cron_expr}");
let schedule = CronSchedule::from_str(&cron_with_seconds)
.map_err(|e| format!("Invalid cron expression '{cron_expr}': {e}"))?;
let now: DateTime<Utc> = Utc::now();
let next = schedule
.upcoming(Utc)
.next()
.ok_or_else(|| "No upcoming schedule found".to_string())?;
let duration = (next - now)
.to_std()
.map_err(|_| "Failed to calculate wait duration".to_string())?;
Ok(duration)
}
/// Evaluate a condition result to determine if it's truthy.
/// Uses iter().next() for first-column extraction — picks an arbitrary first
/// column, which is acceptable here because conditions are single-value
/// queries (SELECT <bool_expr>).
pub fn evaluate_condition(result: &str) -> Result<bool, String> {
if let Ok(json) = serde_json::from_str::<serde_json::Value>(result) {
if let Some(rows) = json.get("rows").and_then(|r| r.as_array()) {
// Empty result set → falsy (no rows means condition is not met)
if rows.is_empty() {
return Ok(false);
}
if let Some(first_row) = rows.first() {
if let Some(obj) = first_row.as_object() {
if let Some((_, value)) = obj.iter().next() {
return Ok(is_truthy(value));
}
}
}
}
return Ok(is_truthy(&json));
}
// Raw string fallback: delegate to is_truthy for consistent behavior
Ok(is_truthy(&serde_json::Value::String(result.to_string())))
}
pub fn is_truthy(value: &serde_json::Value) -> bool {
match value {
serde_json::Value::Bool(b) => *b,
serde_json::Value::Number(n) => {
n.as_i64().map(|i| i != 0).unwrap_or(false)
|| n.as_f64().map(|f| f != 0.0).unwrap_or(false)
}
serde_json::Value::String(s) => {
let trimmed = s.trim();
if trimmed.is_empty() {
return false;
}
let lower = trimmed.to_lowercase();
if matches!(lower.as_str(), "true" | "t" | "yes") {
return true;
}
if matches!(lower.as_str(), "false" | "f" | "no") {
return false;
}
// Numeric strings: try float parsing (covers both ints and floats)
if let Ok(n) = lower.parse::<f64>() {
return n != 0.0;
}
// Non-empty, non-boolean, non-numeric strings are truthy
true
}
serde_json::Value::Array(a) => !a.is_empty(),
serde_json::Value::Object(o) => !o.is_empty(),
serde_json::Value::Null => false,
}
}
/// System variables available during workflow execution
pub struct SystemVars {
pub instance_id: String,
pub label: Option<String>,
}
// ============================================================================
// Result Substitution Helpers
// ============================================================================
fn is_ident_start(b: u8) -> bool {
b.is_ascii_alphabetic() || b == b'_'
}
fn is_ident_continue(b: u8) -> bool {
b.is_ascii_alphanumeric() || b == b'_'
}
/// Parse an identifier at the start of `s`: [a-zA-Z_][a-zA-Z0-9_]*
fn parse_identifier(s: &str) -> &str {
let bytes = s.as_bytes();
if bytes.is_empty() || !is_ident_start(bytes[0]) {
return "";
}
let len = bytes.iter().take_while(|&&b| is_ident_continue(b)).count();
&s[..len]
}
/// Validate that a result name is a safe SQL identifier: [a-zA-Z_][a-zA-Z0-9_]*
/// Returns Ok(()) if valid, Err with message if not.
pub fn validate_result_name(name: &str) -> Result<(), String> {
if name.is_empty() {
return Err("result name cannot be empty".to_string());
}
let parsed = parse_identifier(name);
if parsed.len() != name.len() {
return Err(format!(
"result name '{}' is not a valid identifier — must match [a-zA-Z_][a-zA-Z0-9_]*",
name
));
}
Ok(())
}
/// Double-quote a SQL identifier, escaping any internal double-quotes.
fn quote_identifier(name: &str) -> String {
let escaped = name.replace('"', "\"\"");
format!("\"{escaped}\"")
}
/// Format a JSON value for use in a SQL or raw context.
fn format_value(val: &serde_json::Value, for_sql: bool) -> String {
match val {
serde_json::Value::String(s) => {
if for_sql {
let escaped = s.replace('\'', "''");
format!("'{escaped}'")
} else {
s.clone()
}
}
serde_json::Value::Number(n) => n.to_string(),
serde_json::Value::Bool(b) => b.to_string(),
_ => {
if for_sql {
let s = val.to_string();
let escaped = s.replace('\'', "''");
format!("'{escaped}'")
} else {
val.to_string()
}
}
}
}
/// Extract first-column-first-row (bare `$name` / `$name?`).
fn extract_first_column_value(
name: &str,
json_str: &str,
null_safe: bool,
for_sql: bool,
) -> Result<String, String> {
let json: serde_json::Value = match serde_json::from_str(json_str) {
Ok(v) => v,
Err(_) => {
// Not JSON — return raw value (backward compat for HTTP responses etc.)
return Ok(if for_sql {
let escaped = json_str.replace('\'', "''");
format!("'{escaped}'")
} else {
json_str.to_string()
});
}
};
if let Some(rows) = json.get("rows").and_then(|r| r.as_array()) {
if rows.is_empty() {
return if null_safe {
Ok("NULL".to_string())
} else {
Err(format!("${name} has no rows — query returned zero results"))
};
}
let first_row = rows[0]
.as_object()
.ok_or_else(|| format!("${name}: first row is not an object"))?;
let (_, val) = first_row
.iter()
.next()
.ok_or_else(|| format!("${name}: first row has no columns"))?;
if val.is_null() {
return if null_safe {
Ok("NULL".to_string())
} else {
Err(format!(
"${name} is NULL — first column of first row is NULL"
))
};
}
Ok(format_value(val, for_sql))
} else if for_sql {
let escaped = json_str.replace('\'', "''");
Ok(format!("'{escaped}'"))
} else {
Ok(json_str.to_string())
}
}
/// Extract a named field from a node result (`$name.col` / `$name.col?`).
///
/// SQL node results carry a `rows` array, so the field is read from the first
/// row. HTTP and HTTP_MULTIPART results are flat response envelopes with no
/// `rows` array, so the field is read from the envelope itself — this is what
/// makes `$response.body`, `$response.status` and `$response.ok` work.
///
/// Returns the original pattern when the field does not exist in the result.
fn extract_column_value(
name: &str,
json_str: &str,
col: &str,
null_safe: bool,
for_sql: bool,
) -> Result<String, String> {
let json: serde_json::Value = serde_json::from_str(json_str)
.map_err(|_| format!("${name}.{col}: result is not valid JSON"))?;
let fields = match json.get("rows").and_then(|r| r.as_array()) {
Some(rows) => {
if rows.is_empty() {
return if null_safe {
Ok("NULL".to_string())
} else {
Err(format!("${name} has no rows — query returned zero results"))
};
}
rows[0]
.as_object()
.ok_or_else(|| format!("${name}.{col}: first row is not an object"))?
}
None => json.as_object().ok_or_else(|| {
format!("${name}.{col}: result is neither a row set nor a JSON object")
})?,
};
let val = match fields.get(col) {
Some(v) => v,
None => {
// Missing field.
//
// In a SQL context the pattern is left as-is so PostgreSQL reports
// the error with its own diagnostics. A raw context — a URL, a
// header, a multipart field — has no such parser, so a leftover
// `$name.col` would be sent over the wire verbatim and the request
// would fail somewhere far less obvious. Fail loudly instead.
if !for_sql && !null_safe {
let mut available: Vec<&str> = fields.keys().map(String::as_str).collect();
available.sort_unstable();
return Err(format!(
"${name}.{col}: result has no field '{col}' (available: {})",
available.join(", ")
));
}
let suffix = if null_safe { "?" } else { "" };
return Ok(format!("${name}.{col}{suffix}"));
}
};
if val.is_null() {
return if null_safe {
Ok("NULL".to_string())
} else {
Err(format!("${name}.{col} is NULL"))
};
}
Ok(format_value(val, for_sql))
}
/// Expand `$name.*` into an inline `VALUES` subquery (SQL) or JSON array (raw).
fn expand_row_set(name: &str, json_str: &str, for_sql: bool) -> Result<String, String> {
/// Maximum number of rows allowed in `$name.*` expansion to prevent
/// unbounded SQL string allocation from large result sets.
const MAX_ROWSET_EXPANSION: usize = 10_000;
let json: serde_json::Value = serde_json::from_str(json_str)
.map_err(|e| format!("${name}.* — invalid result JSON: {e}"))?;
let rows = json
.get("rows")
.and_then(|r| r.as_array())
.ok_or_else(|| format!("${name}.* — invalid result format"))?;
if rows.len() > MAX_ROWSET_EXPANSION {
return Err(format!(
"${name}.* — result has {} rows, exceeding the maximum of {} for row-set expansion. \
Use pagination or intermediate tables for large result sets.",
rows.len(),
MAX_ROWSET_EXPANSION
));
}
if !for_sql {
return Ok(serde_json::to_string(rows).unwrap());
}
let quoted_name = quote_identifier(name);
if rows.is_empty() {
return Ok(format!("(SELECT NULL WHERE false) AS {quoted_name}"));
}
let first_obj = rows[0]
.as_object()
.ok_or_else(|| format!("${name}.* — row is not an object"))?;
let col_names: Vec<&str> = first_obj.keys().map(|k| k.as_str()).collect();
let mut value_rows = Vec::with_capacity(rows.len());
for row in rows {
let obj = row
.as_object()
.ok_or_else(|| format!("${name}.* — row is not an object"))?;
let vals: Vec<String> = col_names
.iter()
.map(|&col| match obj.get(col) {
Some(serde_json::Value::String(s)) => {
let escaped = s.replace('\'', "''");
format!("'{escaped}'::text")
}
Some(serde_json::Value::Number(n)) => n.to_string(),
Some(serde_json::Value::Bool(b)) => b.to_string(),
Some(serde_json::Value::Null) | None => "NULL".to_string(),
Some(other) => {
let escaped = other.to_string().replace('\'', "''");
format!("'{escaped}'::text")
}
})
.collect();
value_rows.push(format!("({})", vals.join(",")));
}
let col_list = col_names
.iter()
.map(|c| quote_identifier(c))
.collect::<Vec<_>>()
.join(", ");
Ok(format!(
"(VALUES {}) AS {quoted_name}({col_list})",
value_rows.join(", ")
))
}
/// Scan-based result substitution supporting:
/// `$name.*` — row-set expansion
/// `$name.col?` — null-safe dot-notation
/// `$name.col` — strict dot-notation
/// `$name?` — null-safe scalar
/// `$name` — strict scalar
fn substitute_results(
input: &str,
results: &std::collections::HashMap<String, String>,
for_sql: bool,
) -> Result<String, String> {
if results.is_empty() {
return Ok(input.to_string());
}
// Sort names longest-first to avoid partial matches
let mut names: Vec<&str> = results.keys().map(|s| s.as_str()).collect();
names.sort_by_key(|name| std::cmp::Reverse(name.len()));
let mut out = String::with_capacity(input.len());
let mut i = 0;
let input_bytes = input.as_bytes();
while i < input.len() {
if input_bytes[i] != b'$' {
let ch = input[i..].chars().next().unwrap();
out.push(ch);
i += ch.len_utf8();
continue;
}
let after_dollar = &input[i + 1..];
let mut matched = false;
for name in &names {
if !after_dollar.starts_with(name) {
continue;
}
let after_name = &after_dollar[name.len()..];
let json_str = &results[*name];
// 1. $name.* — row-set expansion
if after_name.starts_with(".*") {
let replacement = expand_row_set(name, json_str, for_sql)?;
out.push_str(&replacement);
i += 1 + name.len() + 2; // $ + name + .*
matched = true;
break;
}
// 2/3. $name.col? or $name.col — dot-notation
if let Some(after_dot) = after_name.strip_prefix('.') {
let col = parse_identifier(after_dot);
if !col.is_empty() {
let after_col = &after_dot[col.len()..];
let null_safe = after_col.starts_with('?');
let replacement =
extract_column_value(name, json_str, col, null_safe, for_sql)?;
out.push_str(&replacement);
i += 1 + name.len() + 1 + col.len() + if null_safe { 1 } else { 0 };
matched = true;
break;
}
// No valid column name after dot — fall through to bare $name
}
// 4. $name? — null-safe scalar
if after_name.starts_with('?') {
let replacement = extract_first_column_value(name, json_str, true, for_sql)?;
out.push_str(&replacement);
i += 1 + name.len() + 1; // $ + name + ?
matched = true;
break;
}
// 5. $name — strict scalar (with word-boundary check)
if after_name.is_empty() || !is_ident_continue(after_name.as_bytes()[0]) {
let replacement = extract_first_column_value(name, json_str, false, for_sql)?;
out.push_str(&replacement);
i += 1 + name.len();
matched = true;
break;
}
// Next char is an identifier continuation — try shorter names
}
if !matched {
out.push('$');
i += 1;
}
}
Ok(out)
}
/// Substitute `{name}` placeholders in a single left-to-right pass over the template.
/// Inserted values are appended as opaque text and are never scanned for more placeholders.
fn substitute_braced_variables(
template: &str,
vars: &std::collections::HashMap<String, String>,
sys_vars: &SystemVars,
) -> String {
let mut out = String::with_capacity(template.len());
let mut remaining = template;
while let Some(open) = remaining.find('{') {
out.push_str(&remaining[..open]);
let after_open = &remaining[open + 1..];
let Some(close) = after_open.find('}') else {
out.push_str(&remaining[open..]);
return out;
};
let name = &after_open[..close];
let replacement = match name {
"sys_instance_id" => Some(sys_vars.instance_id.as_str()),
"sys_label" => Some(sys_vars.label.as_deref().unwrap_or("")),
_ if parse_identifier(name).len() == name.len() => vars.get(name).map(String::as_str),
_ => None,
};
if let Some(value) = replacement {
out.push_str(value);
} else {
out.push_str(&remaining[open..open + close + 2]);
}
remaining = &after_open[close + 1..];
}
out.push_str(remaining);
out
}
/// Substitute all variable types in a query:
/// - {name} for user vars (from FunctionInput.vars) - values are inserted as-is
/// - {sys_instance_id}, {sys_label} for system vars - inserted as-is
/// - $name, $name.col, $name?, $name.col?, $name.* for named results (from |=>)
///
/// User vars and system vars are substituted without quoting - the user should
/// handle SQL escaping in the original query if needed.
///
/// Returns `Err` if a strict (non-`?`) pattern references a result with no rows
/// or a NULL value.
pub fn substitute_all_with_options(
query: &str,
results: &std::collections::HashMap<String, String>,
vars: &std::collections::HashMap<String, String>,
sys_vars: &SystemVars,
quote_results_for_sql: bool,
) -> Result<String, String> {
// SECURITY: Raw substitution of user vars is by design — variables are
// intended for SQL fragments (table names, expressions), not just values.
// The user controls both the variable content and the query template, and
// SQL executes under their own role via connect_as_user().
// See docs/spec-security-model.md §4.3, T10.
// 1/2. Substitute system and user vars in one pass (inserted as-is, no quoting).
let result = substitute_braced_variables(query, vars, sys_vars);
// 3. Substitute results: $name with dot-notation, null-safe, and row-set support
substitute_results(&result, results, quote_results_for_sql)
}
/// Substitute all variables with SQL quoting (default for SQL contexts)
pub fn substitute_all(
query: &str,
results: &std::collections::HashMap<String, String>,
vars: &std::collections::HashMap<String, String>,
sys_vars: &SystemVars,
) -> Result<String, String> {
substitute_all_with_options(query, results, vars, sys_vars, true)
}
/// Substitute all variables without SQL quoting (for URLs, headers, etc.)
pub fn substitute_all_raw(
query: &str,
results: &std::collections::HashMap<String, String>,
vars: &std::collections::HashMap<String, String>,
sys_vars: &SystemVars,
) -> Result<String, String> {
substitute_all_with_options(query, results, vars, sys_vars, false)
}
/// Report whether `value` consists of exactly one variable reference and nothing
/// else, ignoring surrounding whitespace.
///
/// Accepted forms:
/// - `$name`, `$name?`
/// - `$name.col`, `$name.col?`
/// - `{name}` — covers user variables and `{sys_*}` alike
///
/// Deliberately rejected:
/// - `$name.*` — a row-set expansion is never a single opaque value
/// - anything with surrounding literal text, or more than one reference
///
/// This exists for contexts where a value must be replaced wholesale or not at
/// all — notably a multipart part's `data_b64`, where splicing a substitution
/// into the middle of a base64 string can only corrupt the payload.
pub fn is_whole_value_reference(value: &str) -> bool {
let value = value.trim();
if let Some(rest) = value.strip_prefix('$') {
let name = parse_identifier(rest);
if name.is_empty() {
return false;
}
let rest = &rest[name.len()..];
// Dot notation, but never the `.*` row-set form.
let rest = match rest.strip_prefix('.') {
Some(after_dot) => {
let col = parse_identifier(after_dot);
if col.is_empty() {
return false;
}
&after_dot[col.len()..]
}
None => rest,
};
// An optional null-safe marker may follow, and nothing else.
return rest.is_empty() || rest == "?";
}
if let Some(rest) = value.strip_prefix('{') {
let name = parse_identifier(rest);
return !name.is_empty() && &rest[name.len()..] == "}";
}
false
}
/// Legacy function for backward compatibility - only substitutes $name results
pub fn substitute_variables(
query: &str,
results: &std::collections::HashMap<String, String>,
) -> Result<String, String> {
substitute_all(
query,
results,
&std::collections::HashMap::new(),
&SystemVars {
instance_id: String::new(),
label: None,