1use super::{
4 ActionName, ActionRef, ActionSpec, AddonName, AddonSpec, Fields, HttpMethod, ModuleName,
5 ModuleSpec, ParamInput, RouteSpec, TableName, TableSpec, ViewSpec,
6};
7use crate::action::functional::FnAction;
8use crate::action::DynAction;
9use crate::action::{Action as BusinessAction, ActionContext, PermissionMode, TypedAction};
10use crate::error::BaseError;
11use schemars::JsonSchema;
12use serde::de::DeserializeOwned;
13use serde::Serialize;
14use std::future::Future;
15use std::marker::PhantomData;
16use std::sync::Arc;
17
18#[derive(Default)]
20pub struct Actions(Vec<(ActionSpec, Arc<dyn DynAction>)>);
21
22impl Actions {
23 pub const fn new() -> Self {
25 Self(Vec::new())
26 }
27
28 pub fn action<A>(mut self, spec: ActionSpec, handler: A) -> Self
30 where
31 A: DynAction,
32 {
33 self.0.push((spec, Arc::new(handler)));
34 self
35 }
36
37 pub fn native<A>(mut self, handler: A) -> Self
39 where
40 A: BusinessAction + TypedAction,
41 {
42 let name = handler.name();
43 let path = if handler.path().is_empty() {
44 format!("/{name}")
45 } else {
46 handler.path().to_string()
47 };
48 let permissions = handler
49 .permissions()
50 .iter()
51 .map(|permission| permission.name().to_string())
52 .collect::<Vec<_>>();
53 let mut spec = ActionSpec::new(
54 super::ActionName::__from_validated_literal(name),
55 super::RouteSpec::new(handler.http_method(), path, name),
56 )
57 .display_name(handler.display_name())
58 .description(handler.description())
59 .permissions(permissions, handler.permission_mode())
60 .public(handler.is_public())
61 .response_kind(handler.response_kind())
62 .success_status(handler.success_status())
63 .params(<A as BusinessAction>::params());
64 if let Some(multipart) = handler.multipart_spec() {
65 spec = spec.multipart(multipart);
66 }
67 for call in handler.calls() {
68 spec = spec.calls(call);
69 }
70 self.0.push((spec, Arc::new(handler)));
71 self
72 }
73
74 pub(crate) fn into_vec(self) -> Vec<(ActionSpec, Arc<dyn DynAction>)> {
75 self.0
76 }
77}
78
79impl std::fmt::Debug for Actions {
80 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
81 formatter
82 .debug_struct("Actions")
83 .field("len", &self.0.len())
84 .finish()
85 }
86}
87
88impl ModuleSpec {
89 pub fn native_action<A>(self, handler: A) -> Self
91 where
92 A: BusinessAction + TypedAction,
93 {
94 let mut values = Actions::new().native(handler).into_vec();
95 let (mut spec, handler) = values.remove(0);
96 if spec.route.operation_id == spec.name.as_str() {
97 spec.route.operation_id = format!("{}.{}", self.name, spec.name);
98 }
99 self.dyn_action(spec, handler)
100 }
101
102 pub fn action_fn<F, I, O, Fut>(self, name: ActionName, handler: F) -> ActionFnBuilder<F, I, O>
126 where
127 F: Fn(ActionContext, I) -> Fut + Send + Sync + 'static,
128 Fut: Future<Output = Result<O, BaseError>> + Send,
129 I: ParamInput + DeserializeOwned + JsonSchema + Send + 'static,
130 O: Serialize + JsonSchema + Send + 'static,
131 {
132 let spec = ActionSpec::new(
133 name.clone(),
134 RouteSpec::new(HttpMethod::Post, format!("/{name}"), name.as_str()),
135 );
136 ActionFnBuilder {
137 module: self,
138 spec,
139 handler,
140 marker: PhantomData,
141 }
142 }
143}
144
145pub struct ActionFnBuilder<F, I, O> {
151 module: ModuleSpec,
152 spec: ActionSpec,
153 handler: F,
154 marker: PhantomData<fn(I) -> O>,
155}
156
157impl<F, I, O> ActionFnBuilder<F, I, O> {
158 #[must_use]
160 pub fn route(mut self, method: HttpMethod, path: impl Into<String>) -> Self {
161 self.spec.route.method = method;
162 self.spec.route.path = path.into();
163 self
164 }
165
166 #[must_use]
168 pub fn display_name(mut self, display_name: impl Into<String>) -> Self {
169 self.spec.display_name = display_name.into();
170 self
171 }
172
173 #[must_use]
175 pub fn description(mut self, description: impl Into<String>) -> Self {
176 self.spec.description = description.into();
177 self
178 }
179
180 #[must_use]
182 pub fn permissions<P, S>(mut self, permissions: P) -> Self
183 where
184 P: IntoIterator<Item = S>,
185 S: Into<String>,
186 {
187 self.spec.permissions = permissions.into_iter().map(Into::into).collect();
188 self
189 }
190
191 #[must_use]
193 pub fn permission_mode(mut self, mode: PermissionMode) -> Self {
194 self.spec.permission_mode = mode;
195 self
196 }
197
198 #[must_use]
200 pub fn public(mut self) -> Self {
201 self.spec.is_public = true;
202 self
203 }
204
205 #[must_use]
207 pub fn success_status(mut self, status: u16) -> Self {
208 self.spec.success_status = status;
209 self
210 }
211
212 #[must_use]
214 pub fn response_kind(mut self, kind: super::ActionResponseKind) -> Self {
215 self.spec.response_kind = kind;
216 self
217 }
218
219 #[must_use]
221 pub fn multipart(mut self, multipart: super::MultipartSpec) -> Self {
222 self.spec = self.spec.multipart(multipart);
223 self
224 }
225
226 #[must_use]
228 pub fn calls(mut self, action: ActionRef) -> Self {
229 self.spec.calls.push(action);
230 self
231 }
232
233 pub fn register<Fut>(mut self) -> ModuleSpec
240 where
241 F: Fn(ActionContext, I) -> Fut + Send + Sync + 'static,
242 Fut: Future<Output = Result<O, BaseError>> + Send,
243 I: ParamInput + DeserializeOwned + JsonSchema + Send + 'static,
244 O: Serialize + JsonSchema + Send + 'static,
245 {
246 self.spec.params = I::params().into_vec();
247 match (
248 serde_json::to_value(schemars::schema_for!(I)),
249 serde_json::to_value(schemars::schema_for!(O)),
250 ) {
251 (Ok(input_schema), Ok(output_schema)) => {
252 self.spec.input_schema = input_schema;
253 self.spec.output_schema = output_schema;
254 }
255 (Err(error), _) | (_, Err(error)) => {
256 self.spec.contract_error = Some(error.to_string());
257 }
258 }
259 let mut spec = self.spec;
260 if spec.route.operation_id == spec.name.as_str() {
261 spec.route.operation_id = format!("{}.{}", self.module.name, spec.name);
262 }
263 self.module
264 .dyn_action(spec, Arc::new(FnAction::<F, I, O>::new(self.handler)))
265 }
266}
267
268#[derive(Debug, Clone, Default)]
270pub struct Modules(Vec<ModuleSpec>);
271
272impl Modules {
273 pub const fn new() -> Self {
275 Self(Vec::new())
276 }
277
278 pub fn module<M>(mut self, module: M) -> Self
280 where
281 M: Module,
282 {
283 self.0.push(module.into_spec());
284 self
285 }
286
287 pub(crate) fn into_vec(self) -> Vec<ModuleSpec> {
288 self.0
289 }
290}
291
292pub trait Module: Sized {
294 fn name(&self) -> ModuleName;
296
297 fn table(&self) -> Option<TableName> {
299 None
300 }
301
302 fn fields(&self) -> Fields {
304 Fields::new()
305 }
306
307 fn configure_table(&self, table: TableSpec) -> TableSpec {
309 table
310 }
311
312 fn actions(&self) -> Actions {
314 Actions::new()
315 }
316
317 fn views(&self) -> Vec<ViewSpec> {
319 Vec::new()
320 }
321
322 fn into_spec(self) -> ModuleSpec {
324 let module_name = self.name();
325 let mut spec = ModuleSpec::new(module_name.clone());
326 if let Some(table) = self.table() {
327 let table = TableSpec::new(table).fields(self.fields());
328 spec = spec.table(self.configure_table(table));
329 }
330 for (mut action, handler) in self.actions().into_vec() {
331 if action.route.operation_id == action.name.as_str() {
332 action.route.operation_id = format!("{}.{}", module_name, action.name);
333 }
334 spec = spec.dyn_action(action, handler);
335 }
336 for view in self.views() {
337 spec = spec.view(view);
338 }
339 spec
340 }
341}
342
343pub trait Addon: Sized {
345 fn name(&self) -> AddonName;
347
348 fn modules(&self) -> Modules;
350
351 fn dependencies(&self) -> Vec<AddonName> {
353 Vec::new()
354 }
355
356 fn into_spec(self) -> AddonSpec {
358 let mut spec = AddonSpec::new(self.name());
359 for dependency in self.dependencies() {
360 spec = spec.depends_on(dependency);
361 }
362 for module in self.modules().into_vec() {
363 spec = spec.module(module);
364 }
365 spec
366 }
367}
368
369impl<T> From<T> for AddonSpec
370where
371 T: Addon,
372{
373 fn from(value: T) -> Self {
374 value.into_spec()
375 }
376}