Repository navigation
Expand file tree
/
Copy pathstorage.rs
More file actions
688 lines (664 loc) · 25.7 KB
/
Copy pathstorage.rs
File metadata and controls
688 lines (664 loc) · 25.7 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
//! W2 bounded `PostgreSQL` document-row profile with checked reference policies.
use super::{CheckedProject, artifact, input, wire};
use crate::authority::{Effect, Scope, random_hex};
use crate::data::{validate_id, validate_input, validate_record};
use crate::error::{Error, Result};
use crate::hir::{CheckedProgram, Record};
use crate::host::HostRuntime;
use crate::policy::Action;
use crate::syntax::Expr;
use crate::value::{Type, Value, ValueBudget, ValueKind};
use std::collections::BTreeMap;
pub(crate) const SCHEMA: &str = "CREATE SCHEMA IF NOT EXISTS diamond_w2;
CREATE TABLE IF NOT EXISTS diamond_w2.apps (app TEXT PRIMARY KEY, profile INTEGER NOT NULL, shape TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS diamond_w2.rows (app TEXT NOT NULL REFERENCES diamond_w2.apps(app), resource TEXT NOT NULL, id TEXT NOT NULL, payload JSON NOT NULL CHECK (octet_length(payload::text)<=32768), PRIMARY KEY(app,resource,id));
CREATE TABLE IF NOT EXISTS diamond_w2.users (app TEXT NOT NULL REFERENCES diamond_w2.apps(app), username TEXT NOT NULL, password_hash TEXT NOT NULL, PRIMARY KEY(app,username));
CREATE TABLE IF NOT EXISTS diamond_w2.sessions (app TEXT NOT NULL REFERENCES diamond_w2.apps(app), digest TEXT NOT NULL, username TEXT, expires TIMESTAMPTZ NOT NULL, PRIMARY KEY(app,digest), FOREIGN KEY(app,username) REFERENCES diamond_w2.users(app,username));
CREATE TABLE IF NOT EXISTS diamond_w2.rates (app TEXT NOT NULL REFERENCES diamond_w2.apps(app), bucket TEXT NOT NULL, attempts INTEGER NOT NULL, expires TIMESTAMPTZ NOT NULL, PRIMARY KEY(app,bucket));";
#[derive(Debug, PartialEq, Eq)]
enum TransactionFailure {
Clean,
Failed,
Conflict,
}
#[derive(Clone, Copy, Debug)]
enum ActionFailure {
Denied,
Invalid,
Aborted,
}
#[derive(Debug)]
pub(crate) struct PostgresStore {
pub(super) connection: crate::relational::Connection,
pub(super) app: String,
pub(super) program: CheckedProgram,
pub(super) identity: Option<super::accounts::Config>,
pub(super) jobs: std::collections::BTreeMap<String, super::jobs::Binding>,
pub(super) events: std::collections::BTreeMap<String, super::events::Binding>,
pub(super) git: Option<super::git::Config>,
pub(super) delivery: Option<super::delivery::Config>,
pub(super) operations: Option<super::operations::Config>,
pub(super) mail: Option<super::mail::Config>,
pub(super) workflows: std::collections::BTreeMap<String, super::workflows::Binding>,
pub(super) event_types: std::collections::BTreeMap<String, Type>,
pub(super) job_version: String,
pub(super) job_operations: std::collections::BTreeMap<String, super::rpc::Operation>,
pub(super) workflow_version: String,
pub(super) workflow_operations:
std::collections::BTreeMap<String, super::workflows::Operations>,
active: bool,
action_lock: Option<String>,
nested: bool,
failure: TransactionFailure,
action_failure: Option<ActionFailure>,
pub(super) action_access: Option<Vec<super::actions::footprint::Access>>,
pub(super) operation_id: String,
}
impl PostgresStore {
pub(super) fn open(
project: &CheckedProject,
configuration: &str,
initialize: bool,
) -> Result<Self> {
Self::open_with(project, configuration, initialize, None)
}
pub(super) fn open_with(
project: &CheckedProject,
configuration: &str,
initialize: bool,
pool: Option<&std::sync::Arc<crate::relational::Pool>>,
) -> Result<Self> {
Self::open_mode(project, configuration, initialize, pool, true, None)
}
pub(super) fn open_control(
project: &CheckedProject,
configuration: &str,
pool: Option<&std::sync::Arc<crate::relational::Pool>>,
) -> Result<Self> {
Self::open_mode(project, configuration, false, pool, false, None)
}
pub(super) fn open_action(
project: &CheckedProject,
configuration: &str,
pool: Option<&std::sync::Arc<crate::relational::Pool>>,
key: &str,
) -> Result<Self> {
Self::open_mode(project, configuration, false, pool, true, Some(key))
}
fn connect(
project: &CheckedProject,
configuration: &str,
pool: Option<&std::sync::Arc<crate::relational::Pool>>,
) -> Result<Self> {
let connection = if let Some(pool) = pool {
pool.acquire()?
} else {
crate::relational::Connection::Direct(HostRuntime::connect_worker(configuration)?)
};
Ok(Self {
connection,
app: artifact::hash(project.manifest.name.as_bytes()),
program: project.server.clone(),
identity: project.manifest.identity.clone(),
jobs: project.manifest.jobs.clone(),
events: project.manifest.events.clone(),
git: project.manifest.git.clone(),
delivery: project.manifest.delivery.clone(),
operations: project.manifest.operations.clone(),
mail: project.manifest.mail.clone(),
workflows: project.manifest.workflows.clone(),
event_types: project
.manifest
.events
.iter()
.map(|(n, b)| {
Ok((
n.clone(),
super::events::payload(
b,
&project.modules,
&project.manifest,
&project.server,
)?,
))
})
.collect::<Result<_>>()?,
job_operations: project.jobs.clone(),
job_version: super::jobs::version(project)?,
workflow_operations: project.workflows.clone(),
workflow_version: super::workflows::version(project)?,
active: false,
action_lock: None,
nested: false,
failure: TransactionFailure::Clean,
action_failure: None,
action_access: None,
operation_id: random_hex()?,
})
}
fn lock_action(&mut self, action_lock: Option<&str>) -> Result<()> {
// Acquire before BEGIN: a duplicate must take a fresh serializable
// snapshot after the previous invocation commits, not before its wait.
if let Some(key) = action_lock {
let key = format!("{}:actions:{key}", self.app);
self.connection.query(
"SELECT pg_catalog.pg_advisory_lock(pg_catalog.hashtextextended($1,0))",
&[&key],
)?;
self.action_lock = Some(key);
}
Ok(())
}
fn open_mode(
project: &CheckedProject,
configuration: &str,
initialize: bool,
pool: Option<&std::sync::Arc<crate::relational::Pool>>,
serializable: bool,
action_lock: Option<&str>,
) -> Result<Self> {
let mut store = Self::connect(project, configuration, pool)?;
store.lock_action(action_lock)?;
if store.program.storage.is_some() {
store.connection.runtime()?.enable_relational();
store
.connection
.relational_batch(if initialize || !serializable {
"BEGIN"
} else {
"BEGIN ISOLATION LEVEL SERIALIZABLE"
})?;
store.active = true;
if initialize {
store.connection.query(
"SELECT pg_catalog.pg_advisory_xact_lock(pg_catalog.hashtextextended($1,0))",
&[&store.app],
)?;
store.connection.batch(SCHEMA)?;
crate::relational::schema::initialize(
store.connection.runtime()?,
&store.program,
&store.app,
)?;
} else {
crate::relational::schema::validate(
store.connection.runtime()?,
&store.program,
&store.app,
)?;
}
if let Some(config) = &store.identity {
if initialize {
super::accounts::initialize(store.connection.runtime()?, &store.app, config)?;
} else {
super::accounts::validate(store.connection.runtime()?, &store.app)?;
}
}
if !project.manifest.actions.is_empty() {
super::actions::schema(&mut store, initialize)?;
}
if let Some(config) = &project.manifest.files {
super::files::schema(&mut store, config, initialize)?;
}
if let Some(config) = &project.manifest.git {
super::git::schema(&mut store, config, initialize)?;
}
if let Some(config) = &project.manifest.delivery {
super::delivery::schema(&mut store, config, initialize)?;
}
if let Some(config) = &project.manifest.operations {
super::operations::schema(&mut store, config, initialize)?;
}
if let Some(config) = &project.manifest.mail {
super::mail::schema(&mut store, config, initialize)?;
}
if !project.manifest.workflows.is_empty() {
super::workflows::schema(&mut store, project, initialize)?;
}
if !store.jobs.is_empty() || !store.events.is_empty() {
super::jobs::schema(&mut store, project, initialize)?;
}
return Ok(store);
}
// Serialize initialization and every request for this application across
// nodes. W4 replaces this coarse correctness boundary with finer locks.
store.connection.batch("BEGIN")?;
store.active = true;
store.connection.query(
"SELECT pg_catalog.pg_advisory_xact_lock(pg_catalog.hashtextextended($1, 0))",
&[&store.app],
)?;
if initialize {
store.connection.batch(SCHEMA)?;
}
let shape = storage_shape(&store.program)?;
if initialize {
store.connection.query("INSERT INTO diamond_w2.apps(app,profile,shape) VALUES ($1,1,$2) ON CONFLICT (app) DO NOTHING", &[&store.app,&shape])?;
}
let rows = store.connection.query(
"SELECT profile,shape FROM diamond_w2.apps WHERE app=$1",
&[&store.app],
)?;
if rows.len() != 1
|| rows[0]
.try_get::<_, i32>(0)
.map_err(|_| input("invalid storage metadata"))?
!= 1
|| rows[0]
.try_get::<_, String>(1)
.map_err(|_| input("invalid storage metadata"))?
!= shape
{
return Err(input(
"missing or incompatible W2 storage profile; initialize explicitly, migrations are later work",
));
}
Ok(store)
}
pub(super) fn attachment(
&mut self,
scope: &Scope<'_>,
resource: &str,
parent: &str,
write: bool,
) -> Result<()> {
crate::relational::Context {
connection: self.connection.runtime()?,
program: &self.program,
app: &self.app,
scope,
}
.attachment(resource, parent, write)
}
pub(crate) fn check_deadline(&self) -> Result<()> {
self.connection.check_deadline()
}
pub(crate) fn begin(&mut self) -> Result<()> {
if !self.active || self.nested {
return Err(input("nested PostgreSQL transaction"));
}
self.nested = true;
Ok(())
}
pub(crate) fn finish<T>(&mut self, result: Result<T>) -> Result<T> {
if !self.nested {
return Err(Error::Denied);
}
self.nested = false;
if let Err(error) = &result {
self.mark_failed(error);
}
if self.failure != TransactionFailure::Clean && result.is_ok() {
Err(if self.failure == TransactionFailure::Conflict {
Error::Conflict
} else {
Error::Aborted
})
} else {
result
}
}
pub(crate) fn mark_failed(&mut self, error: &Error) {
if self.action_failure.is_none() {
self.action_failure = Some(match error {
Error::Denied | Error::Unauthenticated => ActionFailure::Denied,
Error::Input(_) => ActionFailure::Invalid,
_ => ActionFailure::Aborted,
});
}
if matches!(error, Error::Conflict) {
self.failure = TransactionFailure::Conflict;
} else if self.failure == TransactionFailure::Clean {
self.failure = TransactionFailure::Failed;
}
}
pub(super) fn action_failure(&self) -> Option<Error> {
self.action_failure.map(|kind| match kind {
ActionFailure::Denied => Error::Denied,
ActionFailure::Invalid => input("invalid action input"),
ActionFailure::Aborted => Error::Aborted,
})
}
pub(super) fn action_savepoint(&mut self) -> Result<()> {
if !self.active || self.nested {
return Err(Error::Denied);
}
self.connection
.relational_batch("SAVEPOINT diamond_action_body")
}
pub(super) fn rollback_action_body(&mut self) -> Result<()> {
self.connection
.relational_batch("ROLLBACK TO SAVEPOINT diamond_action_body")?;
self.nested = false;
self.failure = TransactionFailure::Clean;
self.action_failure = None;
Ok(())
}
pub(super) fn finish_request<T>(&mut self, result: Result<T>) -> Result<T> {
if !self.active || self.nested {
return Err(Error::Denied);
}
let result = if self.failure != TransactionFailure::Clean && result.is_ok() {
Err(if self.failure == TransactionFailure::Conflict {
Error::Conflict
} else {
Error::Aborted
})
} else {
result
};
let statement = if result.is_ok() { "COMMIT" } else { "ROLLBACK" };
let relational = self.program.storage.is_some();
let finished = if relational {
self.connection.relational_batch(statement)
} else {
self.connection.batch(statement)
};
self.active = false;
if let Err(error) = finished {
self.connection.close();
if relational
&& (statement == "ROLLBACK" || matches!(error, Error::Conflict | Error::Denied))
{
return if statement == "ROLLBACK" {
result
} else {
Err(error)
};
}
return Err(Error::OutcomeUnknown(self.operation_id.clone()));
}
result
}
pub(crate) fn operation(
&mut self,
scope: &Scope<'_>,
resource: &str,
method: &str,
arguments: &[(Option<String>, Expr)],
values: &[Value],
budget: &mut ValueBudget,
) -> Result<Value> {
if self.failure != TransactionFailure::Clean || !self.active {
return Err(Error::Aborted);
}
if self.program.storage.is_some() {
if self.action_access.is_some() {
return self.tracked_operation(scope, resource, method, arguments, values, budget);
}
return crate::relational::Context {
connection: self.connection.runtime()?,
program: &self.program,
app: &self.app,
scope,
}
.operation(resource, method, arguments, values, budget);
}
scope.require(&if ["get", "select"].contains(&method) {
Effect::Read(resource.into())
} else {
Effect::Write(resource.into())
})?;
if ["create", "update"].contains(&method) {
scope.require(&Effect::Read(resource.into()))?;
}
let program = &self.program;
let name = program.resources.get(resource).ok_or(Error::Denied)?;
let record = &program.records[name];
let policy = program.policies.get(resource).ok_or(Error::Denied)?;
let relation = Relation {
program,
name,
record,
policy,
resource,
app: &self.app,
scope,
};
if method == "select" {
return relation.select(self.connection.runtime()?, arguments, values, budget);
}
if method == "create" {
return relation.create(self.connection.runtime()?, values, budget);
}
let id = values.first().ok_or(Error::Denied)?;
validate_id(record, id)?;
let rows=self.connection.query("SELECT payload::text FROM diamond_w2.rows WHERE app=$1 AND resource=$2 AND id=$3 FOR UPDATE", &[&self.app,&resource,&id.display_text()?])?;
let row = rows.first().ok_or(Error::Denied)?;
let before = read_record(row, name, record, program, budget)?;
let ValueKind::Record(_, fields) = &before.0 else {
return Err(Error::Denied);
};
match method {
"get" => {
policy.check(Action::Read, &[fields], scope.principal())?;
Ok(before)
}
"update" => {
let ValueKind::Record(_, input) = &values.get(1).ok_or(Error::Denied)?.0 else {
return Err(Error::Denied);
};
validate_input(record, input)?;
let mut after = budget.copy_fields(fields)?;
after.extend(budget.copy_fields(input)?);
validate_record(record, &after)?;
policy.check(Action::Update, &[fields, &after], scope.principal())?;
policy.check(Action::Read, &[&after], scope.principal())?;
let value = Value(ValueKind::Record(name.clone(), after));
let payload = payload(&value, budget)?;
self.connection.query("UPDATE diamond_w2.rows SET payload=$4::text::json WHERE app=$1 AND resource=$2 AND id=$3", &[&self.app,&resource,&id.display_text()?,&payload])?;
Ok(value)
}
"delete" => {
policy.check(Action::Delete, &[fields], scope.principal())?;
self.connection.query(
"DELETE FROM diamond_w2.rows WHERE app=$1 AND resource=$2 AND id=$3",
&[&self.app, &resource, &id.display_text()?],
)?;
Ok(Value(ValueKind::Unit))
}
_ => Err(Error::Denied),
}
}
}
struct Relation<'a, 'scope> {
program: &'a CheckedProgram,
name: &'a str,
record: &'a Record,
policy: &'a crate::policy::Policy,
resource: &'a str,
app: &'a str,
scope: &'a Scope<'scope>,
}
impl Relation<'_, '_> {
fn select(
&self,
connection: &mut HostRuntime,
arguments: &[(Option<String>, Expr)],
values: &[Value],
budget: &mut ValueBudget,
) -> Result<Value> {
let program = self.program;
let name = self.name;
let record = self.record;
let policy = self.policy;
let resource = self.resource;
let app = self.app;
let scope = self.scope;
let named = arguments
.iter()
.zip(values)
.map(|((name, _), value)| Ok((name.as_deref().ok_or(Error::Denied)?, value)))
.collect::<Result<BTreeMap<_, _>>>()?;
let Some(Value(ValueKind::Int(limit @ 1..=100))) = named.get("limit").copied() else {
return Err(input("selection limit must be 1..100"));
};
let offset = match named.get("offset").copied() {
None => 0,
Some(Value(ValueKind::Int(v @ 0..=1000))) => *v,
_ => return Err(input("selection offset must be 0..1000")),
};
let rows=connection.query("SELECT payload::text FROM diamond_w2.rows WHERE app=$1 AND resource=$2 ORDER BY id COLLATE \"C\" LIMIT 1001", &[&app,&resource])?;
if rows.len() > 1000 {
return Err(Error::Limit("W2 relation rows"));
}
let mut output = Vec::new();
let mut skipped = 0;
for row in rows {
let value = read_record(&row, name, record, program, budget)?;
let ValueKind::Record(_, fields) = &value.0 else {
return Err(Error::Denied);
};
match policy.check(Action::Read, &[fields], scope.principal()) {
Ok(()) => {}
Err(Error::Denied) => continue,
Err(e) => return Err(e),
}
let matches = named.iter().all(|(key, value)| {
["limit", "offset"].contains(key) || fields.get(*key) == Some(*value)
});
if !matches {
continue;
}
if skipped < offset {
skipped += 1;
continue;
}
if output.len() < usize::try_from(*limit).map_err(|_| Error::Denied)? {
output.push(value);
}
}
let value = Value(ValueKind::List(output));
budget.charge(&value)?;
Ok(value)
}
fn create(
&self,
connection: &mut HostRuntime,
values: &[Value],
budget: &mut ValueBudget,
) -> Result<Value> {
let name = self.name;
let record = self.record;
let policy = self.policy;
let resource = self.resource;
let app = self.app;
let scope = self.scope;
let ValueKind::Record(_, input) = &values.first().ok_or(Error::Denied)?.0 else {
return Err(Error::Denied);
};
validate_input(record, input)?;
let mut fields = BTreeMap::new();
for (key, field) in &record.fields {
let value = if key == "id" {
let Type::Id(tag) = &field.ty else {
return Err(Error::Denied);
};
Value(ValueKind::Id(tag.clone(), random_hex()?))
} else if field.created_by {
Value(ValueKind::Id(
"user".into(),
scope.principal().id().ok_or(Error::Denied)?.into(),
))
} else {
budget.copy(
input
.get(key)
.or(field.default.as_ref())
.ok_or_else(|| input_error(key))?,
)?
};
fields.insert(key.clone(), value);
}
validate_record(record, &fields)?;
policy.check(Action::Create, &[&fields], scope.principal())?;
policy.check(Action::Read, &[&fields], scope.principal())?;
let count =
connection.query("SELECT count(*) FROM diamond_w2.rows WHERE app=$1", &[&app])?;
if count[0].try_get::<_, i64>(0).map_err(|_| Error::Denied)? >= 1000 {
return Err(Error::Limit("W2 application rows"));
}
let id = fields["id"].display_text()?;
let value = Value(ValueKind::Record(name.to_owned(), fields));
let payload = payload(&value, budget)?;
connection.query(
"INSERT INTO diamond_w2.rows(app,resource,id,payload) VALUES ($1,$2,$3,$4::text::json)",
&[&app, &resource, &id, &payload],
)?;
Ok(value)
}
}
impl Drop for PostgresStore {
fn drop(&mut self) {
// The owned driver is aborted/joined even if a rollback cannot finish.
if self.active {
let _rollback = self.connection.batch("ROLLBACK");
}
if let Some(key) = self.action_lock.take()
&& self
.connection
.query(
"SELECT pg_catalog.pg_advisory_unlock(pg_catalog.hashtextextended($1,0))",
&[&key],
)
.is_err()
{
self.connection.close();
}
}
}
fn payload(value: &Value, budget: &mut ValueBudget) -> Result<String> {
budget.charge(value)?;
let payload = serde_json::to_string(&wire::encode(value)?)
.map_err(|_| input("record encoding failed"))?;
if payload.len() > 16_384 {
return Err(Error::Limit("W2 record payload"));
}
Ok(payload)
}
fn read_record(
row: &tokio_postgres::Row,
name: &str,
record: &Record,
program: &CheckedProgram,
budget: &mut ValueBudget,
) -> Result<Value> {
let text: String = row.try_get(0).map_err(|_| input("invalid stored row"))?;
if text.len() > 32_768 {
return Err(Error::Limit("W2 stored payload"));
}
let json = serde_json::from_str(&text).map_err(|_| input("invalid stored row"))?;
let value = wire::decode(&Type::Record(name.into()), &json, program)?;
let ValueKind::Record(_, fields) = &value.0 else {
return Err(Error::Denied);
};
validate_record(record, fields)?;
budget.charge(&value)?;
Ok(value)
}
fn storage_shape(program: &CheckedProgram) -> Result<String> {
let shape = program
.resources
.iter()
.map(|(resource, name)| {
let fields = program.records[name]
.fields
.iter()
.map(|(name, field)| {
Ok((
name.clone(),
field.ty.to_string(),
field.created_by,
field.default.as_ref().map(wire::encode).transpose()?,
))
})
.collect::<Result<Vec<_>>>()?;
Ok((resource, name, fields))
})
.collect::<Result<Vec<_>>>()?;
let bytes = serde_json::to_vec(&shape).map_err(|_| input("storage shape encoding failed"))?;
Ok(artifact::hash(&bytes))
}
fn input_error(field: &str) -> Error {
input(&format!("missing create field {field}"))
}