Repository navigation
Expand file tree
/
Copy pathmod.rs
More file actions
1492 lines (1441 loc) · 53.8 KB
/
Copy pathmod.rs
File metadata and controls
1492 lines (1441 loc) · 53.8 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
//! Checked project graphs, target separation, and versioned application builds.
mod accounts;
mod actions;
mod admission;
mod api;
pub(crate) mod artifact;
mod assets;
mod browser;
mod compute;
mod connected;
pub(crate) mod delivery;
mod deployment;
mod events;
mod files;
pub(crate) mod git;
mod identity;
mod jobs;
mod lower;
pub(crate) mod mail;
pub(crate) mod operations;
mod queries;
mod render;
pub(crate) mod resolve;
mod retry;
mod rpc;
mod schemas;
mod secrets;
mod server;
pub(crate) mod storage;
pub(crate) mod wire;
mod workflows;
use crate::authority::{Effect, Effects, Principal, Scope};
use crate::error::{Error, Result};
use crate::hir::CheckedProgram;
use crate::syntax::{
Declaration, Expr, ExprKind, Function, Program, ProjectModule, Statement, StatementKind,
};
use crate::value::Value;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
use std::net::SocketAddr;
use std::path::Path;
const FORMAT_VERSION: u32 = 5;
const MANIFEST_VERSION: u32 = 1;
const WIRE_VERSION: u32 = 7;
const MAX_PROJECT_BYTES: usize = 8 * crate::MAX_SOURCE_BYTES;
const LINE_STRIDE: usize = crate::MAX_SOURCE_BYTES + 1;
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
enum Target {
Server,
Browser,
Shared,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
struct ModuleConfig {
path: String,
target: Target,
#[serde(default)]
imports: Vec<String>,
#[serde(default)]
provides: BTreeSet<String>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
struct Manifest {
schema_version: u32,
name: String,
server: String,
browser: String,
component: String,
#[serde(default)]
runtime: admission::Config,
#[serde(default)]
provides: BTreeSet<String>,
modules: BTreeMap<String, ModuleConfig>,
#[serde(default)]
rpc: BTreeMap<String, String>,
#[serde(default)]
actions: BTreeMap<String, actions::Binding>,
#[serde(default)]
public_rpc: BTreeSet<String>,
#[serde(default)]
styles: Vec<String>,
#[serde(default)]
assets: BTreeMap<String, String>,
#[serde(default)]
storage: Option<crate::relational::Storage>,
#[serde(default)]
identity: Option<accounts::Config>,
#[serde(default)]
http_api: Option<api::Config>,
#[serde(default)]
files: Option<files::Config>,
#[serde(default)]
git: Option<git::Config>,
#[serde(default)]
delivery: Option<delivery::Config>,
#[serde(default)]
operations: Option<operations::Config>,
#[serde(default)]
jobs: BTreeMap<String, jobs::Binding>,
#[serde(default)]
events: BTreeMap<String, events::Binding>,
#[serde(default)]
mail: Option<mail::Config>,
#[serde(default)]
workflows: BTreeMap<String, workflows::Binding>,
#[serde(default)]
secrets: BTreeMap<String, secrets::SecretUse>,
#[serde(default)]
queries: BTreeMap<String, queries::Config>,
#[serde(default)]
compute: BTreeMap<String, compute::ModuleConfig>,
}
#[derive(Clone, Debug)]
struct Module {
config: ModuleConfig,
parsed: ProjectModule,
symbols: BTreeMap<String, String>,
line_base: usize,
}
/// A checked multi-file application with separated server and browser targets.
/// Host access is supplied explicitly at execution and is never loaded from a build.
///
/// ```no_run
/// let project = diamond::compile_project(std::path::Path::new("examples/foundations/diamond.toml"))?;
/// assert!(project.summary().contains("browser"));
/// # Ok::<(), diamond::Error>(())
/// ```
#[derive(Clone, Debug)]
pub struct CheckedProject {
manifest_source: String,
sources: BTreeMap<String, String>,
manifest: Manifest,
modules: BTreeMap<String, Module>,
server: CheckedProgram,
browser: lower::BrowserProgram,
browser_checked: CheckedProgram,
rpc: BTreeMap<String, rpc::Operation>,
api: BTreeMap<String, api::Operation>,
jobs: BTreeMap<String, rpc::Operation>,
workflows: BTreeMap<String, workflows::Operations>,
queries: BTreeMap<String, queries::Plan>,
}
/// Read and check a bounded project without opening a database or listener.
///
/// # Errors
/// Rejects invalid manifests, source paths, modules, types, targets, or effects.
///
/// ```no_run
/// let project = diamond::compile_project(std::path::Path::new("examples/foundations/diamond.toml"))?;
/// assert!(project.summary().contains("PostgresRead"));
/// # Ok::<(), diamond::Error>(())
/// ```
pub fn compile_project(path: &Path) -> Result<CheckedProject> {
let path = path.canonicalize()?;
let root = path
.parent()
.ok_or_else(|| input("project manifest needs a parent directory"))?;
let manifest_source = artifact::read_text(&path, crate::MAX_SOURCE_BYTES)?;
let manifest = manifest(&manifest_source)?;
let mut sources = BTreeMap::new();
let mut total = manifest_source.len();
let paths = manifest
.modules
.values()
.map(|m| m.path.clone())
.chain(manifest.styles.iter().cloned())
.chain(manifest.assets.values().cloned())
.collect::<BTreeSet<_>>();
for input_path in paths {
resolve::relative_path(&input_path)?;
let source_path = root.join(&input_path).canonicalize()?;
if !source_path.starts_with(root) {
return Err(input("module path escapes the project root"));
}
let source = artifact::read_text(&source_path, crate::MAX_SOURCE_BYTES)?;
total += source.len();
if total > MAX_PROJECT_BYTES {
return Err(Error::Limit("project source bytes"));
}
sources.insert(input_path, source);
}
compile_sources(manifest_source, sources)
}
/// Load a build by rechecking its source and verifying all generated artifacts.
///
/// # Errors
/// Rejects tampering, unsupported versions, missing files, invalid source, or I/O failures.
///
/// ```no_run
/// let project = diamond::load_project_build(std::path::Path::new(".diamond/build"))?;
/// assert!(project.summary().contains("server"));
/// # Ok::<(), diamond::Error>(())
/// ```
pub fn load_project_build(directory: &Path) -> Result<CheckedProject> {
artifact::load(directory)
}
impl CheckedProject {
/// Describe targets, exported interfaces, and maximum host requirements.
///
/// ```no_run
/// let project = diamond::compile_project(std::path::Path::new("examples/foundations/diamond.toml"))?;
/// assert!(project.summary().contains("Foundations"));
/// # Ok::<(), diamond::Error>(())
/// ```
#[must_use]
pub fn summary(&self) -> String {
format!(
"project {}: {} modules; server {}; browser {} / {}; capabilities {:?}\n",
self.manifest.name,
self.modules.len(),
self.manifest.server,
self.manifest.browser,
self.manifest.component,
self.manifest.provides
)
}
/// Evaluate the checked server entry with an optional explicit local `PostgreSQL` grant.
/// The connection string is never put in build artifacts or diagnostic output.
///
/// # Errors
/// Rejects missing grants, unsupported connection profiles, and runtime failures.
///
/// ```no_run
/// let project = diamond::compile_project(std::path::Path::new("examples/foundations/diamond.toml"))?;
/// assert!(project.evaluate(None).is_err());
/// # Ok::<(), diamond::Error>(())
/// ```
pub fn evaluate(&self, postgres_configuration: Option<&str>) -> Result<Value> {
let principal = Principal::Anonymous;
let mut grants = Effects::new();
if postgres_configuration.is_some() {
if !self.manifest.provides.contains("PostgresRead") {
return Err(Error::Denied);
}
grants.insert(Effect::Host("PostgresRead".into()));
}
let scope = Scope::new(&principal, &grants);
for effect in &self
.server
.functions
.get("main")
.ok_or(Error::Denied)?
.effects
{
scope.require(effect)?;
}
let mut interpreter = crate::eval::Interpreter::new(&self.server, &scope, None, None);
if let Some(configuration) = postgres_configuration {
let mut host = crate::host::HostRuntime::connect(configuration)?;
interpreter.with_host(&mut host).main()
} else {
interpreter.main()
}
}
/// Evaluate the checked server entry with explicit runtime grants.
///
/// The scope carries the entry's checked effects, so an undeclared or
/// unregistered capability still fails with the matching `DataError`. This
/// is the embedding counterpart to serving: it opens no listener and no
/// storage.
///
/// # Errors
/// Rejects missing server entries, runtime authority, and runtime failures.
///
/// ```
/// let project = diamond::compile_project(std::path::Path::new("examples/compute-lab/diamond.toml"))?;
/// let value = project.evaluate_with(&diamond::RuntimeGrants::default())?;
/// assert!(matches!(value.into_result(), Err(diamond::Error::Denied)));
/// # Ok::<(), diamond::Error>(())
/// ```
pub fn evaluate_with(&self, runtime: &crate::RuntimeGrants) -> Result<Value> {
let principal = Principal::Anonymous;
let effects = &self
.server
.functions
.get("main")
.ok_or(Error::Denied)?
.effects;
let scope = Scope::new(&principal, effects);
crate::eval::Interpreter::new(&self.server, &scope, None, None)
.with_integrations(runtime)
.main()
}
/// Verify that every declared compute export is registered with a matching
/// signature. Serving and worker entry points call this before accepting
/// work, so a declaration/registration mismatch is a deployment error
/// rather than a first-use failure.
///
/// # Errors
/// Rejects undeclared, unregistered, or signature-mismatched exports.
///
/// ```
/// let project = diamond::compile_project(std::path::Path::new("examples/compute-lab/diamond.toml"))?;
/// assert!(project.validate_compute(&diamond::RuntimeGrants::default()).is_err());
/// # Ok::<(), diamond::Error>(())
/// ```
pub fn validate_compute(&self, runtime: &crate::RuntimeGrants) -> Result<()> {
runtime.validate_compute(&compute::bindings(&self.manifest)?)
}
/// Render a declared route's public initial component content without host authority.
///
/// # Errors
/// Rejects unknown routes, invalid initial values and resource-budget failures.
///
/// ```
/// let project=diamond::compile_project(std::path::Path::new("examples/foundations/diamond.toml"))?;
/// assert!(project.render_page("/")?.contains("diamond-component"));
/// assert!(project.render_page("/not-declared").is_err());
/// # Ok::<(),diamond::Error>(())
/// ```
pub fn render_page(&self, path: &str) -> Result<String> {
if !self.browser.routes.contains(path) && self.browser.schemas.match_path(path).is_none() {
return Err(input("unknown browser route"));
}
render::render(self, path)
}
/// Write deterministic server/browser artifacts to a new output directory.
///
/// # Errors
/// Rejects an existing destination and returns serialization or filesystem errors.
///
/// ```no_run
/// let project = diamond::compile_project(std::path::Path::new("examples/foundations/diamond.toml"))?;
/// project.build(std::path::Path::new(".diamond/new-build"))?;
/// # Ok::<(), diamond::Error>(())
/// ```
pub fn build(&self, output: &Path) -> Result<()> {
artifact::write(self, output)
}
/// Serve the compiled browser application concurrently on loopback.
/// This W1 skeleton exposes no server function, login, RPC, or production profile.
///
/// # Errors
/// Rejects non-loopback addresses, an existing async runtime, or listener/runtime failures.
///
/// ```no_run
/// let project = diamond::compile_project(std::path::Path::new("examples/foundations/diamond.toml"))?;
/// project.serve("127.0.0.1:3000".parse().map_err(|_|diamond::Error::Input("address".into()))?)?;
/// # Ok::<(), diamond::Error>(())
/// ```
pub fn serve(&self, address: SocketAddr) -> Result<()> {
if !self.rpc.is_empty()
|| self.manifest.identity.is_some()
|| self.manifest.http_api.is_some()
{
return Err(input(
"RPC projects require serve_connected with an explicit PostgreSQL grant and origin",
));
}
server::serve(self, address)
}
/// Initialize the explicitly selected `PostgreSQL` storage profile.
///
/// # Errors
/// Rejects missing/unsupported connection grants or an incompatible stored schema.
///
/// ```no_run
/// let project=diamond::compile_project(std::path::Path::new("examples/workspace/diamond.toml"))?;
/// project.initialize_postgres("host=/tmp/postgres user=diamond dbname=diamond")?;
/// # Ok::<(), diamond::Error>(())
/// ```
pub fn initialize_postgres(&self, configuration: &str) -> Result<()> {
synchronous_context()?;
let mut store = storage::PostgresStore::open(self, configuration, true)?;
store.finish_request(Ok(()))
}
/// Inspect current schema version, shape and backfill progress.
/// Returns a JSON object; this administrative interface requires separate database credentials.
/// Application servers must be stopped before a schema migration; there is no mixed-version support.
///
/// # Errors
/// Rejects missing relational metadata, incompatible schemas, invalid batches or database failures.
///
/// ```no_run
/// let project=diamond::compile_project(std::path::Path::new("examples/relational-workspace/diamond.toml"))?;
/// let report=project.postgres_status("host=/tmp/postgres dbname=diamond")?;
/// assert!(report.starts_with('{'));
/// # Ok::<(), diamond::Error>(())
/// ```
pub fn postgres_status(&self, configuration: &str) -> Result<String> {
synchronous_context()?;
if self.server.storage.is_none() {
return Err(input("administrative command requires relational-v1"));
}
let mut connection = crate::host::HostRuntime::connect_worker(configuration)?;
connection.enable_relational();
let app = artifact::hash(self.manifest.name.as_bytes());
crate::relational::status(&mut connection, &self.server, &app)
}
/// Apply one additive schema version under the migration coordinator.
/// Returns a JSON object; this administrative interface requires separate database credentials.
/// Application servers must be stopped before a schema migration; there is no mixed-version support.
///
/// # Errors
/// Rejects missing relational metadata, incompatible schemas, invalid batches or database failures.
///
/// ```no_run
/// let project=diamond::compile_project(std::path::Path::new("examples/relational-workspace/diamond.toml"))?;
/// let report=project.migrate_postgres("host=/tmp/postgres dbname=diamond")?;
/// assert!(report.starts_with('{'));
/// # Ok::<(), diamond::Error>(())
/// ```
pub fn migrate_postgres(&self, configuration: &str) -> Result<String> {
synchronous_context()?;
if self.server.storage.is_none() {
return Err(input("administrative command requires relational-v1"));
}
let mut connection = crate::host::HostRuntime::connect_worker(configuration)?;
connection.enable_relational();
let app = artifact::hash(self.manifest.name.as_bytes());
crate::relational::migrate(&mut connection, &self.server, &app)
}
/// Commit one resumable backfill batch of 1 through 1,000 rows.
/// Returns a JSON object; this administrative interface requires separate database credentials.
/// Application servers must be stopped before a schema migration; there is no mixed-version support.
///
/// # Errors
/// Rejects missing relational metadata, incompatible schemas, invalid batches or database failures.
///
/// ```no_run
/// let project=diamond::compile_project(std::path::Path::new("examples/relational-workspace/diamond.toml"))?;
/// let report=project.backfill_postgres("host=/tmp/postgres dbname=diamond", 100)?;
/// assert!(report.starts_with('{'));
/// # Ok::<(), diamond::Error>(())
/// ```
pub fn backfill_postgres(&self, configuration: &str, batch: usize) -> Result<String> {
synchronous_context()?;
if self.server.storage.is_none() {
return Err(input("administrative command requires relational-v1"));
}
let mut connection = crate::host::HostRuntime::connect_worker(configuration)?;
connection.enable_relational();
let app = artifact::hash(self.manifest.name.as_bytes());
crate::relational::backfill(&mut connection, &self.server, &app, batch)
}
/// Validate stored records in bounded batches under a consistent snapshot.
/// Returns a JSON object; this administrative interface requires separate database credentials.
/// Application servers must be stopped before a schema migration; there is no mixed-version support.
///
/// # Errors
/// Rejects missing relational metadata, incompatible schemas, invalid batches or database failures.
///
/// ```no_run
/// let project=diamond::compile_project(std::path::Path::new("examples/relational-workspace/diamond.toml"))?;
/// let report=project.audit_postgres("host=/tmp/postgres dbname=diamond")?;
/// assert!(report.starts_with('{'));
/// # Ok::<(), diamond::Error>(())
/// ```
pub fn audit_postgres(&self, configuration: &str) -> Result<String> {
synchronous_context()?;
if self.server.storage.is_none() {
return Err(input("administrative command requires relational-v1"));
}
let mut connection = crate::host::HostRuntime::connect_worker(configuration)?;
connection.enable_relational();
let app = artifact::hash(self.manifest.name.as_bytes());
crate::relational::audit(&mut connection, &self.server, &app)
}
/// Provision a shared development account without replacing an existing password.
///
/// # Errors
/// Rejects invalid credentials, duplicate accounts, incompatible stores and I/O failures.
///
/// ```no_run
/// let project=diamond::compile_project(std::path::Path::new("examples/workspace/diamond.toml"))?;
/// project.add_postgres_user("host=/tmp/postgres dbname=diamond", "alice", "a-long-test-password")?;
/// # Ok::<(), diamond::Error>(())
/// ```
pub fn add_postgres_user(
&self,
configuration: &str,
username: &str,
password: &str,
) -> Result<()> {
synchronous_context()?;
let mut store = storage::PostgresStore::open(self, configuration, false)?;
let result = store.add_user(username, password);
store.finish_request(result)
}
/// Serve generated RPC and a Diamond browser component with shared `PostgreSQL` sessions.
/// The exact public origin is the loopback proxy/browser origin, not a forwarded header.
///
/// # Errors
/// Rejects invalid origins/listeners, missing stores/grants and runtime failures.
///
/// ```no_run
/// let project=diamond::compile_project(std::path::Path::new("examples/workspace/diamond.toml"))?;
/// project.serve_connected("127.0.0.1:3001".parse().map_err(|_|diamond::Error::Input("address".into()))?,
/// "http://localhost:3000", "host=/tmp/postgres dbname=diamond")?;
/// # Ok::<(), diamond::Error>(())
/// ```
pub fn serve_connected(
&self,
address: SocketAddr,
public_origin: &str,
configuration: &str,
) -> Result<()> {
connected::serve(self, address, public_origin, configuration, None)
}
/// Provision a verified accounts-v1 administrator using trusted database authority.
///
/// # Errors
/// Rejects duplicate accounts, invalid input, missing profiles and database failures.
///
/// ```no_run
/// # fn example(project: &diamond::CheckedProject) -> Result<(), diamond::Error> {
/// project.add_postgres_administrator("host=/tmp/postgres dbname=diamond", "alice", "alice@example.invalid", "a-long-test-password")?;
/// # Ok(()) }
/// ```
pub fn add_postgres_administrator(
&self,
configuration: &str,
username: &str,
email: &str,
password: &str,
) -> Result<()> {
synchronous_context()?;
let mut store = storage::PostgresStore::open_control(self, configuration, None)?;
let result = store.provision_account(username, email, password, true);
store.finish_request(result)
}
/// Serve accounts-v1 with an explicitly granted owner-only development mail directory.
/// The directory must already exist with mode 0700; delivered challenges are private 0600 files.
///
/// # Errors
/// Rejects invalid origins, listeners, profiles, mailbox grants or database/runtime failures.
///
/// ```no_run
/// # fn example(project: &diamond::CheckedProject) -> Result<(), diamond::Error> {
/// project.serve_accounts("127.0.0.1:3000".parse().map_err(|_|diamond::Error::Input("address".into()))?,
/// "http://localhost:3000", "host=/tmp/postgres dbname=diamond", std::path::Path::new("/tmp/private-mail"))?;
/// # Ok(()) }
/// ```
pub fn serve_accounts(
&self,
address: SocketAddr,
public_origin: &str,
configuration: &str,
mailbox: &Path,
) -> Result<()> {
connected::serve(self, address, public_origin, configuration, Some(mailbox))
}
/// Serve accounts, files, and integrations using explicit native runtime grants.
///
/// # Errors
/// Rejects missing grants, mismatched shared stores, and invalid server profiles.
///
/// ```no_run
/// let project = diamond::compile_project(std::path::Path::new("examples/files-workspace/diamond.toml"))?;
/// let grants = diamond::RuntimeGrants::from_json(&std::env::var("DIAMOND_RUNTIME")?)?;
/// project.serve_with_runtime("127.0.0.1:3000".parse()?, "http://127.0.0.1:3000",
/// &std::env::var("DIAMOND_POSTGRES")?, std::path::Path::new("/private/mail"), grants)?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn serve_with_runtime(
&self,
address: SocketAddr,
public_origin: &str,
configuration: &str,
mailbox: &Path,
grants: crate::RuntimeGrants,
) -> Result<()> {
connected::serve_runtime(
self,
address,
public_origin,
configuration,
Some(mailbox),
grants,
)
}
/// Initialize a shared object store, or reconcile at most 100 expired objects.
/// All servers must mount the same private durable directory. Reconciliation
/// never deletes a ready attachment and does not publish unfinished uploads.
///
/// # Errors
/// Rejects absent grants, incompatible metadata, unsafe paths and storage errors.
///
/// ```no_run
/// let project = diamond::compile_project(std::path::Path::new("examples/files-workspace/diamond.toml"))?;
/// let grants = diamond::RuntimeGrants::from_json(&std::env::var("DIAMOND_RUNTIME")?)?;
/// let report = project.maintain_files(&std::env::var("DIAMOND_POSTGRES")?, &grants, false)?;
/// assert!(report.contains("removed"));
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn maintain_files(
&self,
configuration: &str,
grants: &crate::RuntimeGrants,
initialize: bool,
) -> Result<String> {
synchronous_context()?;
files::maintain(self, configuration, grants, initialize)
}
/// Bind every declared mail outbox to a private runtime delivery directory.
///
/// # Errors
/// Rejects absent bindings, unsafe roots, reused store identities, or
/// incompatible database metadata.
pub fn initialize_mail(
&self,
configuration: &str,
grants: &crate::RuntimeGrants,
) -> Result<String> {
synchronous_context()?;
mail::initialize(self, configuration, grants)
}
/// Bind every declared Git repository store to this application.
///
/// The private roots and fixed Git executables come from native runtime grants;
/// neither value is exposed to Diamond source or build artifacts.
///
/// # Errors
/// Rejects missing bindings, unsafe roots or executables, identity mismatches,
/// incompatible database metadata, and storage failures.
///
/// ```no_run
/// let project = diamond::compile_project(std::path::Path::new("examples/git-browser/diamond.toml"))?;
/// let grants = diamond::RuntimeGrants::from_json(&std::env::var("DIAMOND_RUNTIME")?)?;
/// let report = project.initialize_git(&std::env::var("DIAMOND_POSTGRES")?, &grants)?;
/// assert!(report.contains("initialized"));
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn initialize_git(
&self,
configuration: &str,
grants: &crate::RuntimeGrants,
) -> Result<String> {
synchronous_context()?;
git::initialize(self, configuration, grants)
}
/// Bind every declared delivery store to this application.
///
/// # Errors
/// Rejects missing grants, unsafe roots or runner executables, identity
/// mismatches, incompatible database metadata, and storage failures.
pub fn initialize_delivery(
&self,
configuration: &str,
grants: &crate::RuntimeGrants,
) -> Result<String> {
synchronous_context()?;
delivery::initialize(self, configuration, grants)
}
/// Claim and run one queued delivery job in the isolated native runner.
///
/// # Errors
/// Rejects invalid grants and records a claimed job as failed when its
/// checkout, sandbox, resource limits, or output publication fails.
pub fn work_delivery_once(
&self,
configuration: &str,
grants: &crate::RuntimeGrants,
) -> Result<String> {
synchronous_context()?;
delivery::work(self, configuration, grants, true)
}
/// Serve the active static Pages deployments on a cookie-free listener.
///
/// # Errors
/// Rejects an unknown binding, invalid grants, listener failures, and
/// incompatible delivery metadata.
pub fn serve_pages(
&self,
address: SocketAddr,
configuration: &str,
grants: &crate::RuntimeGrants,
binding: &str,
) -> Result<()> {
synchronous_context()?;
delivery::serve_pages(self, address, configuration, grants, binding)
}
/// Bind every declared G4 operations store to this application.
///
/// # Errors
/// Rejects missing grants, unsafe roots, incompatible metadata, or changed
/// store identities.
pub fn initialize_operations(
&self,
configuration: &str,
grants: &crate::RuntimeGrants,
) -> Result<String> {
synchronous_context()?;
operations::initialize(self, configuration, grants)
}
/// Claim and execute one bounded search, mirror, or garbage-collection task.
///
/// # Errors
/// Rejects invalid grants, stale task fences, unsafe repositories or object
/// stores, and failed bounded native operations.
pub fn work_operations_once(
&self,
configuration: &str,
grants: &crate::RuntimeGrants,
) -> Result<String> {
synchronous_context()?;
operations::work(self, configuration, grants)
}
/// Promote the configured Git root for one binding with compare-and-swap fencing.
///
/// # Errors
/// Rejects a stale expected generation, the currently active store, unsafe
/// target state, malformed repositories, or a concurrent promotion.
pub fn promote_git(
&self,
configuration: &str,
grants: &crate::RuntimeGrants,
binding: &str,
expected_generation: i64,
) -> Result<String> {
synchronous_context()?;
git::promote(self, configuration, grants, binding, expected_generation)
}
/// Reconcile committed local Git push events into `PostgreSQL`.
///
/// # Errors
/// Rejects unsafe spool files, inconsistent duplicate event identities,
/// unbound stores, excessive pending files, or database failures.
pub fn reconcile_git_events(
&self,
configuration: &str,
grants: &crate::RuntimeGrants,
) -> Result<String> {
synchronous_context()?;
git::reconcile_events(self, configuration, grants)
}
/// Resolve an active enrolled SSH key for an OpenSSH authorized-keys command.
///
/// The returned pair contains the opaque key identifier and canonical public
/// key. Callers must bind the identifier into a forced command and prevent
/// shells, forwarding, agents, port forwarding, and terminals.
///
/// # Errors
/// Rejects unknown, revoked, stale, disabled, malformed, or ambiguous keys,
/// incompatible account state, and database failures.
#[doc(hidden)]
pub fn git_ssh_authorized_key(
&self,
configuration: &str,
fingerprint: &str,
) -> Result<(String, String)> {
synchronous_context()?;
git::authorized_ssh_key(self, configuration, fingerprint)
}
/// Resolve an active repository-scoped OpenSSH certificate principal.
///
/// # Errors
/// Rejects malformed, unknown, expired, revoked, or ambiguous principals and
/// incompatible database state.
#[doc(hidden)]
pub fn git_ssh_authorized_principals(
&self,
configuration: &str,
) -> Result<Vec<(String, String)>> {
synchronous_context()?;
git::authorized_ssh_principals(self, configuration)
}
/// Run one forced-command Git SSH session through the bounded adapter.
///
/// # Errors
/// Rejects inactive keys, unauthorized repositories, unsupported command
/// grammar, unsafe runtime grants, policy failures, and process limits.
#[doc(hidden)]
pub fn run_git_ssh(
&self,
configuration: &str,
grants: &crate::RuntimeGrants,
key_id: &str,
original_command: &str,
) -> Result<()> {
synchronous_context()?;
git::run_ssh(self, configuration, grants, key_id, original_command)
}
}
fn synchronous_context() -> Result<()> {
if tokio::runtime::Handle::try_current().is_ok() {
return Err(input(
"call synchronous project setup outside an async runtime",
));
}
Ok(())
}
fn manifest(source: &str) -> Result<Manifest> {
let manifest: Manifest = toml::from_str(source)
.map_err(|error| input(&format!("invalid project manifest: {error}")))?;
manifest.runtime.checked()?;
if manifest.schema_version != MANIFEST_VERSION {
return Err(input("unsupported project manifest version"));
}
if !resolve::identifier(&manifest.name)
|| manifest.modules.is_empty()
|| manifest.modules.len() > 64
{
return Err(input("project needs a valid name and 1..64 modules"));
}
if !resolve::identifier(&manifest.component) {
return Err(input("invalid root component name"));
}
for capability in &manifest.provides {
capability_effect(capability)?;
}
if let Some(config) = &manifest.identity {
config.checked()?;
if manifest.storage.is_none() {
return Err(input("accounts-v1 requires relational storage"));
}
}
if manifest.git.is_some() && manifest.identity.is_none() {
return Err(input("Git bindings require accounts-v1"));
}
if manifest.delivery.is_some() && (manifest.identity.is_none() || manifest.git.is_none()) {
return Err(input("delivery-v1 requires accounts-v1 and Git"));
}
if manifest.operations.is_some()
&& (manifest.identity.is_none() || manifest.git.is_none() || manifest.delivery.is_none())
{
return Err(input(
"operations-v1 requires accounts-v1, Git, and delivery-v1",
));
}
if manifest.http_api.is_some() && manifest.identity.is_none() {
return Err(input("HTTP APIs require accounts-v1"));
}
if manifest.rpc.len() > 128 {
return Err(input("at most 128 RPC operations are supported"));
}
let mut paths = BTreeSet::new();
for (name, config) in &manifest.modules {
resolve::relative_path(&config.path)?;
if !resolve::identifier(name) || !paths.insert(&config.path) || config.imports.len() > 64 {
return Err(input(
"module names/paths must be valid and unique; imports are bounded",
));
}
if !config.provides.is_subset(&manifest.provides) {
return Err(input("module host budget exceeds the application budget"));
}
if config.target != Target::Server && !config.provides.is_empty() {
return Err(input(
"browser/shared modules cannot receive host capabilities",
));
}
}
for (name, target) in [
(&manifest.server, Target::Server),
(&manifest.browser, Target::Browser),
] {
if !manifest
.modules
.get(name)
.is_some_and(|module| module.target == target)
{
return Err(input("entry module is missing or has the wrong target"));
}
}
if manifest.styles.len() + manifest.assets.len() > 64 {
return Err(input("at most 64 style/asset inputs"));
}
if manifest
.styles
.iter()
.any(|path| Path::new(path).extension().and_then(|e| e.to_str()) != Some("css"))
{
return Err(input("styles require CSS inputs"));
}
for path in manifest.styles.iter().chain(manifest.assets.values()) {
resolve::relative_path(path)?;
if !["css", "svg", "txt"].contains(
&Path::new(path)
.extension()
.and_then(|e| e.to_str())
.unwrap_or_default(),
) {
return Err(input("W3 static inputs support UTF-8 CSS, SVG and text"));
}
}
for (name, path) in &manifest.assets {
if !resolve::identifier(name) || manifest.modules.values().any(|m| &m.path == path) {
return Err(input("invalid asset name or module/asset collision"));
}
}
resolve::order(&manifest.modules)?;
Ok(manifest)
}
fn compile_sources(
manifest_source: String,
sources: BTreeMap<String, String>,
) -> Result<CheckedProject> {
let manifest = manifest(&manifest_source)?;
let paths = manifest
.modules
.values()
.map(|m| m.path.as_str())
.chain(manifest.styles.iter().map(String::as_str))
.chain(manifest.assets.values().map(String::as_str))
.collect::<BTreeSet<_>>();
if sources.keys().map(String::as_str).collect::<BTreeSet<_>>() != paths
|| sources.values().map(String::len).sum::<usize>() + manifest_source.len()
> MAX_PROJECT_BYTES
{
return Err(Error::Limit("project sources"));
}
let modules = parse_modules(&manifest, &sources)?;
let server = check_server(&manifest, &modules)?;
let rpc = checked_operations(&manifest, &modules, &server)?;
let api = api::operations(&manifest, &modules, &server)?;
let queries = queries::checked(&manifest, &modules, &server, &rpc)?;
let jobs = jobs::checked(&manifest, &modules, &server)?;
let workflows = workflows::checked(&manifest, &modules, &server)?;
events::checked(&manifest, &modules, &server)?;
let browser_names = resolve::reachable(&manifest.browser, &manifest.modules);
let browser_source = combined(&modules, &browser_names);
let browser_checked =
crate::checker::check(&browser_source).map_err(|error| locate(&modules, error))?;
let schemas = schemas::Schemas::checked(&modules, &browser_checked)
.map_err(|error| locate(&modules, error))?;
for name in schemas.routes.keys().chain(schemas.forms.keys()) {
if !server.records.contains_key(name) {
return Err(input(
"reactive schemas must be imported by the server and browser",
));
}
}
let root = &modules[&manifest.browser];
if !root.parsed.exports.contains(&manifest.component) {
return Err(input("root browser component must be exported"));
}
let component = root
.parsed
.components
.iter()
.find(|component| root.symbols.get(&manifest.component) == Some(&component.name))
.ok_or_else(|| input("root browser export is not a component"))?;
let components = browser_names
.iter()
.flat_map(|n| modules[n].parsed.components.clone())
.collect::<Vec<_>>();
let mut browser = lower::lower(
&browser_checked,
&component.name,
&components,
lower::Interfaces {
actions: &manifest.actions,
rpc: &rpc,
identity: manifest.identity.as_ref(),
files: manifest.files.as_ref(),
channels: manifest
.events
.iter()
.map(|(n, b)| Ok((n.clone(), events::payload(b, &modules, &manifest, &server)?)))
.collect::<Result<_>>()?,
schemas: &schemas,
},
)
.map_err(|error| locate(&modules, error))?;
let urls = assets::urls(&manifest, &sources)?;