1use toasty::stmt::{Expr, List, OrderByExpr, Query};
8use topcoat::{Result, context::Cx};
9
10use crate::BoxFuture;
11
12pub trait OptionSource: Sized + Send + Sync + 'static {
21 type Model: toasty::schema::Model + toasty::stmt::IntoExpr<Self::Model> + Send + Sync + 'static;
23
24 fn scoped_query(cx: &Cx) -> Result<Query<List<Self::Model>>>;
27
28 fn lists(_cx: &Cx) -> bool {
32 false
33 }
34
35 fn requires_tenant(_cx: &Cx) -> bool {
42 false
43 }
44
45 fn search_expr(_cx: &Cx, _term: &str) -> Option<Expr<bool>> {
48 None
49 }
50
51 fn order_by(_cx: &Cx) -> Option<OrderByExpr> {
53 None
54 }
55
56 fn label(cx: &Cx, record: &Self::Model) -> String;
63
64 #[doc(hidden)]
67 fn available(_cx: &Cx) -> bool {
68 true
69 }
70
71 #[doc(hidden)]
74 fn hidden_fields(_cx: &Cx) -> Vec<String> {
75 Vec::new()
76 }
77
78 #[doc(hidden)]
80 fn creates() -> bool {
81 false
82 }
83
84 #[doc(hidden)]
87 fn create_page(_cx: &Cx) -> Option<String> {
88 None
89 }
90}
91
92#[derive(Debug, Clone, PartialEq, Eq)]
95pub(crate) enum OptionLoadError {
96 Denied,
97 LoadFailed,
98 Overflow,
99 Misdeclared,
100}
101
102pub(crate) type RelationshipLoader = std::sync::Arc<
103 dyn Fn(&Cx) -> BoxFuture<'static, Result<Vec<(String, String)>, OptionLoadError>> + Send + Sync,
104>;
105
106pub(crate) type RelationshipSearchLoader = std::sync::Arc<
107 dyn Fn(
108 &Cx,
109 String,
110 Option<Expr<bool>>,
111 ) -> BoxFuture<'static, Result<Vec<(String, String)>, OptionLoadError>>
112 + Send
113 + Sync,
114>;
115
116pub(crate) type RelationshipNamer = std::sync::Arc<
119 dyn Fn(&Cx, String) -> BoxFuture<'static, Result<Option<(String, String)>, OptionLoadError>>
120 + Send
121 + Sync,
122>;
123
124pub(crate) type RelationshipChecker = std::sync::Arc<
125 dyn for<'a> Fn(
126 &'a Cx,
127 String,
128 Option<Expr<bool>>,
129 &'a mut dyn toasty::Executor,
130 ) -> BoxFuture<'a, Result<bool, OptionLoadError>>
131 + Send
132 + Sync,
133>;
134
135pub(crate) fn ensure_option_access<R>(cx: &Cx) -> Result<(), OptionLoadError>
138where
139 R: OptionSource,
140{
141 if !R::lists(cx) {
142 return Err(OptionLoadError::Denied);
143 }
144 if R::requires_tenant(cx) && crate::tenancy::tenant_id(cx).is_none() {
145 return Err(OptionLoadError::Denied);
146 }
147 Ok(())
148}
149
150fn option_query<R>(cx: &Cx) -> Result<Query<List<R::Model>>, OptionLoadError>
153where
154 R: OptionSource,
155{
156 R::scoped_query(cx).map_err(|error| {
157 tracing::error!(
158 resource = std::any::type_name::<R>(),
159 error = %error,
160 "relationship option load cannot scope the related resource"
161 );
162 OptionLoadError::Misdeclared
163 })
164}
165
166pub const MAX_RELATIONSHIP_OPTIONS: usize = 200;
168
169#[topcoat::context::memoize(as_ref)]
171pub(crate) async fn related_records<R>(
172 cx: &Cx,
173 _tenant: Option<crate::TenantId>,
174) -> Result<Vec<R::Model>, OptionLoadError>
175where
176 R: OptionSource,
177{
178 ensure_option_access::<R>(cx)?;
179 let mut query = option_query::<R>(cx)?;
180 if let Some(ord) = R::order_by(cx) {
181 query = query.order_by(ord);
182 }
183 bounded_options::<R>(
184 cx,
185 query,
186 "relationship option load failed",
187 "relationship option table overflows the cap",
188 )
189 .await
190}
191
192async fn bounded_options<R>(
194 cx: &Cx,
195 query: Query<List<R::Model>>,
196 failed: &str,
197 overflow: &str,
198) -> Result<Vec<R::Model>, OptionLoadError>
199where
200 R: OptionSource,
201{
202 let mut db = crate::db::db(cx).map_err(|_| OptionLoadError::Misdeclared)?;
203 let records = query
204 .limit(MAX_RELATIONSHIP_OPTIONS + 1)
205 .exec(&mut db)
206 .await
207 .map_err(|e| {
208 tracing::warn!(
209 resource = std::any::type_name::<R>(),
210 error = %e,
211 "{failed}"
212 );
213 OptionLoadError::LoadFailed
214 })?;
215 if records.len() > MAX_RELATIONSHIP_OPTIONS {
216 tracing::warn!(
217 resource = std::any::type_name::<R>(),
218 max = MAX_RELATIONSHIP_OPTIONS,
219 "{overflow}"
220 );
221 return Err(OptionLoadError::Overflow);
222 }
223 Ok(records)
224}
225
226pub(crate) const MAX_QUERY_TERM: usize = 128;
229
230pub(crate) fn clamp_query_term(term: &str) -> String {
233 term.trim().chars().take(MAX_QUERY_TERM).collect()
234}
235
236pub(crate) async fn related_records_search<R>(
239 cx: &Cx,
240 q: String,
241 scope: Option<Expr<bool>>,
242) -> Result<Vec<R::Model>, OptionLoadError>
243where
244 R: OptionSource,
245{
246 ensure_option_access::<R>(cx)?;
247 let term = clamp_query_term(&q);
248 let mut query = option_query::<R>(cx)?;
249 if let Some(scope) = scope {
250 query = query.filter(scope);
251 }
252 if !term.is_empty()
253 && let Some(expr) = R::search_expr(cx, &term)
254 {
255 query = query.filter(crate::toasty_compat::case_insensitive_search(
256 &crate::db::db(cx).map_err(|_| OptionLoadError::Misdeclared)?,
257 expr,
258 ));
259 }
260 if let Some(ord) = R::order_by(cx) {
261 query = query.order_by(ord);
262 }
263 bounded_options::<R>(
264 cx,
265 query,
266 "relationship option search failed",
267 "relationship option search overflows the cap",
268 )
269 .await
270}
271
272pub(crate) async fn related_record<R>(
274 cx: &Cx,
275 key: &str,
276) -> Result<Option<R::Model>, OptionLoadError>
277where
278 R: OptionSource,
279{
280 ensure_option_access::<R>(cx)?;
281 let Some(expr) = crate::toasty_compat::pk::pk_eq_expr::<R::Model>(key.trim()) else {
282 return Ok(None);
283 };
284 option_query::<R>(cx)?
285 .filter(expr)
286 .first()
287 .exec(&mut crate::db::db(cx).map_err(|_| OptionLoadError::Misdeclared)?)
288 .await
289 .map_err(|e| {
290 tracing::warn!(
291 resource = std::any::type_name::<R>(),
292 error = %e,
293 "relationship option read failed"
294 );
295 OptionLoadError::LoadFailed
296 })
297}
298
299pub(crate) async fn related_record_check<R>(
302 cx: &Cx,
303 value: String,
304 scope: Option<Expr<bool>>,
305 ex: &mut dyn toasty::Executor,
306) -> Result<bool, OptionLoadError>
307where
308 R: OptionSource,
309{
310 ensure_option_access::<R>(cx)?;
311 let trimmed = value.trim();
312 let Some(expr) = crate::toasty_compat::pk::pk_eq_expr::<R::Model>(trimmed) else {
313 return Ok(false);
314 };
315 let mut query = option_query::<R>(cx)?.filter(expr);
316 if let Some(scope) = scope {
317 query = query.filter(scope);
318 }
319 let row = query.first().exec(ex).await.map_err(|e| {
320 tracing::warn!(
321 resource = std::any::type_name::<R>(),
322 error = %e,
323 "relationship option check failed"
324 );
325 OptionLoadError::LoadFailed
326 })?;
327 Ok(row.is_some())
328}
329
330#[topcoat::context::memoize(as_ref)]
334pub(crate) async fn held_keys<R>(
335 cx: &Cx,
336 _tenant: Option<crate::TenantId>,
337 keys: &[String],
338) -> Result<std::collections::HashSet<String>, OptionLoadError>
339where
340 R: OptionSource,
341{
342 ensure_option_access::<R>(cx)?;
343 let Some(any) = keys
344 .iter()
345 .filter_map(|key| crate::toasty_compat::pk::pk_eq_expr::<R::Model>(key))
346 .reduce(|any, one| any.or(one))
347 else {
348 return Ok(std::collections::HashSet::new());
349 };
350 let rows = option_query::<R>(cx)?
351 .filter(any)
352 .exec(&mut crate::db::db(cx).map_err(|_| OptionLoadError::Misdeclared)?)
353 .await
354 .map_err(|e| {
355 tracing::warn!(
356 resource = std::any::type_name::<R>(),
357 error = %e,
358 "relationship filter check failed"
359 );
360 OptionLoadError::LoadFailed
361 })?;
362 Ok(rows.iter().map(crate::toasty_compat::pk::pk_text).collect())
363}
364
365#[cfg(test)]
366mod tests;