-
Notifications
You must be signed in to change notification settings - Fork 193
Adding metadata to application CRUD group #705
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
2 changes: 2 additions & 0 deletions
2
server/svix-server/migrations/20221104170041_add_applicationmetadata.down.sql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
-- Add down migration script here | ||
DROP TABLE IF EXISTS applicationmetadata; |
10 changes: 10 additions & 0 deletions
10
server/svix-server/migrations/20221104170041_add_applicationmetadata.up.sql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
-- Add up migration script here | ||
CREATE TABLE applicationmetadata ( | ||
created_at timestamp with time zone NOT NULL, | ||
updated_at timestamp with time zone NOT NULL, | ||
id character varying NOT NULL COLLATE pg_catalog."C", | ||
data jsonb NOT NULL | ||
); | ||
|
||
ALTER TABLE ONLY applicationmetadata | ||
ADD CONSTRAINT applicationmetadata_pkey PRIMARY KEY (id); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
use std::collections::HashMap; | ||
|
||
use crate::json_wrapper; | ||
use serde::{Deserialize, Serialize}; | ||
|
||
pub const MAX_METADATA_SIZE: usize = 4096; | ||
|
||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Default)] | ||
pub struct Metadata(HashMap<String, String>); | ||
|
||
json_wrapper!(Metadata); | ||
|
||
impl Metadata { | ||
pub fn is_empty(&self) -> bool { | ||
self.0.is_empty() | ||
} | ||
} | ||
|
||
impl<'de> Deserialize<'de> for Metadata { | ||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> | ||
where | ||
D: serde::Deserializer<'de>, | ||
{ | ||
let inner: Option<HashMap<String, String>> = Deserialize::deserialize(deserializer)?; | ||
let metadata = inner.unwrap_or_default(); // coerce `null` to `{}` | ||
|
||
let size = serde_json::to_string(&metadata) | ||
.map(|blob| blob.len()) | ||
.map_err(|_| serde::de::Error::custom("metadata is not valid json"))?; | ||
|
||
if size > MAX_METADATA_SIZE { | ||
return Err(serde::de::Error::custom(format!( | ||
"metadata must be less than or equal to {MAX_METADATA_SIZE} bytes" | ||
))); | ||
} | ||
|
||
Ok(Self(metadata)) | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
100 changes: 100 additions & 0 deletions
100
server/svix-server/src/db/models/applicationmetadata.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,100 @@ | ||
// SPDX-FileCopyrightText: © 2022 Svix Authors | ||
// SPDX-License-Identifier: MIT | ||
use crate::core::types::ApplicationId; | ||
|
||
use crate::core::types::metadata::Metadata; | ||
use crate::{ctx, error}; | ||
use chrono::Utc; | ||
use sea_orm::entity::prelude::*; | ||
use sea_orm::sea_query::OnConflict; | ||
use sea_orm::ActiveValue::Set; | ||
use sea_orm::{ConnectionTrait, TryIntoModel}; | ||
|
||
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)] | ||
#[sea_orm(table_name = "applicationmetadata")] | ||
pub struct Model { | ||
#[sea_orm(primary_key, auto_increment = false)] | ||
pub id: ApplicationId, | ||
pub created_at: DateTimeWithTimeZone, | ||
pub updated_at: DateTimeWithTimeZone, | ||
pub data: Metadata, | ||
} | ||
|
||
impl Model { | ||
pub fn metadata(self) -> Metadata { | ||
self.data | ||
} | ||
|
||
pub fn new(app_id: ApplicationId) -> Self { | ||
ActiveModel::new(app_id, None) | ||
.try_into_model() | ||
.expect("ActiveModel::create(...) should have set all fields") | ||
} | ||
} | ||
|
||
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] | ||
pub enum Relation { | ||
#[sea_orm( | ||
belongs_to = "super::application::Entity", | ||
from = "Column::Id", | ||
to = "super::application::Column::Id", | ||
on_update = "NoAction", | ||
on_delete = "Restrict" | ||
)] | ||
Application, | ||
} | ||
|
||
impl Related<super::application::Entity> for Entity { | ||
fn to() -> RelationDef { | ||
Relation::Application.def() | ||
} | ||
} | ||
|
||
impl ActiveModelBehavior for ActiveModel { | ||
fn before_save(mut self, _insert: bool) -> Result<Self, DbErr> { | ||
self.updated_at = Set(Utc::now().into()); | ||
Ok(self) | ||
} | ||
} | ||
|
||
impl ActiveModel { | ||
pub fn new(app_id: ApplicationId, metadata: impl Into<Option<Metadata>>) -> Self { | ||
let id = Set(app_id); | ||
let data = Set(metadata.into().unwrap_or_default()); | ||
let timestamp = Utc::now(); | ||
Self { | ||
id, | ||
data, | ||
created_at: Set(timestamp.into()), | ||
updated_at: Set(timestamp.into()), | ||
} | ||
} | ||
|
||
/// Upserts the record if it's new or updated, AND data is nonempty. Otherwise the record is | ||
/// ignored or destroyed as appropriate. | ||
pub async fn upsert_or_delete(self, db: &impl ConnectionTrait) -> error::Result<Model> { | ||
let data = self.data.clone().take().unwrap_or_default(); | ||
|
||
if data.is_empty() { | ||
let model = ctx!(self.clone().try_into_model())?; | ||
ctx!(self.delete(db).await)?; | ||
return Ok(model); | ||
} | ||
|
||
ctx!(Entity::upsert(self).exec_with_returning(db).await) | ||
} | ||
} | ||
|
||
impl Entity { | ||
pub fn secure_find(app_id: ApplicationId) -> sea_orm::Select<Entity> { | ||
Self::find().filter(Column::Id.eq(app_id)) | ||
} | ||
|
||
pub fn upsert(am: ActiveModel) -> sea_orm::Insert<ActiveModel> { | ||
Self::insert(am).on_conflict( | ||
OnConflict::column(Column::Id) | ||
.update_columns([Column::Data, Column::UpdatedAt]) | ||
.to_owned(), | ||
) | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.