use std::collections::{BTreeMap, HashMap};
use std::sync::{Arc, Mutex};
mod values;
pub(crate) use values::open_stored;
pub use values::{CustomValues, Opened, SEALED_PREFIX, is_sealed};
use crate::auth::AuthUser;
pub const MASK: &str = "••••••";
pub const REVEAL_ABILITY: &str = "custom_fields.reveal";
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::db::{DateTime, Db, Migration, Row, now, sql};
use crate::{Error, Result};
pub(crate) const MIGRATION: Migration =
crate::db::framework_migration!("custom_fields", "00010101000430_create_custom_fields_table");
pub const DEFAULT_LABEL_LOCALE: &str = "en";
const MAX_KEY: usize = 64;
#[derive(Clone, Default)]
pub(crate) struct Cache(Arc<Mutex<HashMap<String, Arc<Vec<CustomField>>>>>);
impl Cache {
fn get(&self, model: &str) -> Option<Arc<Vec<CustomField>>> {
self.0
.lock()
.unwrap_or_else(|e| e.into_inner())
.get(model)
.cloned()
}
fn put(&self, model: &str, fields: Arc<Vec<CustomField>>) {
self.0
.lock()
.unwrap_or_else(|e| e.into_inner())
.insert(model.to_owned(), fields);
}
fn forget(&self, model: &str) {
self.0
.lock()
.unwrap_or_else(|e| e.into_inner())
.remove(model);
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum FieldKind {
Text,
Number,
Date,
Bool,
Choice,
Reference,
File,
}
impl FieldKind {
pub fn as_str(self) -> &'static str {
match self {
FieldKind::Text => "text",
FieldKind::Number => "number",
FieldKind::Date => "date",
FieldKind::Bool => "bool",
FieldKind::Choice => "choice",
FieldKind::Reference => "reference",
FieldKind::File => "file",
}
}
pub fn parse(name: &str) -> Option<Self> {
Some(match name {
"text" => FieldKind::Text,
"number" => FieldKind::Number,
"date" => FieldKind::Date,
"bool" => FieldKind::Bool,
"choice" => FieldKind::Choice,
"reference" => FieldKind::Reference,
"file" => FieldKind::File,
_ => return None,
})
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct LocaleMap(pub BTreeMap<String, String>);
impl LocaleMap {
pub fn resolve(&self, locale: &str, fallback: &str) -> Option<&str> {
[locale, fallback, DEFAULT_LABEL_LOCALE]
.into_iter()
.find_map(|l| self.0.get(l))
.or_else(|| self.0.values().next())
.map(String::as_str)
}
pub fn set(&mut self, locale: impl Into<String>, text: impl Into<String>) {
self.0.insert(locale.into(), text.into());
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChoiceOption {
pub value: String,
#[serde(default)]
pub label: LocaleMap,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct FieldRules {
#[serde(default)]
pub required: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub min: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max: Option<i64>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub options: Vec<ChoiceOption>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub target: Option<String>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub sensitive: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reveal: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
#[non_exhaustive]
pub struct CustomField {
pub id: i64,
pub model: String,
pub key: String,
pub kind: FieldKind,
pub label: LocaleMap,
pub rules: FieldRules,
pub meta: Value,
pub position: i64,
pub active: bool,
pub created_at: DateTime,
pub updated_at: DateTime,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
#[non_exhaustive]
pub struct FieldView {
pub key: String,
pub kind: FieldKind,
pub label: String,
pub required: bool,
pub min: Option<i64>,
pub max: Option<i64>,
pub options: Vec<(String, String)>,
pub labels: BTreeMap<String, String>,
pub target: Option<String>,
pub meta: Value,
pub sensitive: bool,
pub masked: bool,
}
pub fn is_valid_key(key: &str) -> bool {
let mut chars = key.chars();
key.len() <= MAX_KEY
&& chars.next().is_some_and(|c| c.is_ascii_lowercase())
&& chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
}
impl CustomField {
fn new(model: &str, key: &str, kind: FieldKind) -> Self {
let at = now();
CustomField {
id: 0,
model: model.to_owned(),
key: key.to_owned(),
kind,
label: LocaleMap::default(),
rules: FieldRules::default(),
meta: Value::Null,
position: 0,
active: true,
created_at: at,
updated_at: at,
}
}
pub fn text(model: &str, key: &str) -> Self {
Self::new(model, key, FieldKind::Text)
}
pub fn number(model: &str, key: &str) -> Self {
Self::new(model, key, FieldKind::Number)
}
pub fn date(model: &str, key: &str) -> Self {
Self::new(model, key, FieldKind::Date)
}
pub fn bool(model: &str, key: &str) -> Self {
Self::new(model, key, FieldKind::Bool)
}
pub fn choice(model: &str, key: &str) -> Self {
Self::new(model, key, FieldKind::Choice)
}
pub fn reference(model: &str, key: &str, target: &str) -> Self {
let mut field = Self::new(model, key, FieldKind::Reference);
field.rules.target = Some(target.to_owned());
field
}
pub fn file(model: &str, key: &str, disk: &str) -> Self {
let mut field = Self::new(model, key, FieldKind::File);
field.rules.target = Some(disk.to_owned());
field
}
pub fn label(self, text: &str) -> Self {
self.label_in(DEFAULT_LABEL_LOCALE, text)
}
pub fn label_in(mut self, locale: &str, text: &str) -> Self {
self.label.set(locale, text);
self
}
pub fn required(mut self) -> Self {
self.rules.required = true;
self
}
pub fn max(mut self, max: i64) -> Self {
self.rules.max = Some(max);
self
}
pub fn min(mut self, min: i64) -> Self {
self.rules.min = Some(min);
self
}
pub fn options(mut self, values: &[&str]) -> Self {
self.rules.options = values
.iter()
.map(|v| ChoiceOption {
value: (*v).to_owned(),
label: LocaleMap::default(),
})
.collect();
self
}
pub fn option_labeled(mut self, value: &str, label: LocaleMap) -> Self {
self.rules.options.push(ChoiceOption {
value: value.to_owned(),
label,
});
self
}
pub fn meta(mut self, meta: Value) -> Self {
self.meta = meta;
self
}
pub fn sensitive(mut self) -> Self {
self.rules.sensitive = true;
self
}
pub fn reveal_with(mut self, ability: &str) -> Self {
self.rules.sensitive = true;
self.rules.reveal = Some(ability.to_owned());
self
}
pub fn position(mut self, position: i64) -> Self {
self.position = position;
self
}
pub fn inactive(mut self) -> Self {
self.active = false;
self
}
pub fn label_for(&self, locale: &str, fallback: &str) -> String {
self.label
.resolve(locale, fallback)
.unwrap_or(&self.key)
.to_owned()
}
fn view(&self, locale: &str, fallback: &str, viewer: Option<&AuthUser>) -> FieldView {
let options: Vec<(String, String)> = self
.rules
.options
.iter()
.map(|o| {
let label = o.label.resolve(locale, fallback).unwrap_or(&o.value);
(o.value.clone(), label.to_owned())
})
.collect();
FieldView {
key: self.key.clone(),
kind: self.kind,
label: self.label_for(locale, fallback),
required: self.rules.required,
min: self.rules.min,
max: self.rules.max,
labels: options.iter().cloned().collect(),
options,
target: self.rules.target.clone(),
meta: self.meta.clone(),
sensitive: self.rules.sensitive,
masked: !self.can_reveal(viewer),
}
}
pub fn can_reveal(&self, viewer: Option<&AuthUser>) -> bool {
if !self.rules.sensitive {
return true;
}
let ability = self.rules.reveal.as_deref().unwrap_or(REVEAL_ABILITY);
viewer.is_some_and(|auth| auth.allows(ability))
}
pub async fn views(db: &Db, model: &str, locale: &str) -> Result<Vec<FieldView>> {
Self::views_for(db, model, locale, None).await
}
pub async fn views_for(
db: &Db,
model: &str,
locale: &str,
viewer: Option<&AuthUser>,
) -> Result<Vec<FieldView>> {
let fields = Self::for_model(db, model).await?;
Ok(fields
.iter()
.map(|f| f.view(locale, DEFAULT_LABEL_LOCALE, viewer))
.collect())
}
fn check(&self) -> Result<()> {
let bad = |msg: String| Err(Error::BadRequest(msg));
if !is_valid_key(&self.key) {
return bad(format!(
"custom field key `{}` must match [a-z][a-z0-9_]* (at most {MAX_KEY} characters)",
self.key.escape_debug()
));
}
if self.model.trim().is_empty() {
return bad("custom field model must not be empty".into());
}
if self.kind == FieldKind::Choice && self.rules.options.is_empty() {
return bad(format!("choice field `{}` needs options", self.key));
}
if matches!(self.kind, FieldKind::Reference | FieldKind::File)
&& self.rules.target.as_deref().is_none_or(str::is_empty)
{
return bad(format!(
"{} field `{}` needs a target",
self.kind.as_str(),
self.key
));
}
if self.rules.sensitive && matches!(self.kind, FieldKind::Reference | FieldKind::File) {
return bad(format!(
"{} field `{}` can't be sensitive: a sealed id or file key would not protect the record or file",
self.kind.as_str(),
self.key
));
}
if self
.rules
.reveal
.as_deref()
.is_some_and(|r| r.trim().is_empty())
{
return bad(format!("field `{}`: the reveal ability is empty", self.key));
}
if let (Some(min), Some(max)) = (self.rules.min, self.rules.max)
&& min > max
{
return bad(format!("field `{}`: min is above max", self.key));
}
Ok(())
}
pub async fn save(&self, db: &Db) -> Result<CustomField> {
self.check()?;
let label = serde_json::to_string(&self.label).map_err(anyhow::Error::from)?;
let rules = serde_json::to_string(&self.rules).map_err(anyhow::Error::from)?;
let meta = serde_json::to_string(&self.meta).map_err(anyhow::Error::from)?;
let at = now();
let id = if self.id == 0 {
sql("INSERT INTO custom_fields \
(model, key, kind, label, rules, meta, position, active, created_at, updated_at) \
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id")
.bind(self.model.as_str())
.bind(self.key.as_str())
.bind(self.kind.as_str())
.bind(label)
.bind(rules)
.bind(meta)
.bind(self.position)
.bind(i64::from(self.active))
.bind(at)
.bind(at)
.scalar::<i64>(db)
.await?
} else {
let changed = sql("UPDATE custom_fields SET label = ?, rules = ?, meta = ?, \
position = ?, active = ?, updated_at = ? WHERE id = ?")
.bind(label)
.bind(rules)
.bind(meta)
.bind(self.position)
.bind(i64::from(self.active))
.bind(at)
.bind(self.id)
.execute(db)
.await?;
if changed == 0 {
return Err(Error::NotFound);
}
self.id
};
db.custom_fields_cache().forget(&self.model);
let stored = Self::find(db, id).await?.ok_or(Error::NotFound)?;
db.custom_fields_cache().forget(&stored.model);
Ok(stored)
}
pub async fn find(db: &Db, id: i64) -> Result<Option<CustomField>> {
let row = sql(SELECT_BY_ID).bind(id).fetch_optional(db).await?;
row.as_ref().map(read).transpose()
}
pub async fn for_model(db: &Db, model: &str) -> Result<Arc<Vec<CustomField>>> {
if let Some(cached) = db.custom_fields_cache().get(model) {
return Ok(cached);
}
let fields = Arc::new(Self::list_for(db, model, false).await?);
db.custom_fields_cache().put(model, fields.clone());
Ok(fields)
}
pub async fn all_for_model(db: &Db, model: &str) -> Result<Vec<CustomField>> {
Self::list_for(db, model, true).await
}
async fn list_for(db: &Db, model: &str, inactive: bool) -> Result<Vec<CustomField>> {
let query = if inactive {
"SELECT * FROM custom_fields WHERE model = ? ORDER BY position, id"
} else {
"SELECT * FROM custom_fields WHERE model = ? AND active = 1 ORDER BY position, id"
};
let rows = sql(query).bind(model).fetch_all(db).await?;
rows.iter().map(read).collect()
}
pub async fn deactivate(db: &Db, id: i64) -> Result<()> {
Self::set_active(db, id, false).await
}
pub async fn activate(db: &Db, id: i64) -> Result<()> {
Self::set_active(db, id, true).await
}
async fn set_active(db: &Db, id: i64, active: bool) -> Result<()> {
let found = Self::find(db, id).await?.ok_or(Error::NotFound)?;
sql("UPDATE custom_fields SET active = ?, updated_at = ? WHERE id = ?")
.bind(i64::from(active))
.bind(now())
.bind(id)
.execute(db)
.await?;
db.custom_fields_cache().forget(&found.model);
Ok(())
}
pub async fn delete(db: &Db, id: i64) -> Result<()> {
let found = Self::find(db, id).await?.ok_or(Error::NotFound)?;
sql("DELETE FROM custom_fields WHERE id = ?")
.bind(id)
.execute(db)
.await?;
db.custom_fields_cache().forget(&found.model);
Ok(())
}
pub fn forget(db: &Db, model: &str) {
db.custom_fields_cache().forget(model);
}
}
const SELECT_BY_ID: &str = "SELECT * FROM custom_fields WHERE id = ?";
fn json<T: serde::de::DeserializeOwned>(row: &Row, column: &str) -> Result<T> {
let text: String = row.try_get(column)?;
Ok(serde_json::from_str(&text).map_err(anyhow::Error::from)?)
}
fn read(row: &Row) -> Result<CustomField> {
let kind: String = row.try_get("kind")?;
Ok(CustomField {
id: row.try_get("id")?,
model: row.try_get("model")?,
key: row.try_get("key")?,
kind: FieldKind::parse(&kind)
.ok_or_else(|| anyhow::anyhow!("unknown custom field kind `{kind}`"))?,
label: json(row, "label")?,
rules: json(row, "rules")?,
meta: json(row, "meta")?,
position: row.try_get("position")?,
active: row.try_get::<i64>("active")? != 0,
created_at: row.try_get("created_at")?,
updated_at: row.try_get("updated_at")?,
})
}