From ea74daca4809e4008dd8d01039db9fff3be659d9 Mon Sep 17 00:00:00 2001 From: Owen Jacobson Date: Wed, 16 Oct 2024 20:14:33 -0400 Subject: Organizational pass on endpoints and routes. --- src/channel/routes/test.rs | 83 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 src/channel/routes/test.rs (limited to 'src/channel/routes/test.rs') diff --git a/src/channel/routes/test.rs b/src/channel/routes/test.rs new file mode 100644 index 0000000..81f1465 --- /dev/null +++ b/src/channel/routes/test.rs @@ -0,0 +1,83 @@ +use axum::extract::{Json, State}; +use futures::stream::StreamExt as _; + +use super::post; +use crate::{ + channel::{self, app}, + event, + test::fixtures::{self, future::Immediately as _}, +}; + +#[tokio::test] +async fn new_channel() { + // Set up the environment + + let app = fixtures::scratch_app().await; + let creator = fixtures::login::create(&app, &fixtures::now()).await; + + // Call the endpoint + + let name = fixtures::channel::propose(); + let request = post::Request { name: name.clone() }; + let Json(response_channel) = + post::handler(State(app.clone()), creator, fixtures::now(), Json(request)) + .await + .expect("new channel in an empty app"); + + // Verify the structure of the response + + assert_eq!(name, response_channel.name); + + // Verify the semantics + + let snapshot = app.boot().snapshot().await.expect("boot always succeeds"); + assert!(snapshot + .channels + .iter() + .any(|channel| channel.name == response_channel.name && channel.id == response_channel.id)); + + let mut events = app + .events() + .subscribe(None) + .await + .expect("subscribing never fails") + .filter(fixtures::filter::created()); + + let event = events + .next() + .immediately() + .await + .expect("creation event published"); + + assert!(matches!( + event, + event::Event::Channel(channel::Event::Created(event)) + if event.channel == response_channel + )); +} + +#[tokio::test] +async fn duplicate_name() { + // Set up the environment + + let app = fixtures::scratch_app().await; + let creator = fixtures::login::create(&app, &fixtures::now()).await; + let channel = fixtures::channel::create(&app, &fixtures::now()).await; + + // Call the endpoint + + let request = post::Request { + name: channel.name.clone(), + }; + let post::Error(error) = + post::handler(State(app.clone()), creator, fixtures::now(), Json(request)) + .await + .expect_err("duplicate channel name should fail the request"); + + // Verify the structure of the response + + assert!(matches!( + error, + app::CreateError::DuplicateName(name) if channel.name == name + )); +} -- cgit v1.2.3 From 777e4281431a036eb663b5eec70f347b7425737d Mon Sep 17 00:00:00 2001 From: Owen Jacobson Date: Thu, 17 Oct 2024 01:45:58 -0400 Subject: Retain deleted messages and channels temporarily, to preserve events for replay. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Previously, when a channel (message) was deleted, `hi` would send events to all _connected_ clients to inform them of the deletion, then delete all memory of the channel (message). Any disconnected client, on reconnecting, would not receive the deletion event, and would de-synch with the service. The creation events were also immediately retconned out of the event stream, as well. With this change, `hi` keeps a record of deleted channels (messages). When replaying events, these records are used to replay the deletion event. After 7 days, the retained data is deleted, both to keep storage under control and to conform to users' expectations that deleted means gone. To match users' likely intuitions about what deletion does, deleting a channel (message) _does_ immediately delete some of its associated data. Channels' names are blanked, and messages' bodies are also blanked. When the event stream is replayed, the original channel.created (message.sent) event is "tombstoned", with an additional `deleted_at` field to inform clients. The included client does not use this field, at least yet. The migration is, once again, screamingingly complicated due to sqlite's limited ALTER TABLE … ALTER COLUMN support. This change also contains capabilities that would allow the API to return 410 Gone for deleted channels or messages, instead of 404. I did experiment with this, but it's tricky to do pervasively, especially since most app-level interfaces return an `Option` or `Option`. Redesigning these to return either `Ok(Channel)` (`Ok(Message)`) or `Err(Error::NotFound)` or `Err(Error::Deleted)` is more work than I wanted to take on for this change, and the utility of 410 Gone responses is not obvious to me. We have other, more pressing API design warts to address. --- ...ccdde2e9e4a49e52e74c3d0e28e82a0b01a3c9887f.json | 20 ++ ...86018161718e2a6788413bffffb252de3e1959f341.json | 38 ---- ...7e56e515d121964d3481e48aae3558b53a5123ce7d.json | 50 ----- ...4a4d68d68c8d9f8b9483af48de5d4e09857181d632.json | 20 ++ ...4abfbb9e06a5889460743202ca7956acabf006843e.json | 20 -- ...0c5b16e9ae908c4ea30e2d682d59d4720699b8de91.json | 62 +++++++ ...11f4726612141f7242decad1de5d9d5f166cb04990.json | 20 ++ ...8da75962b278d8191f77ffdea8dad8441f2bf72786.json | 12 ++ ...767190eeaaf479b458c18f79ff62c46b7aac158a77.json | 62 +++++++ ...1fc629c8edba240926d21fbe03d884e2a48b034336.json | 50 +++++ ...89d6e1a0eb2131b6581759a5028afb6a0910284803.json | 12 ++ ...e65e101d0941f2a266679209f793fd27466b9e3719.json | 50 +++++ ...ae7e18ecb51d54d1e304dcbd847de145c0c75423a7.json | 20 ++ ...fc8c187294a4661c18c2d820f4379dfd82138a8f77.json | 38 ---- ...48f3b75adcb3ddf8a88439aa8ddb0c66be2f0b384e.json | 50 ----- ...afabe3524caa9882d0cba0dc4359eb62cf8154c92d.json | 50 ----- ...314ba09dbe4e42fd49b2007e47bcfb07b5ba9001b0.json | 20 ++ ...df5de8c7d9ad11bb09a0d0d243181d97c79d771071.json | 20 -- ...b3abb8945a49ce18fb715d249bc9d93fc7d10e817d.json | 62 +++++++ ...6a6a72a129f9484b4d9b9e62e7c546d965cdde721a.json | 62 +++++++ ...8143f6b5d16dbeb19ad13ac36dcb40851f0af238e8.json | 38 ---- ...55c7cf413825151e1cda939378984611dc2d9a789a.json | 20 ++ ...b2060b9a6d6e0bbcb4cf8d01c48b297e6f0a950ebc.json | 50 +++++ ...075d18b090751a345ac2e90bb8c116e0fbb5dfbb99.json | 50 ----- ...e32c2cc4f93832948768dcbd1d12abcdbc5089ca8e.json | 50 +++++ ...5294ae908114b03719dc0cb237cec11f807bf757b1.json | 62 +++++++ ...87ec44bfea55ae259cc5fd412bdc30881b98ed12f8.json | 20 ++ ...ad2d2dec42949522f182a61bfb249f13ee78564179.json | 20 -- ...20ac429b55db93ceb5ce501917188e7b2f14975f34.json | 12 ++ ...96a0e7b12a920f9827aff2b05ee0364ff7688a38ae.json | 38 ---- docs/api/channels-messages.md | 12 +- docs/api/events.md | 34 ++-- migrations/20241017005219_retain_deleted.sql | 92 ++++++++++ src/channel/app.rs | 30 ++- src/channel/history.rs | 5 + src/channel/repo.rs | 196 ++++++++++++++------ src/channel/routes/channel/delete.rs | 2 +- src/channel/routes/channel/test.rs | 6 +- src/channel/routes/test.rs | 106 +++++++++-- src/channel/snapshot.rs | 3 + src/event/repo.rs | 5 +- src/event/routes/test.rs | 33 ++-- src/event/sequence.rs | 11 ++ src/expire.rs | 2 + src/login/repo.rs | 15 +- src/message/app.rs | 24 ++- src/message/history.rs | 5 + src/message/repo.rs | 204 ++++++++++++++------- src/message/routes/message.rs | 6 +- src/message/snapshot.rs | 4 +- src/test/fixtures/channel.rs | 23 ++- src/test/fixtures/event.rs | 7 +- src/test/fixtures/filter.rs | 11 -- src/test/fixtures/message.rs | 18 +- src/test/fixtures/mod.rs | 1 - src/token/repo/auth.rs | 5 +- 56 files changed, 1321 insertions(+), 637 deletions(-) create mode 100644 .sqlx/query-15ec7a8aa11908f8b2022accdde2e9e4a49e52e74c3d0e28e82a0b01a3c9887f.json delete mode 100644 .sqlx/query-1654b05159c27f74cb333586018161718e2a6788413bffffb252de3e1959f341.json delete mode 100644 .sqlx/query-191255b9e55c9b36d0fd047e56e515d121964d3481e48aae3558b53a5123ce7d.json create mode 100644 .sqlx/query-2252b49c77ff76a88ee7d24a4d68d68c8d9f8b9483af48de5d4e09857181d632.json delete mode 100644 .sqlx/query-33f9a143409e6f436ed6b64abfbb9e06a5889460743202ca7956acabf006843e.json create mode 100644 .sqlx/query-400de8e1dca27c48362b060c5b16e9ae908c4ea30e2d682d59d4720699b8de91.json create mode 100644 .sqlx/query-487092b18b01005fdb446c11f4726612141f7242decad1de5d9d5f166cb04990.json create mode 100644 .sqlx/query-58c17422db7edd8f0462378da75962b278d8191f77ffdea8dad8441f2bf72786.json create mode 100644 .sqlx/query-6c82af3b136a6719d52f49767190eeaaf479b458c18f79ff62c46b7aac158a77.json create mode 100644 .sqlx/query-771d1afa5961bae86112a51fc629c8edba240926d21fbe03d884e2a48b034336.json create mode 100644 .sqlx/query-814400dfe985ef284db22c89d6e1a0eb2131b6581759a5028afb6a0910284803.json create mode 100644 .sqlx/query-8d9b83fb53e4191ee58b68e65e101d0941f2a266679209f793fd27466b9e3719.json create mode 100644 .sqlx/query-8eebba45e8267b9eebc7b1ae7e18ecb51d54d1e304dcbd847de145c0c75423a7.json delete mode 100644 .sqlx/query-9386cdaa2cb41f5a7e19d2fc8c187294a4661c18c2d820f4379dfd82138a8f77.json delete mode 100644 .sqlx/query-9f83f0365b174ce61adb6d48f3b75adcb3ddf8a88439aa8ddb0c66be2f0b384e.json delete mode 100644 .sqlx/query-afe4404b44bd8ce6c9a51aafabe3524caa9882d0cba0dc4359eb62cf8154c92d.json create mode 100644 .sqlx/query-b1ba724a62135a6fbcb7ad314ba09dbe4e42fd49b2007e47bcfb07b5ba9001b0.json delete mode 100644 .sqlx/query-b7e05e2b2eb5484c954bcedf5de8c7d9ad11bb09a0d0d243181d97c79d771071.json create mode 100644 .sqlx/query-bddc3b0d75f6048c36630db3abb8945a49ce18fb715d249bc9d93fc7d10e817d.json create mode 100644 .sqlx/query-c90cbe4c836adf7f104b7b6a6a72a129f9484b4d9b9e62e7c546d965cdde721a.json delete mode 100644 .sqlx/query-cda3a4a974eb986ebe26838143f6b5d16dbeb19ad13ac36dcb40851f0af238e8.json create mode 100644 .sqlx/query-d6feb736b61c645649082e55c7cf413825151e1cda939378984611dc2d9a789a.json create mode 100644 .sqlx/query-e2686f26f8646b4cd31beeb2060b9a6d6e0bbcb4cf8d01c48b297e6f0a950ebc.json delete mode 100644 .sqlx/query-e476c3fb3f2227b7421ad2075d18b090751a345ac2e90bb8c116e0fbb5dfbb99.json create mode 100644 .sqlx/query-e621d064ba52cd13b196bce32c2cc4f93832948768dcbd1d12abcdbc5089ca8e.json create mode 100644 .sqlx/query-e702a0e7ff9a0a9808f8d45294ae908114b03719dc0cb237cec11f807bf757b1.json create mode 100644 .sqlx/query-ea5d8528095f8885b7e31687ec44bfea55ae259cc5fd412bdc30881b98ed12f8.json delete mode 100644 .sqlx/query-f3a338b9e4a65856decd79ad2d2dec42949522f182a61bfb249f13ee78564179.json create mode 100644 .sqlx/query-f511d351018c908bf303ae20ac429b55db93ceb5ce501917188e7b2f14975f34.json delete mode 100644 .sqlx/query-f6909336ab05b7ad423c7b96a0e7b12a920f9827aff2b05ee0364ff7688a38ae.json create mode 100644 migrations/20241017005219_retain_deleted.sql delete mode 100644 src/test/fixtures/filter.rs (limited to 'src/channel/routes/test.rs') diff --git a/.sqlx/query-15ec7a8aa11908f8b2022accdde2e9e4a49e52e74c3d0e28e82a0b01a3c9887f.json b/.sqlx/query-15ec7a8aa11908f8b2022accdde2e9e4a49e52e74c3d0e28e82a0b01a3c9887f.json new file mode 100644 index 0000000..167e768 --- /dev/null +++ b/.sqlx/query-15ec7a8aa11908f8b2022accdde2e9e4a49e52e74c3d0e28e82a0b01a3c9887f.json @@ -0,0 +1,20 @@ +{ + "db_name": "SQLite", + "query": "\n insert into message_deleted (id, deleted_at, deleted_sequence)\n values ($1, $2, $3)\n returning 1 as \"deleted: bool\"\n ", + "describe": { + "columns": [ + { + "name": "deleted: bool", + "ordinal": 0, + "type_info": "Null" + } + ], + "parameters": { + "Right": 3 + }, + "nullable": [ + null + ] + }, + "hash": "15ec7a8aa11908f8b2022accdde2e9e4a49e52e74c3d0e28e82a0b01a3c9887f" +} diff --git a/.sqlx/query-1654b05159c27f74cb333586018161718e2a6788413bffffb252de3e1959f341.json b/.sqlx/query-1654b05159c27f74cb333586018161718e2a6788413bffffb252de3e1959f341.json deleted file mode 100644 index cc716ed..0000000 --- a/.sqlx/query-1654b05159c27f74cb333586018161718e2a6788413bffffb252de3e1959f341.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "db_name": "SQLite", - "query": "\n delete from channel\n where id = $1\n returning\n id as \"id: Id\",\n name,\n created_at as \"created_at: DateTime\",\n created_sequence as \"created_sequence: Sequence\"\n ", - "describe": { - "columns": [ - { - "name": "id: Id", - "ordinal": 0, - "type_info": "Text" - }, - { - "name": "name", - "ordinal": 1, - "type_info": "Text" - }, - { - "name": "created_at: DateTime", - "ordinal": 2, - "type_info": "Text" - }, - { - "name": "created_sequence: Sequence", - "ordinal": 3, - "type_info": "Integer" - } - ], - "parameters": { - "Right": 1 - }, - "nullable": [ - false, - false, - false, - false - ] - }, - "hash": "1654b05159c27f74cb333586018161718e2a6788413bffffb252de3e1959f341" -} diff --git a/.sqlx/query-191255b9e55c9b36d0fd047e56e515d121964d3481e48aae3558b53a5123ce7d.json b/.sqlx/query-191255b9e55c9b36d0fd047e56e515d121964d3481e48aae3558b53a5123ce7d.json deleted file mode 100644 index fe443f9..0000000 --- a/.sqlx/query-191255b9e55c9b36d0fd047e56e515d121964d3481e48aae3558b53a5123ce7d.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "db_name": "SQLite", - "query": "\n select\n channel as \"channel: channel::Id\",\n sender as \"sender: login::Id\",\n id as \"id: Id\",\n body,\n sent_at as \"sent_at: DateTime\",\n sent_sequence as \"sent_sequence: Sequence\"\n from message\n where coalesce(sent_sequence <= $2, true)\n order by sent_sequence\n ", - "describe": { - "columns": [ - { - "name": "channel: channel::Id", - "ordinal": 0, - "type_info": "Text" - }, - { - "name": "sender: login::Id", - "ordinal": 1, - "type_info": "Text" - }, - { - "name": "id: Id", - "ordinal": 2, - "type_info": "Text" - }, - { - "name": "body", - "ordinal": 3, - "type_info": "Text" - }, - { - "name": "sent_at: DateTime", - "ordinal": 4, - "type_info": "Text" - }, - { - "name": "sent_sequence: Sequence", - "ordinal": 5, - "type_info": "Integer" - } - ], - "parameters": { - "Right": 1 - }, - "nullable": [ - false, - false, - false, - false, - false, - false - ] - }, - "hash": "191255b9e55c9b36d0fd047e56e515d121964d3481e48aae3558b53a5123ce7d" -} diff --git a/.sqlx/query-2252b49c77ff76a88ee7d24a4d68d68c8d9f8b9483af48de5d4e09857181d632.json b/.sqlx/query-2252b49c77ff76a88ee7d24a4d68d68c8d9f8b9483af48de5d4e09857181d632.json new file mode 100644 index 0000000..9975fd1 --- /dev/null +++ b/.sqlx/query-2252b49c77ff76a88ee7d24a4d68d68c8d9f8b9483af48de5d4e09857181d632.json @@ -0,0 +1,20 @@ +{ + "db_name": "SQLite", + "query": "\n update channel\n set name = \"\"\n where id = $1\n returning 1 as \"updated: bool\"\n ", + "describe": { + "columns": [ + { + "name": "updated: bool", + "ordinal": 0, + "type_info": "Null" + } + ], + "parameters": { + "Right": 1 + }, + "nullable": [ + null + ] + }, + "hash": "2252b49c77ff76a88ee7d24a4d68d68c8d9f8b9483af48de5d4e09857181d632" +} diff --git a/.sqlx/query-33f9a143409e6f436ed6b64abfbb9e06a5889460743202ca7956acabf006843e.json b/.sqlx/query-33f9a143409e6f436ed6b64abfbb9e06a5889460743202ca7956acabf006843e.json deleted file mode 100644 index 1480953..0000000 --- a/.sqlx/query-33f9a143409e6f436ed6b64abfbb9e06a5889460743202ca7956acabf006843e.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "db_name": "SQLite", - "query": "\n delete from message\n where\n id = $1\n returning 1 as \"deleted: i64\"\n ", - "describe": { - "columns": [ - { - "name": "deleted: i64", - "ordinal": 0, - "type_info": "Null" - } - ], - "parameters": { - "Right": 1 - }, - "nullable": [ - null - ] - }, - "hash": "33f9a143409e6f436ed6b64abfbb9e06a5889460743202ca7956acabf006843e" -} diff --git a/.sqlx/query-400de8e1dca27c48362b060c5b16e9ae908c4ea30e2d682d59d4720699b8de91.json b/.sqlx/query-400de8e1dca27c48362b060c5b16e9ae908c4ea30e2d682d59d4720699b8de91.json new file mode 100644 index 0000000..3d77307 --- /dev/null +++ b/.sqlx/query-400de8e1dca27c48362b060c5b16e9ae908c4ea30e2d682d59d4720699b8de91.json @@ -0,0 +1,62 @@ +{ + "db_name": "SQLite", + "query": "\n select\n id as \"id: Id\",\n message.channel as \"channel: channel::Id\",\n message.sender as \"sender: login::Id\",\n message.sent_at as \"sent_at: DateTime\",\n message.sent_sequence as \"sent_sequence: Sequence\",\n message.body,\n deleted.deleted_at as \"deleted_at: DateTime\",\n deleted.deleted_sequence as \"deleted_sequence: Sequence\"\n from message\n left join message_deleted as deleted\n using (id)\n where coalesce(message.sent_sequence > $1, true)\n ", + "describe": { + "columns": [ + { + "name": "id: Id", + "ordinal": 0, + "type_info": "Text" + }, + { + "name": "channel: channel::Id", + "ordinal": 1, + "type_info": "Text" + }, + { + "name": "sender: login::Id", + "ordinal": 2, + "type_info": "Text" + }, + { + "name": "sent_at: DateTime", + "ordinal": 3, + "type_info": "Text" + }, + { + "name": "sent_sequence: Sequence", + "ordinal": 4, + "type_info": "Integer" + }, + { + "name": "body", + "ordinal": 5, + "type_info": "Text" + }, + { + "name": "deleted_at: DateTime", + "ordinal": 6, + "type_info": "Text" + }, + { + "name": "deleted_sequence: Sequence", + "ordinal": 7, + "type_info": "Integer" + } + ], + "parameters": { + "Right": 1 + }, + "nullable": [ + false, + false, + false, + false, + false, + false, + true, + true + ] + }, + "hash": "400de8e1dca27c48362b060c5b16e9ae908c4ea30e2d682d59d4720699b8de91" +} diff --git a/.sqlx/query-487092b18b01005fdb446c11f4726612141f7242decad1de5d9d5f166cb04990.json b/.sqlx/query-487092b18b01005fdb446c11f4726612141f7242decad1de5d9d5f166cb04990.json new file mode 100644 index 0000000..c919eb2 --- /dev/null +++ b/.sqlx/query-487092b18b01005fdb446c11f4726612141f7242decad1de5d9d5f166cb04990.json @@ -0,0 +1,20 @@ +{ + "db_name": "SQLite", + "query": "\n with has_messages as (\n select channel\n from message\n group by channel\n )\n delete from channel_deleted\n where deleted_at < $1\n and id not in has_messages\n returning id as \"id: Id\"\n ", + "describe": { + "columns": [ + { + "name": "id: Id", + "ordinal": 0, + "type_info": "Text" + } + ], + "parameters": { + "Right": 1 + }, + "nullable": [ + false + ] + }, + "hash": "487092b18b01005fdb446c11f4726612141f7242decad1de5d9d5f166cb04990" +} diff --git a/.sqlx/query-58c17422db7edd8f0462378da75962b278d8191f77ffdea8dad8441f2bf72786.json b/.sqlx/query-58c17422db7edd8f0462378da75962b278d8191f77ffdea8dad8441f2bf72786.json new file mode 100644 index 0000000..ebfb579 --- /dev/null +++ b/.sqlx/query-58c17422db7edd8f0462378da75962b278d8191f77ffdea8dad8441f2bf72786.json @@ -0,0 +1,12 @@ +{ + "db_name": "SQLite", + "query": "\n insert into channel_name_reservation (id, name)\n values ($1, $2)\n ", + "describe": { + "columns": [], + "parameters": { + "Right": 2 + }, + "nullable": [] + }, + "hash": "58c17422db7edd8f0462378da75962b278d8191f77ffdea8dad8441f2bf72786" +} diff --git a/.sqlx/query-6c82af3b136a6719d52f49767190eeaaf479b458c18f79ff62c46b7aac158a77.json b/.sqlx/query-6c82af3b136a6719d52f49767190eeaaf479b458c18f79ff62c46b7aac158a77.json new file mode 100644 index 0000000..4251f92 --- /dev/null +++ b/.sqlx/query-6c82af3b136a6719d52f49767190eeaaf479b458c18f79ff62c46b7aac158a77.json @@ -0,0 +1,62 @@ +{ + "db_name": "SQLite", + "query": "\n select\n message.channel as \"channel: channel::Id\",\n message.sender as \"sender: login::Id\",\n id as \"id: Id\",\n message.body,\n message.sent_at as \"sent_at: DateTime\",\n message.sent_sequence as \"sent_sequence: Sequence\",\n deleted.deleted_at as \"deleted_at: DateTime\",\n deleted.deleted_sequence as \"deleted_sequence: Sequence\"\n from message\n left join message_deleted as deleted\n using (id)\n where id = $1\n ", + "describe": { + "columns": [ + { + "name": "channel: channel::Id", + "ordinal": 0, + "type_info": "Text" + }, + { + "name": "sender: login::Id", + "ordinal": 1, + "type_info": "Text" + }, + { + "name": "id: Id", + "ordinal": 2, + "type_info": "Text" + }, + { + "name": "body", + "ordinal": 3, + "type_info": "Text" + }, + { + "name": "sent_at: DateTime", + "ordinal": 4, + "type_info": "Text" + }, + { + "name": "sent_sequence: Sequence", + "ordinal": 5, + "type_info": "Integer" + }, + { + "name": "deleted_at: DateTime", + "ordinal": 6, + "type_info": "Text" + }, + { + "name": "deleted_sequence: Sequence", + "ordinal": 7, + "type_info": "Integer" + } + ], + "parameters": { + "Right": 1 + }, + "nullable": [ + false, + false, + false, + false, + false, + false, + true, + true + ] + }, + "hash": "6c82af3b136a6719d52f49767190eeaaf479b458c18f79ff62c46b7aac158a77" +} diff --git a/.sqlx/query-771d1afa5961bae86112a51fc629c8edba240926d21fbe03d884e2a48b034336.json b/.sqlx/query-771d1afa5961bae86112a51fc629c8edba240926d21fbe03d884e2a48b034336.json new file mode 100644 index 0000000..8a92f44 --- /dev/null +++ b/.sqlx/query-771d1afa5961bae86112a51fc629c8edba240926d21fbe03d884e2a48b034336.json @@ -0,0 +1,50 @@ +{ + "db_name": "SQLite", + "query": "\n select\n channel.id as \"id: Id\",\n channel.name,\n channel.created_at as \"created_at: DateTime\",\n channel.created_sequence as \"created_sequence: Sequence\",\n deleted.deleted_at as \"deleted_at: DateTime\",\n deleted.deleted_sequence as \"deleted_sequence: Sequence\"\n from channel\n left join channel_deleted as deleted\n using (id)\n left join message\n where channel.created_at < $1\n and message.id is null\n and deleted.id is null\n ", + "describe": { + "columns": [ + { + "name": "id: Id", + "ordinal": 0, + "type_info": "Text" + }, + { + "name": "name", + "ordinal": 1, + "type_info": "Text" + }, + { + "name": "created_at: DateTime", + "ordinal": 2, + "type_info": "Text" + }, + { + "name": "created_sequence: Sequence", + "ordinal": 3, + "type_info": "Integer" + }, + { + "name": "deleted_at: DateTime", + "ordinal": 4, + "type_info": "Text" + }, + { + "name": "deleted_sequence: Sequence", + "ordinal": 5, + "type_info": "Integer" + } + ], + "parameters": { + "Right": 1 + }, + "nullable": [ + false, + false, + false, + false, + true, + true + ] + }, + "hash": "771d1afa5961bae86112a51fc629c8edba240926d21fbe03d884e2a48b034336" +} diff --git a/.sqlx/query-814400dfe985ef284db22c89d6e1a0eb2131b6581759a5028afb6a0910284803.json b/.sqlx/query-814400dfe985ef284db22c89d6e1a0eb2131b6581759a5028afb6a0910284803.json new file mode 100644 index 0000000..4bcf6d0 --- /dev/null +++ b/.sqlx/query-814400dfe985ef284db22c89d6e1a0eb2131b6581759a5028afb6a0910284803.json @@ -0,0 +1,12 @@ +{ + "db_name": "SQLite", + "query": "\n delete from channel\n where id = $1\n ", + "describe": { + "columns": [], + "parameters": { + "Right": 1 + }, + "nullable": [] + }, + "hash": "814400dfe985ef284db22c89d6e1a0eb2131b6581759a5028afb6a0910284803" +} diff --git a/.sqlx/query-8d9b83fb53e4191ee58b68e65e101d0941f2a266679209f793fd27466b9e3719.json b/.sqlx/query-8d9b83fb53e4191ee58b68e65e101d0941f2a266679209f793fd27466b9e3719.json new file mode 100644 index 0000000..c09bdc6 --- /dev/null +++ b/.sqlx/query-8d9b83fb53e4191ee58b68e65e101d0941f2a266679209f793fd27466b9e3719.json @@ -0,0 +1,50 @@ +{ + "db_name": "SQLite", + "query": "\n select\n id as \"id: Id\",\n channel.name,\n channel.created_at as \"created_at: DateTime\",\n channel.created_sequence as \"created_sequence: Sequence\",\n deleted.deleted_at as \"deleted_at: DateTime\",\n deleted.deleted_sequence as \"deleted_sequence: Sequence\"\n from channel\n left join channel_deleted as deleted\n using (id)\n where coalesce(channel.created_sequence <= $1, true)\n order by channel.name\n ", + "describe": { + "columns": [ + { + "name": "id: Id", + "ordinal": 0, + "type_info": "Text" + }, + { + "name": "name", + "ordinal": 1, + "type_info": "Text" + }, + { + "name": "created_at: DateTime", + "ordinal": 2, + "type_info": "Text" + }, + { + "name": "created_sequence: Sequence", + "ordinal": 3, + "type_info": "Integer" + }, + { + "name": "deleted_at: DateTime", + "ordinal": 4, + "type_info": "Text" + }, + { + "name": "deleted_sequence: Sequence", + "ordinal": 5, + "type_info": "Integer" + } + ], + "parameters": { + "Right": 1 + }, + "nullable": [ + false, + false, + false, + false, + true, + true + ] + }, + "hash": "8d9b83fb53e4191ee58b68e65e101d0941f2a266679209f793fd27466b9e3719" +} diff --git a/.sqlx/query-8eebba45e8267b9eebc7b1ae7e18ecb51d54d1e304dcbd847de145c0c75423a7.json b/.sqlx/query-8eebba45e8267b9eebc7b1ae7e18ecb51d54d1e304dcbd847de145c0c75423a7.json new file mode 100644 index 0000000..0394bc5 --- /dev/null +++ b/.sqlx/query-8eebba45e8267b9eebc7b1ae7e18ecb51d54d1e304dcbd847de145c0c75423a7.json @@ -0,0 +1,20 @@ +{ + "db_name": "SQLite", + "query": "\n update message\n set body = \"\"\n where id = $1\n returning 1 as \"blanked: bool\"\n ", + "describe": { + "columns": [ + { + "name": "blanked: bool", + "ordinal": 0, + "type_info": "Null" + } + ], + "parameters": { + "Right": 1 + }, + "nullable": [ + null + ] + }, + "hash": "8eebba45e8267b9eebc7b1ae7e18ecb51d54d1e304dcbd847de145c0c75423a7" +} diff --git a/.sqlx/query-9386cdaa2cb41f5a7e19d2fc8c187294a4661c18c2d820f4379dfd82138a8f77.json b/.sqlx/query-9386cdaa2cb41f5a7e19d2fc8c187294a4661c18c2d820f4379dfd82138a8f77.json deleted file mode 100644 index e9c3967..0000000 --- a/.sqlx/query-9386cdaa2cb41f5a7e19d2fc8c187294a4661c18c2d820f4379dfd82138a8f77.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "db_name": "SQLite", - "query": "\n select\n id as \"id: Id\",\n name,\n created_at as \"created_at: DateTime\",\n created_sequence as \"created_sequence: Sequence\"\n from channel\n where coalesce(created_sequence > $1, true)\n ", - "describe": { - "columns": [ - { - "name": "id: Id", - "ordinal": 0, - "type_info": "Text" - }, - { - "name": "name", - "ordinal": 1, - "type_info": "Text" - }, - { - "name": "created_at: DateTime", - "ordinal": 2, - "type_info": "Text" - }, - { - "name": "created_sequence: Sequence", - "ordinal": 3, - "type_info": "Integer" - } - ], - "parameters": { - "Right": 1 - }, - "nullable": [ - false, - false, - false, - false - ] - }, - "hash": "9386cdaa2cb41f5a7e19d2fc8c187294a4661c18c2d820f4379dfd82138a8f77" -} diff --git a/.sqlx/query-9f83f0365b174ce61adb6d48f3b75adcb3ddf8a88439aa8ddb0c66be2f0b384e.json b/.sqlx/query-9f83f0365b174ce61adb6d48f3b75adcb3ddf8a88439aa8ddb0c66be2f0b384e.json deleted file mode 100644 index c8ce115..0000000 --- a/.sqlx/query-9f83f0365b174ce61adb6d48f3b75adcb3ddf8a88439aa8ddb0c66be2f0b384e.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "db_name": "SQLite", - "query": "\n select\n channel as \"channel: channel::Id\",\n sender as \"sender: login::Id\",\n id as \"id: Id\",\n body,\n sent_at as \"sent_at: DateTime\",\n sent_sequence as \"sent_sequence: Sequence\"\n from message\n where id = $1\n ", - "describe": { - "columns": [ - { - "name": "channel: channel::Id", - "ordinal": 0, - "type_info": "Text" - }, - { - "name": "sender: login::Id", - "ordinal": 1, - "type_info": "Text" - }, - { - "name": "id: Id", - "ordinal": 2, - "type_info": "Text" - }, - { - "name": "body", - "ordinal": 3, - "type_info": "Text" - }, - { - "name": "sent_at: DateTime", - "ordinal": 4, - "type_info": "Text" - }, - { - "name": "sent_sequence: Sequence", - "ordinal": 5, - "type_info": "Integer" - } - ], - "parameters": { - "Right": 1 - }, - "nullable": [ - false, - false, - false, - false, - false, - false - ] - }, - "hash": "9f83f0365b174ce61adb6d48f3b75adcb3ddf8a88439aa8ddb0c66be2f0b384e" -} diff --git a/.sqlx/query-afe4404b44bd8ce6c9a51aafabe3524caa9882d0cba0dc4359eb62cf8154c92d.json b/.sqlx/query-afe4404b44bd8ce6c9a51aafabe3524caa9882d0cba0dc4359eb62cf8154c92d.json deleted file mode 100644 index cc8a074..0000000 --- a/.sqlx/query-afe4404b44bd8ce6c9a51aafabe3524caa9882d0cba0dc4359eb62cf8154c92d.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "db_name": "SQLite", - "query": "\n select\n channel as \"channel: channel::Id\",\n sender as \"sender: login::Id\",\n id as \"id: Id\",\n body,\n sent_at as \"sent_at: DateTime\",\n sent_sequence as \"sent_sequence: Sequence\"\n from message\n where channel = $1\n and coalesce(sent_sequence <= $2, true)\n order by sent_sequence\n ", - "describe": { - "columns": [ - { - "name": "channel: channel::Id", - "ordinal": 0, - "type_info": "Text" - }, - { - "name": "sender: login::Id", - "ordinal": 1, - "type_info": "Text" - }, - { - "name": "id: Id", - "ordinal": 2, - "type_info": "Text" - }, - { - "name": "body", - "ordinal": 3, - "type_info": "Text" - }, - { - "name": "sent_at: DateTime", - "ordinal": 4, - "type_info": "Text" - }, - { - "name": "sent_sequence: Sequence", - "ordinal": 5, - "type_info": "Integer" - } - ], - "parameters": { - "Right": 2 - }, - "nullable": [ - false, - false, - false, - false, - false, - false - ] - }, - "hash": "afe4404b44bd8ce6c9a51aafabe3524caa9882d0cba0dc4359eb62cf8154c92d" -} diff --git a/.sqlx/query-b1ba724a62135a6fbcb7ad314ba09dbe4e42fd49b2007e47bcfb07b5ba9001b0.json b/.sqlx/query-b1ba724a62135a6fbcb7ad314ba09dbe4e42fd49b2007e47bcfb07b5ba9001b0.json new file mode 100644 index 0000000..5825ce8 --- /dev/null +++ b/.sqlx/query-b1ba724a62135a6fbcb7ad314ba09dbe4e42fd49b2007e47bcfb07b5ba9001b0.json @@ -0,0 +1,20 @@ +{ + "db_name": "SQLite", + "query": "\n insert into channel_deleted (id, deleted_at, deleted_sequence)\n values ($1, $2, $3)\n returning 1 as \"deleted: bool\"\n ", + "describe": { + "columns": [ + { + "name": "deleted: bool", + "ordinal": 0, + "type_info": "Null" + } + ], + "parameters": { + "Right": 3 + }, + "nullable": [ + null + ] + }, + "hash": "b1ba724a62135a6fbcb7ad314ba09dbe4e42fd49b2007e47bcfb07b5ba9001b0" +} diff --git a/.sqlx/query-b7e05e2b2eb5484c954bcedf5de8c7d9ad11bb09a0d0d243181d97c79d771071.json b/.sqlx/query-b7e05e2b2eb5484c954bcedf5de8c7d9ad11bb09a0d0d243181d97c79d771071.json deleted file mode 100644 index b82727f..0000000 --- a/.sqlx/query-b7e05e2b2eb5484c954bcedf5de8c7d9ad11bb09a0d0d243181d97c79d771071.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "db_name": "SQLite", - "query": "\n select\n channel.id as \"id: Id\"\n from channel\n left join message\n where created_at < $1\n and message.id is null\n ", - "describe": { - "columns": [ - { - "name": "id: Id", - "ordinal": 0, - "type_info": "Text" - } - ], - "parameters": { - "Right": 1 - }, - "nullable": [ - false - ] - }, - "hash": "b7e05e2b2eb5484c954bcedf5de8c7d9ad11bb09a0d0d243181d97c79d771071" -} diff --git a/.sqlx/query-bddc3b0d75f6048c36630db3abb8945a49ce18fb715d249bc9d93fc7d10e817d.json b/.sqlx/query-bddc3b0d75f6048c36630db3abb8945a49ce18fb715d249bc9d93fc7d10e817d.json new file mode 100644 index 0000000..f454fbb --- /dev/null +++ b/.sqlx/query-bddc3b0d75f6048c36630db3abb8945a49ce18fb715d249bc9d93fc7d10e817d.json @@ -0,0 +1,62 @@ +{ + "db_name": "SQLite", + "query": "\n select\n message.channel as \"channel: channel::Id\",\n message.sender as \"sender: login::Id\",\n id as \"id: Id\",\n message.body,\n message.sent_at as \"sent_at: DateTime\",\n message.sent_sequence as \"sent_sequence: Sequence\",\n deleted.deleted_at as \"deleted_at: DateTime\",\n deleted.deleted_sequence as \"deleted_sequence: Sequence\"\n from message\n left join message_deleted as deleted\n using (id)\n where coalesce(message.sent_sequence <= $2, true)\n order by message.sent_sequence\n ", + "describe": { + "columns": [ + { + "name": "channel: channel::Id", + "ordinal": 0, + "type_info": "Text" + }, + { + "name": "sender: login::Id", + "ordinal": 1, + "type_info": "Text" + }, + { + "name": "id: Id", + "ordinal": 2, + "type_info": "Text" + }, + { + "name": "body", + "ordinal": 3, + "type_info": "Text" + }, + { + "name": "sent_at: DateTime", + "ordinal": 4, + "type_info": "Text" + }, + { + "name": "sent_sequence: Sequence", + "ordinal": 5, + "type_info": "Integer" + }, + { + "name": "deleted_at: DateTime", + "ordinal": 6, + "type_info": "Text" + }, + { + "name": "deleted_sequence: Sequence", + "ordinal": 7, + "type_info": "Integer" + } + ], + "parameters": { + "Right": 1 + }, + "nullable": [ + false, + false, + false, + false, + false, + false, + true, + true + ] + }, + "hash": "bddc3b0d75f6048c36630db3abb8945a49ce18fb715d249bc9d93fc7d10e817d" +} diff --git a/.sqlx/query-c90cbe4c836adf7f104b7b6a6a72a129f9484b4d9b9e62e7c546d965cdde721a.json b/.sqlx/query-c90cbe4c836adf7f104b7b6a6a72a129f9484b4d9b9e62e7c546d965cdde721a.json new file mode 100644 index 0000000..eb41cba --- /dev/null +++ b/.sqlx/query-c90cbe4c836adf7f104b7b6a6a72a129f9484b4d9b9e62e7c546d965cdde721a.json @@ -0,0 +1,62 @@ +{ + "db_name": "SQLite", + "query": "\n select\n id as \"id: Id\",\n message.channel as \"channel: channel::Id\",\n message.sender as \"sender: login::Id\",\n message.sent_at as \"sent_at: DateTime\",\n message.sent_sequence as \"sent_sequence: Sequence\",\n message.body,\n deleted.deleted_at as \"deleted_at: DateTime\",\n deleted.deleted_sequence as \"deleted_sequence: Sequence\"\n from message\n left join message_deleted as deleted\n using (id)\n where message.sent_at < $1\n and deleted.id is null\n ", + "describe": { + "columns": [ + { + "name": "id: Id", + "ordinal": 0, + "type_info": "Text" + }, + { + "name": "channel: channel::Id", + "ordinal": 1, + "type_info": "Text" + }, + { + "name": "sender: login::Id", + "ordinal": 2, + "type_info": "Text" + }, + { + "name": "sent_at: DateTime", + "ordinal": 3, + "type_info": "Text" + }, + { + "name": "sent_sequence: Sequence", + "ordinal": 4, + "type_info": "Integer" + }, + { + "name": "body", + "ordinal": 5, + "type_info": "Text" + }, + { + "name": "deleted_at: DateTime", + "ordinal": 6, + "type_info": "Text" + }, + { + "name": "deleted_sequence: Sequence", + "ordinal": 7, + "type_info": "Integer" + } + ], + "parameters": { + "Right": 1 + }, + "nullable": [ + false, + false, + false, + false, + false, + false, + true, + true + ] + }, + "hash": "c90cbe4c836adf7f104b7b6a6a72a129f9484b4d9b9e62e7c546d965cdde721a" +} diff --git a/.sqlx/query-cda3a4a974eb986ebe26838143f6b5d16dbeb19ad13ac36dcb40851f0af238e8.json b/.sqlx/query-cda3a4a974eb986ebe26838143f6b5d16dbeb19ad13ac36dcb40851f0af238e8.json deleted file mode 100644 index bce6a88..0000000 --- a/.sqlx/query-cda3a4a974eb986ebe26838143f6b5d16dbeb19ad13ac36dcb40851f0af238e8.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "db_name": "SQLite", - "query": "\n select\n id as \"id: Id\",\n name,\n created_at as \"created_at: DateTime\",\n created_sequence as \"created_sequence: Sequence\"\n from channel\n where coalesce(created_sequence <= $1, true)\n order by channel.name\n ", - "describe": { - "columns": [ - { - "name": "id: Id", - "ordinal": 0, - "type_info": "Text" - }, - { - "name": "name", - "ordinal": 1, - "type_info": "Text" - }, - { - "name": "created_at: DateTime", - "ordinal": 2, - "type_info": "Text" - }, - { - "name": "created_sequence: Sequence", - "ordinal": 3, - "type_info": "Integer" - } - ], - "parameters": { - "Right": 1 - }, - "nullable": [ - false, - false, - false, - false - ] - }, - "hash": "cda3a4a974eb986ebe26838143f6b5d16dbeb19ad13ac36dcb40851f0af238e8" -} diff --git a/.sqlx/query-d6feb736b61c645649082e55c7cf413825151e1cda939378984611dc2d9a789a.json b/.sqlx/query-d6feb736b61c645649082e55c7cf413825151e1cda939378984611dc2d9a789a.json new file mode 100644 index 0000000..f96ceca --- /dev/null +++ b/.sqlx/query-d6feb736b61c645649082e55c7cf413825151e1cda939378984611dc2d9a789a.json @@ -0,0 +1,20 @@ +{ + "db_name": "SQLite", + "query": "\n delete from channel_name_reservation\n where id = $1\n returning 1 as \"deleted: bool\"\n ", + "describe": { + "columns": [ + { + "name": "deleted: bool", + "ordinal": 0, + "type_info": "Null" + } + ], + "parameters": { + "Right": 1 + }, + "nullable": [ + null + ] + }, + "hash": "d6feb736b61c645649082e55c7cf413825151e1cda939378984611dc2d9a789a" +} diff --git a/.sqlx/query-e2686f26f8646b4cd31beeb2060b9a6d6e0bbcb4cf8d01c48b297e6f0a950ebc.json b/.sqlx/query-e2686f26f8646b4cd31beeb2060b9a6d6e0bbcb4cf8d01c48b297e6f0a950ebc.json new file mode 100644 index 0000000..b8ab769 --- /dev/null +++ b/.sqlx/query-e2686f26f8646b4cd31beeb2060b9a6d6e0bbcb4cf8d01c48b297e6f0a950ebc.json @@ -0,0 +1,50 @@ +{ + "db_name": "SQLite", + "query": "\n select\n id as \"id: Id\",\n channel.name,\n channel.created_at as \"created_at: DateTime\",\n channel.created_sequence as \"created_sequence: Sequence\",\n deleted.deleted_at as \"deleted_at: DateTime\",\n deleted.deleted_sequence as \"deleted_sequence: Sequence\"\n from channel\n left join channel_deleted as deleted\n using (id)\n where coalesce(channel.created_sequence > $1, true)\n ", + "describe": { + "columns": [ + { + "name": "id: Id", + "ordinal": 0, + "type_info": "Text" + }, + { + "name": "name", + "ordinal": 1, + "type_info": "Text" + }, + { + "name": "created_at: DateTime", + "ordinal": 2, + "type_info": "Text" + }, + { + "name": "created_sequence: Sequence", + "ordinal": 3, + "type_info": "Integer" + }, + { + "name": "deleted_at: DateTime", + "ordinal": 4, + "type_info": "Text" + }, + { + "name": "deleted_sequence: Sequence", + "ordinal": 5, + "type_info": "Integer" + } + ], + "parameters": { + "Right": 1 + }, + "nullable": [ + false, + false, + false, + false, + true, + true + ] + }, + "hash": "e2686f26f8646b4cd31beeb2060b9a6d6e0bbcb4cf8d01c48b297e6f0a950ebc" +} diff --git a/.sqlx/query-e476c3fb3f2227b7421ad2075d18b090751a345ac2e90bb8c116e0fbb5dfbb99.json b/.sqlx/query-e476c3fb3f2227b7421ad2075d18b090751a345ac2e90bb8c116e0fbb5dfbb99.json deleted file mode 100644 index 821bd8f..0000000 --- a/.sqlx/query-e476c3fb3f2227b7421ad2075d18b090751a345ac2e90bb8c116e0fbb5dfbb99.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "db_name": "SQLite", - "query": "\n select\n channel as \"channel: channel::Id\",\n sender as \"sender: login::Id\",\n id as \"id: Id\",\n body,\n sent_at as \"sent_at: DateTime\",\n sent_sequence as \"sent_sequence: Sequence\"\n from message\n where coalesce(message.sent_sequence > $1, true)\n ", - "describe": { - "columns": [ - { - "name": "channel: channel::Id", - "ordinal": 0, - "type_info": "Text" - }, - { - "name": "sender: login::Id", - "ordinal": 1, - "type_info": "Text" - }, - { - "name": "id: Id", - "ordinal": 2, - "type_info": "Text" - }, - { - "name": "body", - "ordinal": 3, - "type_info": "Text" - }, - { - "name": "sent_at: DateTime", - "ordinal": 4, - "type_info": "Text" - }, - { - "name": "sent_sequence: Sequence", - "ordinal": 5, - "type_info": "Integer" - } - ], - "parameters": { - "Right": 1 - }, - "nullable": [ - false, - false, - false, - false, - false, - false - ] - }, - "hash": "e476c3fb3f2227b7421ad2075d18b090751a345ac2e90bb8c116e0fbb5dfbb99" -} diff --git a/.sqlx/query-e621d064ba52cd13b196bce32c2cc4f93832948768dcbd1d12abcdbc5089ca8e.json b/.sqlx/query-e621d064ba52cd13b196bce32c2cc4f93832948768dcbd1d12abcdbc5089ca8e.json new file mode 100644 index 0000000..d56cec0 --- /dev/null +++ b/.sqlx/query-e621d064ba52cd13b196bce32c2cc4f93832948768dcbd1d12abcdbc5089ca8e.json @@ -0,0 +1,50 @@ +{ + "db_name": "SQLite", + "query": "\n select\n id as \"id: Id\",\n channel.name,\n channel.created_at as \"created_at: DateTime\",\n channel.created_sequence as \"created_sequence: Sequence\",\n deleted.deleted_at as \"deleted_at: DateTime\",\n deleted.deleted_sequence as \"deleted_sequence: Sequence\"\n from channel\n left join channel_deleted as deleted\n using (id)\n where id = $1\n ", + "describe": { + "columns": [ + { + "name": "id: Id", + "ordinal": 0, + "type_info": "Text" + }, + { + "name": "name", + "ordinal": 1, + "type_info": "Text" + }, + { + "name": "created_at: DateTime", + "ordinal": 2, + "type_info": "Text" + }, + { + "name": "created_sequence: Sequence", + "ordinal": 3, + "type_info": "Integer" + }, + { + "name": "deleted_at: DateTime", + "ordinal": 4, + "type_info": "Text" + }, + { + "name": "deleted_sequence: Sequence", + "ordinal": 5, + "type_info": "Integer" + } + ], + "parameters": { + "Right": 1 + }, + "nullable": [ + false, + false, + false, + false, + true, + true + ] + }, + "hash": "e621d064ba52cd13b196bce32c2cc4f93832948768dcbd1d12abcdbc5089ca8e" +} diff --git a/.sqlx/query-e702a0e7ff9a0a9808f8d45294ae908114b03719dc0cb237cec11f807bf757b1.json b/.sqlx/query-e702a0e7ff9a0a9808f8d45294ae908114b03719dc0cb237cec11f807bf757b1.json new file mode 100644 index 0000000..0b48645 --- /dev/null +++ b/.sqlx/query-e702a0e7ff9a0a9808f8d45294ae908114b03719dc0cb237cec11f807bf757b1.json @@ -0,0 +1,62 @@ +{ + "db_name": "SQLite", + "query": "\n select\n message.channel as \"channel: channel::Id\",\n message.sender as \"sender: login::Id\",\n id as \"id: Id\",\n message.body,\n message.sent_at as \"sent_at: DateTime\",\n message.sent_sequence as \"sent_sequence: Sequence\",\n deleted.deleted_at as \"deleted_at: DateTime\",\n deleted.deleted_sequence as \"deleted_sequence: Sequence\"\n from message\n left join message_deleted as deleted\n using (id)\n where message.channel = $1\n and deleted.id is null\n ", + "describe": { + "columns": [ + { + "name": "channel: channel::Id", + "ordinal": 0, + "type_info": "Text" + }, + { + "name": "sender: login::Id", + "ordinal": 1, + "type_info": "Text" + }, + { + "name": "id: Id", + "ordinal": 2, + "type_info": "Text" + }, + { + "name": "body", + "ordinal": 3, + "type_info": "Text" + }, + { + "name": "sent_at: DateTime", + "ordinal": 4, + "type_info": "Text" + }, + { + "name": "sent_sequence: Sequence", + "ordinal": 5, + "type_info": "Integer" + }, + { + "name": "deleted_at: DateTime", + "ordinal": 6, + "type_info": "Text" + }, + { + "name": "deleted_sequence: Sequence", + "ordinal": 7, + "type_info": "Integer" + } + ], + "parameters": { + "Right": 1 + }, + "nullable": [ + false, + false, + false, + false, + false, + false, + true, + true + ] + }, + "hash": "e702a0e7ff9a0a9808f8d45294ae908114b03719dc0cb237cec11f807bf757b1" +} diff --git a/.sqlx/query-ea5d8528095f8885b7e31687ec44bfea55ae259cc5fd412bdc30881b98ed12f8.json b/.sqlx/query-ea5d8528095f8885b7e31687ec44bfea55ae259cc5fd412bdc30881b98ed12f8.json new file mode 100644 index 0000000..68b7155 --- /dev/null +++ b/.sqlx/query-ea5d8528095f8885b7e31687ec44bfea55ae259cc5fd412bdc30881b98ed12f8.json @@ -0,0 +1,20 @@ +{ + "db_name": "SQLite", + "query": "\n delete from message_deleted\n where deleted_at < $1\n returning id as \"id: Id\"\n ", + "describe": { + "columns": [ + { + "name": "id: Id", + "ordinal": 0, + "type_info": "Text" + } + ], + "parameters": { + "Right": 1 + }, + "nullable": [ + false + ] + }, + "hash": "ea5d8528095f8885b7e31687ec44bfea55ae259cc5fd412bdc30881b98ed12f8" +} diff --git a/.sqlx/query-f3a338b9e4a65856decd79ad2d2dec42949522f182a61bfb249f13ee78564179.json b/.sqlx/query-f3a338b9e4a65856decd79ad2d2dec42949522f182a61bfb249f13ee78564179.json deleted file mode 100644 index 92a64a3..0000000 --- a/.sqlx/query-f3a338b9e4a65856decd79ad2d2dec42949522f182a61bfb249f13ee78564179.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "db_name": "SQLite", - "query": "\n select\n id as \"message: Id\"\n from message\n where sent_at < $1\n ", - "describe": { - "columns": [ - { - "name": "message: Id", - "ordinal": 0, - "type_info": "Text" - } - ], - "parameters": { - "Right": 1 - }, - "nullable": [ - false - ] - }, - "hash": "f3a338b9e4a65856decd79ad2d2dec42949522f182a61bfb249f13ee78564179" -} diff --git a/.sqlx/query-f511d351018c908bf303ae20ac429b55db93ceb5ce501917188e7b2f14975f34.json b/.sqlx/query-f511d351018c908bf303ae20ac429b55db93ceb5ce501917188e7b2f14975f34.json new file mode 100644 index 0000000..69fdf03 --- /dev/null +++ b/.sqlx/query-f511d351018c908bf303ae20ac429b55db93ceb5ce501917188e7b2f14975f34.json @@ -0,0 +1,12 @@ +{ + "db_name": "SQLite", + "query": "\n delete from message\n where id = $1\n ", + "describe": { + "columns": [], + "parameters": { + "Right": 1 + }, + "nullable": [] + }, + "hash": "f511d351018c908bf303ae20ac429b55db93ceb5ce501917188e7b2f14975f34" +} diff --git a/.sqlx/query-f6909336ab05b7ad423c7b96a0e7b12a920f9827aff2b05ee0364ff7688a38ae.json b/.sqlx/query-f6909336ab05b7ad423c7b96a0e7b12a920f9827aff2b05ee0364ff7688a38ae.json deleted file mode 100644 index ded48e1..0000000 --- a/.sqlx/query-f6909336ab05b7ad423c7b96a0e7b12a920f9827aff2b05ee0364ff7688a38ae.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "db_name": "SQLite", - "query": "\n select\n id as \"id: Id\",\n name,\n created_at as \"created_at: DateTime\",\n created_sequence as \"created_sequence: Sequence\"\n from channel\n where id = $1\n ", - "describe": { - "columns": [ - { - "name": "id: Id", - "ordinal": 0, - "type_info": "Text" - }, - { - "name": "name", - "ordinal": 1, - "type_info": "Text" - }, - { - "name": "created_at: DateTime", - "ordinal": 2, - "type_info": "Text" - }, - { - "name": "created_sequence: Sequence", - "ordinal": 3, - "type_info": "Integer" - } - ], - "parameters": { - "Right": 1 - }, - "nullable": [ - false, - false, - false, - false - ] - }, - "hash": "f6909336ab05b7ad423c7b96a0e7b12a920f9827aff2b05ee0364ff7688a38ae" -} diff --git a/docs/api/channels-messages.md b/docs/api/channels-messages.md index d032ac1..99a525e 100644 --- a/docs/api/channels-messages.md +++ b/docs/api/channels-messages.md @@ -8,7 +8,7 @@ stateDiagram-v2 [*] --> Active : POST /api/channels Active --> Deleted : DELETE /api/channels/C1234 Active --> Deleted : Expiry - Deleted --> [*] + Deleted --> [*] : Purge ``` ```mermaid @@ -19,14 +19,19 @@ stateDiagram-v2 [*] --> Sent : POST /api/channels/C1234 Sent --> Deleted : DELETE /api/messages/Mabcd Sent --> Deleted : Expiry - Deleted --> [*] + Deleted --> [*] : Purge ``` Messages allow logins to communicate with one another. Channels are the conversations to which those messages are sent. Every channel has a unique name, chosen when the channel is created. -Both channels and messages expire after a time, to prevent the service from consuming unlimited amounts of storage. Messages expire 90 days after being sent. Channels expire 90 days after the last message sent to them, or after creation if no messages are sent in that time. + +## Expiry and purging + +Both channels and messages expire after a time. Messages expire 90 days after being sent. Channels expire 90 days after the last message sent to them, or after creation if no messages are sent in that time. + +Deleted channels and messages, including those that have expired, are temporarily retained by the service, to allow clients that are not connected to receive the corresponding deletion [events](./events.md). To limit storage growth, deleted channels and messages are purged from the service seven days after they were deleted. ## `POST /api/channels` @@ -103,6 +108,7 @@ This endpoint will respond with a status of `202 Accepted` when successful. The This endpoint will respond with a status of `404 Not Found` if the channel ID is not valid. + ## `DELETE /api/channels/:id` Deletes a channel (and all messages in it). diff --git a/docs/api/events.md b/docs/api/events.md index 9fe9ca9..da2f4b6 100644 --- a/docs/api/events.md +++ b/docs/api/events.md @@ -133,11 +133,16 @@ Sent whenever a new channel is created. These events have the `event` field set to `"created"`. They include the following additional fields: -| Field | Type | Description | -|:-------|:----------|:--| -| `at` | timestamp | The moment the channel was created. | -| `id` | string | A unique identifier for the newly-created channel. This can be used to associate the channel with other events, or to make API calls targeting the channel. | -| `name` | string | The channel's name. | +| Field | Type | Description | +|:-------------|:--------------------|:--| +| `at` | timestamp | The moment the channel was created. | +| `id` | string | A unique identifier for the newly-created channel. This can be used to associate the channel with other events, or to make API calls targeting the channel. | +| `name` | string | The channel's name. | +| `deleted_at` | timestamp, optional | If set, the moment the channel was deleted. | + +When a channel is deleted or expires, the `"created"` event is replaced with a tombstone `"created"` event, so that the original channel cannot be trivially recovered from the event stream. Tombstone events have a `deleted_at` field, and a `name` of `""`. + +Once a deleted channel is [purged](./channels-messages.md#expiry-and-purging), these tombstone events are removed from the event stream. ### Channel deleted @@ -184,13 +189,18 @@ Sent whenever a message is sent by a client. These events have the `event` field set to `"sent"`. They include the following additional fields: -| Field | Type | Description | -|:----------|:----------|:--| -| `at` | timestamp | The moment the message was sent. | -| `channel` | string | The ID of the channel the message was sent to. | -| `sender` | string | The ID of the login that sent the message. | -| `id` | string | A unique identifier for the message. This can be used to associate the message with other events, or to make API calls targeting the message. | -| `body` | string | The text of the message. | +| Field | Type | Description | +|:-------------|:--------------------|:--| +| `at` | timestamp | The moment the message was sent. | +| `channel` | string | The ID of the channel the message was sent to. | +| `sender` | string | The ID of the login that sent the message. | +| `id` | string | A unique identifier for the message. This can be used to associate the message with other events, or to make API calls targeting the message. | +| `body` | string | The text of the message. | +| `deleted_at` | timestamp, optional | If set, the moment the message was deleted. | + +When a message is deleted or expires, the `"sent"` event is replaced with a tombstone `"sent"` event, so that the original message cannot be trivially recovered from the event stream. Tombstone events have a `deleted_at` field, and a `body` of `""`. + +Once a deleted message is [purged](./channels-messages.md#expiry-and-purging), these tombstone events are removed from the event stream. ### Message deleted diff --git a/migrations/20241017005219_retain_deleted.sql b/migrations/20241017005219_retain_deleted.sql new file mode 100644 index 0000000..6205482 --- /dev/null +++ b/migrations/20241017005219_retain_deleted.sql @@ -0,0 +1,92 @@ +alter table channel +rename to old_channel; + +alter table message +rename to old_message; + +create table channel ( + id text + not null + primary key, + name text + not null, + created_sequence bigint + unique + not null, + created_at text + not null, + unique (id, name) +); + +insert into channel (id, name, created_sequence, created_at) +select id, name, created_sequence, created_at from old_channel; + +create table channel_name_reservation ( + id text + not null + unique, + name text + not null + unique, + primary key (id, name), + foreign key (id, name) + references channel (id, name) +); + +insert into channel_name_reservation (id, name) +select id, name from old_channel; + +create table channel_deleted ( + id text + not null + primary key + references channel (id), + deleted_sequence bigint + unique + not null, + deleted_at text + not null +); + +create table message ( + id text + not null + primary key, + channel text + not null + references channel (id), + sender text + not null + references login (id), + sent_sequence bigint + unique + not null, + sent_at text + not null, + body text + not null +); + +insert into message (id, channel, sender, sent_sequence, sent_at, body) +select id, channel, sender, sent_sequence, sent_at, body from old_message; + +create table message_deleted ( + id text + not null + primary key + references message (id), + deleted_sequence bigint + unique + not null, + deleted_at text + not null +); + +drop table old_message; +drop table old_channel; + +create index message_sent_at +on message (sent_at); + +create index channel_created_at +on channel (created_at); diff --git a/src/channel/app.rs b/src/channel/app.rs index 46eaba8..0409076 100644 --- a/src/channel/app.rs +++ b/src/channel/app.rs @@ -23,9 +23,9 @@ impl<'a> Channels<'a> { pub async fn create(&self, name: &str, created_at: &DateTime) -> Result { let mut tx = self.db.begin().await?; let created = tx.sequence().next(created_at).await?; - let channel = tx - .channels() - .create(name, &created) + let channel = tx.channels().create(name, &created).await?; + tx.channels() + .reserve_name(&channel, name) .await .duplicate(|| CreateError::DuplicateName(name.into()))?; tx.commit().await?; @@ -43,7 +43,7 @@ impl<'a> Channels<'a> { let channel = tx.channels().by_id(channel).await.optional()?; tx.commit().await?; - Ok(channel.iter().flat_map(History::events).collect()) + Ok(channel.as_ref().and_then(History::as_snapshot)) } pub async fn delete(&self, channel: &Id, deleted_at: &DateTime) -> Result<(), Error> { @@ -54,13 +54,16 @@ impl<'a> Channels<'a> { .by_id(channel) .await .not_found(|| Error::NotFound(channel.clone()))?; + channel + .as_snapshot() + .ok_or_else(|| Error::Deleted(channel.id().clone()))?; let mut events = Vec::new(); - let messages = tx.messages().in_channel(&channel, None).await?; + let messages = tx.messages().live(&channel).await?; for message in messages { let deleted = tx.sequence().next(deleted_at).await?; - let message = tx.messages().delete(message.id(), &deleted).await?; + let message = tx.messages().delete(&message, &deleted).await?; events.extend( message .events() @@ -70,7 +73,7 @@ impl<'a> Channels<'a> { } let deleted = tx.sequence().next(deleted_at).await?; - let channel = tx.channels().delete(channel.id(), &deleted).await?; + let channel = tx.channels().delete(&channel, &deleted).await?; events.extend( channel .events() @@ -115,6 +118,17 @@ impl<'a> Channels<'a> { Ok(()) } + + pub async fn purge(&self, relative_to: &DateTime) -> Result<(), sqlx::Error> { + // Somewhat arbitrarily, purge after 7 days. + let purge_at = relative_to.to_owned() - TimeDelta::days(7); + + let mut tx = self.db.begin().await?; + tx.channels().purge(&purge_at).await?; + tx.commit().await?; + + Ok(()) + } } #[derive(Debug, thiserror::Error)] @@ -129,6 +143,8 @@ pub enum CreateError { pub enum Error { #[error("channel {0} not found")] NotFound(Id), + #[error("channel {0} deleted")] + Deleted(Id), #[error(transparent)] Database(#[from] sqlx::Error), } diff --git a/src/channel/history.rs b/src/channel/history.rs index 78b3437..4b9fcc7 100644 --- a/src/channel/history.rs +++ b/src/channel/history.rs @@ -31,6 +31,11 @@ impl History { .filter(Sequence::up_to(resume_point.into())) .collect() } + + // Snapshot of this channel as of all events recorded in this history. + pub fn as_snapshot(&self) -> Option { + self.events().collect() + } } // Event factories diff --git a/src/channel/repo.rs b/src/channel/repo.rs index 2f57581..4b10c54 100644 --- a/src/channel/repo.rs +++ b/src/channel/repo.rs @@ -41,11 +41,9 @@ impl<'c> Channels<'c> { channel: Channel { id: row.id, name: row.name, + deleted_at: None, }, - created: Instant { - at: row.created_at, - sequence: row.created_sequence, - }, + created: Instant::new(row.created_at, row.created_sequence), deleted: None, }) .fetch_one(&mut *self.0) @@ -54,15 +52,35 @@ impl<'c> Channels<'c> { Ok(channel) } + pub async fn reserve_name(&mut self, channel: &History, name: &str) -> Result<(), sqlx::Error> { + let channel = channel.id(); + sqlx::query!( + r#" + insert into channel_name_reservation (id, name) + values ($1, $2) + "#, + channel, + name, + ) + .execute(&mut *self.0) + .await?; + + Ok(()) + } + pub async fn by_id(&mut self, channel: &Id) -> Result { let channel = sqlx::query!( r#" select id as "id: Id", - name, - created_at as "created_at: DateTime", - created_sequence as "created_sequence: Sequence" + channel.name, + channel.created_at as "created_at: DateTime", + channel.created_sequence as "created_sequence: Sequence", + deleted.deleted_at as "deleted_at: DateTime", + deleted.deleted_sequence as "deleted_sequence: Sequence" from channel + left join channel_deleted as deleted + using (id) where id = $1 "#, channel, @@ -71,12 +89,10 @@ impl<'c> Channels<'c> { channel: Channel { id: row.id, name: row.name, + deleted_at: row.deleted_at, }, - created: Instant { - at: row.created_at, - sequence: row.created_sequence, - }, - deleted: None, + created: Instant::new(row.created_at, row.created_sequence), + deleted: Instant::optional(row.deleted_at, row.deleted_sequence), }) .fetch_one(&mut *self.0) .await?; @@ -89,11 +105,15 @@ impl<'c> Channels<'c> { r#" select id as "id: Id", - name, - created_at as "created_at: DateTime", - created_sequence as "created_sequence: Sequence" + channel.name, + channel.created_at as "created_at: DateTime", + channel.created_sequence as "created_sequence: Sequence", + deleted.deleted_at as "deleted_at: DateTime", + deleted.deleted_sequence as "deleted_sequence: Sequence" from channel - where coalesce(created_sequence <= $1, true) + left join channel_deleted as deleted + using (id) + where coalesce(channel.created_sequence <= $1, true) order by channel.name "#, resume_at, @@ -102,12 +122,10 @@ impl<'c> Channels<'c> { channel: Channel { id: row.id, name: row.name, + deleted_at: row.deleted_at, }, - created: Instant { - at: row.created_at, - sequence: row.created_sequence, - }, - deleted: None, + created: Instant::new(row.created_at, row.created_sequence), + deleted: Instant::optional(row.deleted_at, row.deleted_sequence), }) .fetch_all(&mut *self.0) .await?; @@ -123,11 +141,15 @@ impl<'c> Channels<'c> { r#" select id as "id: Id", - name, - created_at as "created_at: DateTime", - created_sequence as "created_sequence: Sequence" + channel.name, + channel.created_at as "created_at: DateTime", + channel.created_sequence as "created_sequence: Sequence", + deleted.deleted_at as "deleted_at: DateTime", + deleted.deleted_sequence as "deleted_sequence: Sequence" from channel - where coalesce(created_sequence > $1, true) + left join channel_deleted as deleted + using (id) + where coalesce(channel.created_sequence > $1, true) "#, resume_at, ) @@ -135,12 +157,10 @@ impl<'c> Channels<'c> { channel: Channel { id: row.id, name: row.name, + deleted_at: row.deleted_at, }, - created: Instant { - at: row.created_at, - sequence: row.created_sequence, - }, - deleted: None, + created: Instant::new(row.created_at, row.created_sequence), + deleted: Instant::optional(row.deleted_at, row.deleted_sequence), }) .fetch_all(&mut *self.0) .await?; @@ -150,50 +170,118 @@ impl<'c> Channels<'c> { pub async fn delete( &mut self, - channel: &Id, + channel: &History, deleted: &Instant, ) -> Result { - let channel = sqlx::query!( + let id = channel.id(); + sqlx::query_scalar!( r#" - delete from channel + delete from channel_name_reservation where id = $1 - returning - id as "id: Id", - name, - created_at as "created_at: DateTime", - created_sequence as "created_sequence: Sequence" + returning 1 as "deleted: bool" "#, - channel, + id, + ) + .fetch_one(&mut *self.0) + .await?; + + sqlx::query_scalar!( + r#" + insert into channel_deleted (id, deleted_at, deleted_sequence) + values ($1, $2, $3) + returning 1 as "deleted: bool" + "#, + id, + deleted.at, + deleted.sequence, + ) + .fetch_one(&mut *self.0) + .await?; + + // Small social responsibility hack here: when a channel is deleted, its name is + // retconned to have been the empty string. Someone reading the event stream + // afterwards, or looking at channels via the API, cannot retrieve the + // "deleted" channel's information by ignoring the deletion event. + sqlx::query_scalar!( + r#" + update channel + set name = "" + where id = $1 + returning 1 as "updated: bool" + "#, + id, ) - .map(|row| History { - channel: Channel { - id: row.id, - name: row.name, - }, - created: Instant { - at: row.created_at, - sequence: row.created_sequence, - }, - deleted: Some(*deleted), - }) .fetch_one(&mut *self.0) .await?; + let channel = self.by_id(id).await?; + Ok(channel) } - pub async fn expired(&mut self, expired_at: &DateTime) -> Result, sqlx::Error> { + pub async fn purge(&mut self, purge_at: &DateTime) -> Result<(), sqlx::Error> { let channels = sqlx::query_scalar!( + r#" + with has_messages as ( + select channel + from message + group by channel + ) + delete from channel_deleted + where deleted_at < $1 + and id not in has_messages + returning id as "id: Id" + "#, + purge_at, + ) + .fetch_all(&mut *self.0) + .await?; + + for channel in channels { + // Wanted: a way to batch these up into one query. + sqlx::query!( + r#" + delete from channel + where id = $1 + "#, + channel, + ) + .execute(&mut *self.0) + .await?; + } + + Ok(()) + } + + pub async fn expired(&mut self, expired_at: &DateTime) -> Result, sqlx::Error> { + let channels = sqlx::query!( r#" select - channel.id as "id: Id" + channel.id as "id: Id", + channel.name, + channel.created_at as "created_at: DateTime", + channel.created_sequence as "created_sequence: Sequence", + deleted.deleted_at as "deleted_at: DateTime", + deleted.deleted_sequence as "deleted_sequence: Sequence" from channel - left join message - where created_at < $1 + left join channel_deleted as deleted + using (id) + left join message + where channel.created_at < $1 and message.id is null + and deleted.id is null "#, expired_at, ) + .map(|row| History { + channel: Channel { + id: row.id, + name: row.name, + deleted_at: row.deleted_at, + }, + created: Instant::new(row.created_at, row.created_sequence), + deleted: Instant::optional(row.deleted_at, row.deleted_sequence), + }) .fetch_all(&mut *self.0) .await?; diff --git a/src/channel/routes/channel/delete.rs b/src/channel/routes/channel/delete.rs index efac0c0..5f40ddf 100644 --- a/src/channel/routes/channel/delete.rs +++ b/src/channel/routes/channel/delete.rs @@ -32,7 +32,7 @@ impl IntoResponse for Error { let Self(error) = self; #[allow(clippy::match_wildcard_for_single_variants)] match error { - app::Error::NotFound(_) => NotFound(error).into_response(), + app::Error::NotFound(_) | app::Error::Deleted(_) => NotFound(error).into_response(), other => Internal::from(other).into_response(), } } diff --git a/src/channel/routes/channel/test.rs b/src/channel/routes/channel/test.rs index bc02b20..c6541cd 100644 --- a/src/channel/routes/channel/test.rs +++ b/src/channel/routes/channel/test.rs @@ -4,7 +4,7 @@ use futures::stream::StreamExt; use super::post; use crate::{ channel, - event::{self, Sequenced}, + event::Sequenced, message::{self, app::SendError}, test::fixtures::{self, future::Immediately as _}, }; @@ -45,7 +45,7 @@ async fn messages_in_order() { .subscribe(None) .await .expect("subscribing to a valid channel") - .filter(fixtures::filter::messages()) + .filter_map(fixtures::message::events) .take(requests.len()); let events = events.collect::>().immediately().await; @@ -54,7 +54,7 @@ async fn messages_in_order() { assert_eq!(*sent_at, event.at()); assert!(matches!( event, - event::Event::Message(message::Event::Sent(event)) + message::Event::Sent(event) if event.message.sender == sender.id && event.message.body == message )); diff --git a/src/channel/routes/test.rs b/src/channel/routes/test.rs index 81f1465..ffd8484 100644 --- a/src/channel/routes/test.rs +++ b/src/channel/routes/test.rs @@ -1,10 +1,11 @@ +use std::future; + use axum::extract::{Json, State}; use futures::stream::StreamExt as _; use super::post; use crate::{ - channel::{self, app}, - event, + channel::app, test::fixtures::{self, future::Immediately as _}, }; @@ -19,29 +20,35 @@ async fn new_channel() { let name = fixtures::channel::propose(); let request = post::Request { name: name.clone() }; - let Json(response_channel) = - post::handler(State(app.clone()), creator, fixtures::now(), Json(request)) - .await - .expect("new channel in an empty app"); + let Json(response) = post::handler(State(app.clone()), creator, fixtures::now(), Json(request)) + .await + .expect("creating a channel in an empty app succeeds"); // Verify the structure of the response - assert_eq!(name, response_channel.name); + assert_eq!(name, response.name); // Verify the semantics let snapshot = app.boot().snapshot().await.expect("boot always succeeds"); - assert!(snapshot - .channels - .iter() - .any(|channel| channel.name == response_channel.name && channel.id == response_channel.id)); + assert!(snapshot.channels.iter().any(|channel| channel == &response)); + + let channel = app + .channels() + .get(&response.id) + .await + .expect("searching for channels by ID never fails") + .expect("the newly-created channel exists"); + assert_eq!(response, channel); let mut events = app .events() .subscribe(None) .await .expect("subscribing never fails") - .filter(fixtures::filter::created()); + .filter_map(fixtures::channel::events) + .filter_map(fixtures::channel::created) + .filter(|event| future::ready(event.channel == response)); let event = events .next() @@ -49,11 +56,7 @@ async fn new_channel() { .await .expect("creation event published"); - assert!(matches!( - event, - event::Event::Channel(channel::Event::Created(event)) - if event.channel == response_channel - )); + assert_eq!(event.channel, response); } #[tokio::test] @@ -81,3 +84,72 @@ async fn duplicate_name() { app::CreateError::DuplicateName(name) if channel.name == name )); } + +#[tokio::test] +async fn name_reusable_after_delete() { + // Set up the environment + + let app = fixtures::scratch_app().await; + let creator = fixtures::login::create(&app, &fixtures::now()).await; + let name = fixtures::channel::propose(); + + // Call the endpoint (first time) + + let request = post::Request { name: name.clone() }; + let Json(response) = post::handler( + State(app.clone()), + creator.clone(), + fixtures::now(), + Json(request), + ) + .await + .expect("new channel in an empty app"); + + // Delete the channel + + app.channels() + .delete(&response.id, &fixtures::now()) + .await + .expect("deleting a newly-created channel succeeds"); + + // Call the endpoint (second time) + + let request = post::Request { name: name.clone() }; + let Json(response) = post::handler(State(app.clone()), creator, fixtures::now(), Json(request)) + .await + .expect("new channel in an empty app"); + + // Verify the structure of the response + + assert_eq!(name, response.name); + + // Verify the semantics + + let snapshot = app.boot().snapshot().await.expect("boot always succeeds"); + assert!(snapshot.channels.iter().any(|channel| channel == &response)); + + let channel = app + .channels() + .get(&response.id) + .await + .expect("searching for channels by ID never fails") + .expect("the newly-created channel exists"); + assert_eq!(response, channel); + + let mut events = app + .events() + .subscribe(None) + .await + .expect("subscribing never fails") + .filter_map(fixtures::channel::events) + .filter_map(fixtures::channel::created) + .filter(|event| future::ready(event.channel == response)); + + let event = events + .next() + .immediately() + .await + .expect("creation event published"); + + assert_eq!(event.channel, response); +} diff --git a/src/channel/snapshot.rs b/src/channel/snapshot.rs index d4d1d27..2b7d89a 100644 --- a/src/channel/snapshot.rs +++ b/src/channel/snapshot.rs @@ -2,11 +2,14 @@ use super::{ event::{Created, Event}, Id, }; +use crate::clock::DateTime; #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize)] pub struct Channel { pub id: Id, pub name: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub deleted_at: Option, } impl Channel { diff --git a/src/event/repo.rs b/src/event/repo.rs index 40d6a53..56beeea 100644 --- a/src/event/repo.rs +++ b/src/event/repo.rs @@ -29,10 +29,7 @@ impl<'c> Sequences<'c> { .fetch_one(&mut *self.0) .await?; - Ok(Instant { - at: *at, - sequence: next, - }) + Ok(Instant::new(*at, next)) } pub async fn current(&mut self) -> Result { diff --git a/src/event/routes/test.rs b/src/event/routes/test.rs index 249f5c2..e6a8b9d 100644 --- a/src/event/routes/test.rs +++ b/src/event/routes/test.rs @@ -31,7 +31,7 @@ async fn includes_historical_message() { // Verify the structure of the response. let event = events - .filter(fixtures::filter::messages()) + .filter_map(fixtures::message::events) .next() .immediately() .await @@ -62,7 +62,7 @@ async fn includes_live_message() { let message = fixtures::message::send(&app, &channel, &sender, &fixtures::now()).await; let event = events - .filter(fixtures::filter::messages()) + .filter_map(fixtures::message::events) .next() .immediately() .await @@ -104,7 +104,7 @@ async fn includes_multiple_channels() { // Verify the structure of the response. let events = events - .filter(fixtures::filter::messages()) + .filter_map(fixtures::message::events) .take(messages.len()) .collect::>() .immediately() @@ -141,13 +141,15 @@ async fn sequential_messages() { // Verify the structure of the response. - let mut events = events.filter(|event| { - future::ready( - messages - .iter() - .any(|message| fixtures::event::message_sent(event, message)), - ) - }); + let mut events = events + .filter_map(fixtures::message::events) + .filter(|event| { + future::ready( + messages + .iter() + .any(|message| fixtures::event::message_sent(event, message)), + ) + }); // Verify delivery in order for message in &messages { @@ -193,7 +195,7 @@ async fn resumes_from() { .expect("subscribe never fails"); let event = events - .filter(fixtures::filter::messages()) + .filter_map(fixtures::message::events) .next() .immediately() .await @@ -217,6 +219,7 @@ async fn resumes_from() { // Verify the structure of the response. let events = resumed + .filter_map(fixtures::message::events) .take(later_messages.len()) .collect::>() .immediately() @@ -275,7 +278,7 @@ async fn serial_resume() { .expect("subscribe never fails"); let events = events - .filter(fixtures::filter::messages()) + .filter_map(fixtures::message::events) .take(initial_messages.len()) .collect::>() .immediately() @@ -313,7 +316,7 @@ async fn serial_resume() { .expect("subscribe never fails"); let events = events - .filter(fixtures::filter::messages()) + .filter_map(fixtures::message::events) .take(resume_messages.len()) .collect::>() .immediately() @@ -351,7 +354,7 @@ async fn serial_resume() { .expect("subscribe never fails"); let events = events - .filter(fixtures::filter::messages()) + .filter_map(fixtures::message::events) .take(final_messages.len()) .collect::>() .immediately() @@ -401,6 +404,7 @@ async fn terminates_on_token_expiry() { ]; assert!(events + .filter_map(fixtures::message::events) .filter(|event| future::ready( messages .iter() @@ -452,6 +456,7 @@ async fn terminates_on_logout() { ]; assert!(events + .filter_map(fixtures::message::events) .filter(|event| future::ready( messages .iter() diff --git a/src/event/sequence.rs b/src/event/sequence.rs index bf6d5b8..9bc399b 100644 --- a/src/event/sequence.rs +++ b/src/event/sequence.rs @@ -10,6 +10,17 @@ pub struct Instant { pub sequence: Sequence, } +impl Instant { + pub fn new(at: DateTime, sequence: Sequence) -> Self { + Self { at, sequence } + } + + pub fn optional(at: Option, sequence: Option) -> Option { + at.zip(sequence) + .map(|(at, sequence)| Self::new(at, sequence)) + } +} + impl From for Sequence { fn from(instant: Instant) -> Self { instant.sequence diff --git a/src/expire.rs b/src/expire.rs index eaedc44..1427a8d 100644 --- a/src/expire.rs +++ b/src/expire.rs @@ -16,6 +16,8 @@ pub async fn middleware( app.tokens().expire(&expired_at).await?; app.invites().expire(&expired_at).await?; app.messages().expire(&expired_at).await?; + app.messages().purge(&expired_at).await?; app.channels().expire(&expired_at).await?; + app.channels().purge(&expired_at).await?; Ok(next.run(req).await) } diff --git a/src/login/repo.rs b/src/login/repo.rs index 6d6510c..7d0fcb1 100644 --- a/src/login/repo.rs +++ b/src/login/repo.rs @@ -49,10 +49,7 @@ impl<'c> Logins<'c> { id: row.id, name: row.name, }, - created: Instant { - at: row.created_at, - sequence: row.created_sequence, - }, + created: Instant::new(row.created_at, row.created_sequence), }) .fetch_one(&mut *self.0) .await?; @@ -79,10 +76,7 @@ impl<'c> Logins<'c> { id: row.id, name: row.name, }, - created: Instant { - at: row.created_at, - sequence: row.created_sequence, - }, + created: Instant::new(row.created_at, row.created_sequence), }) .fetch_all(&mut *self.0) .await?; @@ -107,10 +101,7 @@ impl<'c> Logins<'c> { id: row.id, name: row.name, }, - created: Instant { - at: row.created_at, - sequence: row.created_sequence, - }, + created: Instant::new(row.created_at, row.created_sequence), }) .fetch_all(&mut *self.0) .await?; diff --git a/src/message/app.rs b/src/message/app.rs index c1bcde6..4e50513 100644 --- a/src/message/app.rs +++ b/src/message/app.rs @@ -46,8 +46,17 @@ impl<'a> Messages<'a> { pub async fn delete(&self, message: &Id, deleted_at: &DateTime) -> Result<(), DeleteError> { let mut tx = self.db.begin().await?; + let message = tx + .messages() + .by_id(message) + .await + .not_found(|| DeleteError::NotFound(message.clone()))?; + message + .as_snapshot() + .ok_or_else(|| DeleteError::Deleted(message.id().clone()))?; + let deleted = tx.sequence().next(deleted_at).await?; - let message = tx.messages().delete(message, &deleted).await?; + let message = tx.messages().delete(&message, &deleted).await?; tx.commit().await?; self.events.broadcast( @@ -91,6 +100,17 @@ impl<'a> Messages<'a> { Ok(()) } + + pub async fn purge(&self, relative_to: &DateTime) -> Result<(), sqlx::Error> { + // Somewhat arbitrarily, purge after 6 hours. + let purge_at = relative_to.to_owned() - TimeDelta::hours(6); + + let mut tx = self.db.begin().await?; + tx.messages().purge(&purge_at).await?; + tx.commit().await?; + + Ok(()) + } } #[derive(Debug, thiserror::Error)] @@ -107,6 +127,8 @@ pub enum DeleteError { ChannelNotFound(channel::Id), #[error("message {0} not found")] NotFound(Id), + #[error("message {0} deleted")] + Deleted(Id), #[error(transparent)] Database(#[from] sqlx::Error), } diff --git a/src/message/history.rs b/src/message/history.rs index 09e69b7..0424d0d 100644 --- a/src/message/history.rs +++ b/src/message/history.rs @@ -30,6 +30,11 @@ impl History { .filter(Sequence::up_to(resume_point.into())) .collect() } + + // Snapshot of this message as of all events recorded in this history. + pub fn as_snapshot(&self) -> Option { + self.events().collect() + } } // Events interface diff --git a/src/message/repo.rs b/src/message/repo.rs index 71c6d10..14ff7bf 100644 --- a/src/message/repo.rs +++ b/src/message/repo.rs @@ -53,14 +53,12 @@ impl<'c> Messages<'c> { ) .map(|row| History { message: Message { - sent: Instant { - at: row.sent_at, - sequence: row.sent_sequence, - }, + sent: Instant::new(row.sent_at, row.sent_sequence), channel: row.channel, sender: row.sender, id: row.id, body: row.body, + deleted_at: None, }, deleted: None, }) @@ -70,41 +68,37 @@ impl<'c> Messages<'c> { Ok(message) } - pub async fn in_channel( - &mut self, - channel: &channel::History, - resume_at: ResumePoint, - ) -> Result, sqlx::Error> { + pub async fn live(&mut self, channel: &channel::History) -> Result, sqlx::Error> { let channel_id = channel.id(); let messages = sqlx::query!( r#" select - channel as "channel: channel::Id", - sender as "sender: login::Id", + message.channel as "channel: channel::Id", + message.sender as "sender: login::Id", id as "id: Id", - body, - sent_at as "sent_at: DateTime", - sent_sequence as "sent_sequence: Sequence" + message.body, + message.sent_at as "sent_at: DateTime", + message.sent_sequence as "sent_sequence: Sequence", + deleted.deleted_at as "deleted_at: DateTime", + deleted.deleted_sequence as "deleted_sequence: Sequence" from message - where channel = $1 - and coalesce(sent_sequence <= $2, true) - order by sent_sequence + left join message_deleted as deleted + using (id) + where message.channel = $1 + and deleted.id is null "#, channel_id, - resume_at, ) .map(|row| History { message: Message { - sent: Instant { - at: row.sent_at, - sequence: row.sent_sequence, - }, + sent: Instant::new(row.sent_at, row.sent_sequence), channel: row.channel, sender: row.sender, id: row.id, body: row.body, + deleted_at: row.deleted_at, }, - deleted: None, + deleted: Instant::optional(row.deleted_at, row.deleted_sequence), }) .fetch_all(&mut *self.0) .await?; @@ -116,30 +110,32 @@ impl<'c> Messages<'c> { let messages = sqlx::query!( r#" select - channel as "channel: channel::Id", - sender as "sender: login::Id", + message.channel as "channel: channel::Id", + message.sender as "sender: login::Id", id as "id: Id", - body, - sent_at as "sent_at: DateTime", - sent_sequence as "sent_sequence: Sequence" + message.body, + message.sent_at as "sent_at: DateTime", + message.sent_sequence as "sent_sequence: Sequence", + deleted.deleted_at as "deleted_at: DateTime", + deleted.deleted_sequence as "deleted_sequence: Sequence" from message - where coalesce(sent_sequence <= $2, true) - order by sent_sequence + left join message_deleted as deleted + using (id) + where coalesce(message.sent_sequence <= $2, true) + order by message.sent_sequence "#, resume_at, ) .map(|row| History { message: Message { - sent: Instant { - at: row.sent_at, - sequence: row.sent_sequence, - }, + sent: Instant::new(row.sent_at, row.sent_sequence), channel: row.channel, sender: row.sender, id: row.id, body: row.body, + deleted_at: row.deleted_at, }, - deleted: None, + deleted: Instant::optional(row.deleted_at, row.deleted_sequence), }) .fetch_all(&mut *self.0) .await?; @@ -147,33 +143,35 @@ impl<'c> Messages<'c> { Ok(messages) } - async fn by_id(&mut self, message: &Id) -> Result { + pub async fn by_id(&mut self, message: &Id) -> Result { let message = sqlx::query!( r#" select - channel as "channel: channel::Id", - sender as "sender: login::Id", + message.channel as "channel: channel::Id", + message.sender as "sender: login::Id", id as "id: Id", - body, - sent_at as "sent_at: DateTime", - sent_sequence as "sent_sequence: Sequence" + message.body, + message.sent_at as "sent_at: DateTime", + message.sent_sequence as "sent_sequence: Sequence", + deleted.deleted_at as "deleted_at: DateTime", + deleted.deleted_sequence as "deleted_sequence: Sequence" from message + left join message_deleted as deleted + using (id) where id = $1 "#, message, ) .map(|row| History { message: Message { - sent: Instant { - at: row.sent_at, - sequence: row.sent_sequence, - }, + sent: Instant::new(row.sent_at, row.sent_sequence), channel: row.channel, sender: row.sender, id: row.id, body: row.body, + deleted_at: row.deleted_at, }, - deleted: None, + deleted: Instant::optional(row.deleted_at, row.deleted_sequence), }) .fetch_one(&mut *self.0) .await?; @@ -183,39 +181,103 @@ impl<'c> Messages<'c> { pub async fn delete( &mut self, - message: &Id, + message: &History, deleted: &Instant, ) -> Result { - let history = self.by_id(message).await?; + let id = message.id(); sqlx::query_scalar!( r#" - delete from message - where - id = $1 - returning 1 as "deleted: i64" + insert into message_deleted (id, deleted_at, deleted_sequence) + values ($1, $2, $3) + returning 1 as "deleted: bool" "#, - history.message.id, + id, + deleted.at, + deleted.sequence, ) .fetch_one(&mut *self.0) .await?; - Ok(History { - deleted: Some(*deleted), - ..history - }) + // Small social responsibility hack here: when a message is deleted, its body is + // retconned to have been the empty string. Someone reading the event stream + // afterwards, or looking at messages in the channel, cannot retrieve the + // "deleted" message by ignoring the deletion event. + sqlx::query_scalar!( + r#" + update message + set body = "" + where id = $1 + returning 1 as "blanked: bool" + "#, + id, + ) + .fetch_one(&mut *self.0) + .await?; + + let message = self.by_id(id).await?; + + Ok(message) } - pub async fn expired(&mut self, expire_at: &DateTime) -> Result, sqlx::Error> { + pub async fn purge(&mut self, purge_at: &DateTime) -> Result<(), sqlx::Error> { let messages = sqlx::query_scalar!( + r#" + delete from message_deleted + where deleted_at < $1 + returning id as "id: Id" + "#, + purge_at, + ) + .fetch_all(&mut *self.0) + .await?; + + for message in messages { + sqlx::query!( + r#" + delete from message + where id = $1 + "#, + message, + ) + .execute(&mut *self.0) + .await?; + } + + Ok(()) + } + + pub async fn expired(&mut self, expire_at: &DateTime) -> Result, sqlx::Error> { + let messages = sqlx::query!( r#" select - id as "message: Id" + id as "id: Id", + message.channel as "channel: channel::Id", + message.sender as "sender: login::Id", + message.sent_at as "sent_at: DateTime", + message.sent_sequence as "sent_sequence: Sequence", + message.body, + deleted.deleted_at as "deleted_at: DateTime", + deleted.deleted_sequence as "deleted_sequence: Sequence" from message - where sent_at < $1 + left join message_deleted as deleted + using (id) + where message.sent_at < $1 + and deleted.id is null "#, expire_at, ) + .map(|row| History { + message: Message { + sent: Instant::new(row.sent_at, row.sent_sequence), + id: row.id, + channel: row.channel, + sender: row.sender, + body: row.body, + deleted_at: row.deleted_at, + }, + deleted: Instant::optional(row.deleted_at, row.deleted_sequence), + }) .fetch_all(&mut *self.0) .await?; @@ -226,29 +288,31 @@ impl<'c> Messages<'c> { let messages = sqlx::query!( r#" select - channel as "channel: channel::Id", - sender as "sender: login::Id", id as "id: Id", - body, - sent_at as "sent_at: DateTime", - sent_sequence as "sent_sequence: Sequence" + message.channel as "channel: channel::Id", + message.sender as "sender: login::Id", + message.sent_at as "sent_at: DateTime", + message.sent_sequence as "sent_sequence: Sequence", + message.body, + deleted.deleted_at as "deleted_at: DateTime", + deleted.deleted_sequence as "deleted_sequence: Sequence" from message + left join message_deleted as deleted + using (id) where coalesce(message.sent_sequence > $1, true) "#, resume_at, ) .map(|row| History { message: Message { - sent: Instant { - at: row.sent_at, - sequence: row.sent_sequence, - }, + sent: Instant::new(row.sent_at, row.sent_sequence), channel: row.channel, sender: row.sender, id: row.id, body: row.body, + deleted_at: row.deleted_at, }, - deleted: None, + deleted: Instant::optional(row.deleted_at, row.deleted_sequence), }) .fetch_all(&mut *self.0) .await?; diff --git a/src/message/routes/message.rs b/src/message/routes/message.rs index 059b8c1..fbef35a 100644 --- a/src/message/routes/message.rs +++ b/src/message/routes/message.rs @@ -33,9 +33,9 @@ pub mod delete { let Self(error) = self; #[allow(clippy::match_wildcard_for_single_variants)] match error { - DeleteError::ChannelNotFound(_) | DeleteError::NotFound(_) => { - NotFound(error).into_response() - } + DeleteError::ChannelNotFound(_) + | DeleteError::NotFound(_) + | DeleteError::Deleted(_) => NotFound(error).into_response(), other => Internal::from(other).into_response(), } } diff --git a/src/message/snapshot.rs b/src/message/snapshot.rs index 0eb37bb..7300918 100644 --- a/src/message/snapshot.rs +++ b/src/message/snapshot.rs @@ -2,7 +2,7 @@ use super::{ event::{Event, Sent}, Id, }; -use crate::{channel, event::Instant, login}; +use crate::{channel, clock::DateTime, event::Instant, login}; #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize)] pub struct Message { @@ -12,6 +12,8 @@ pub struct Message { pub sender: login::Id, pub id: Id, pub body: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub deleted_at: Option, } impl Message { diff --git a/src/test/fixtures/channel.rs b/src/test/fixtures/channel.rs index b678717..a1dda61 100644 --- a/src/test/fixtures/channel.rs +++ b/src/test/fixtures/channel.rs @@ -1,10 +1,17 @@ +use std::future; + use faker_rand::{ en_us::{addresses::CityName, names::FullName}, faker_impl_from_templates, }; use rand; -use crate::{app::App, channel::Channel, clock::RequestedAt}; +use crate::{ + app::App, + channel::{self, Channel}, + clock::RequestedAt, + event::Event, +}; pub async fn create(app: &App, created_at: &RequestedAt) -> Channel { let name = propose(); @@ -22,3 +29,17 @@ struct Name(String); faker_impl_from_templates! { Name; "{} {}", CityName, FullName; } + +pub fn events(event: Event) -> future::Ready> { + future::ready(match event { + Event::Channel(channel) => Some(channel), + _ => None, + }) +} + +pub fn created(event: channel::Event) -> future::Ready> { + future::ready(match event { + channel::Event::Created(event) => Some(event), + channel::Event::Deleted(_) => None, + }) +} diff --git a/src/test/fixtures/event.rs b/src/test/fixtures/event.rs index 7fe2bf3..fa4fbc0 100644 --- a/src/test/fixtures/event.rs +++ b/src/test/fixtures/event.rs @@ -1,11 +1,8 @@ -use crate::{ - event::Event, - message::{Event::Sent, Message}, -}; +use crate::message::{Event, Message}; pub fn message_sent(event: &Event, message: &Message) -> bool { matches!( &event, - Event::Message(Sent(event)) if message == &event.into() + Event::Sent(event) if message == &event.into() ) } diff --git a/src/test/fixtures/filter.rs b/src/test/fixtures/filter.rs deleted file mode 100644 index 84d27b0..0000000 --- a/src/test/fixtures/filter.rs +++ /dev/null @@ -1,11 +0,0 @@ -use futures::future; - -use crate::{channel::Event::Created, event::Event, message::Event::Sent}; - -pub fn messages() -> impl FnMut(&Event) -> future::Ready { - |event| future::ready(matches!(event, Event::Message(Sent(_)))) -} - -pub fn created() -> impl FnMut(&Event) -> future::Ready { - |event| future::ready(matches!(event, Event::Channel(Created(_)))) -} diff --git a/src/test/fixtures/message.rs b/src/test/fixtures/message.rs index 381b10b..eb00e7c 100644 --- a/src/test/fixtures/message.rs +++ b/src/test/fixtures/message.rs @@ -1,6 +1,15 @@ +use std::future; + use faker_rand::lorem::Paragraphs; -use crate::{app::App, channel::Channel, clock::RequestedAt, login::Login, message::Message}; +use crate::{ + app::App, + channel::Channel, + clock::RequestedAt, + event::Event, + login::Login, + message::{self, Message}, +}; pub async fn send(app: &App, channel: &Channel, login: &Login, sent_at: &RequestedAt) -> Message { let body = propose(); @@ -14,3 +23,10 @@ pub async fn send(app: &App, channel: &Channel, login: &Login, sent_at: &Request pub fn propose() -> String { rand::random::().to_string() } + +pub fn events(event: Event) -> future::Ready> { + future::ready(match event { + Event::Message(event) => Some(event), + _ => None, + }) +} diff --git a/src/test/fixtures/mod.rs b/src/test/fixtures/mod.rs index 41f7e13..9658831 100644 --- a/src/test/fixtures/mod.rs +++ b/src/test/fixtures/mod.rs @@ -4,7 +4,6 @@ use crate::{app::App, clock::RequestedAt, db}; pub mod channel; pub mod event; -pub mod filter; pub mod future; pub mod identity; pub mod login; diff --git a/src/token/repo/auth.rs b/src/token/repo/auth.rs index 9aee81f..88d0878 100644 --- a/src/token/repo/auth.rs +++ b/src/token/repo/auth.rs @@ -40,10 +40,7 @@ impl<'t> Auth<'t> { id: row.id, name: row.name, }, - created: Instant { - at: row.created_at, - sequence: row.created_sequence, - }, + created: Instant::new(row.created_at, row.created_sequence), }, row.password_hash, ) -- cgit v1.2.3 From ad00b553d845dba8af7b0e9fa2930209aee1dd62 Mon Sep 17 00:00:00 2001 From: Owen Jacobson Date: Sat, 19 Oct 2024 00:57:20 -0400 Subject: Make the responses for various data creation requests more consistent. In general: * If the client can only assume the response is immediately valid (mostly, login creation, where the client cannot monitor the event stream), then 200 Okay, with data describing the server's view of the request. * If the client can monitor for completion by watching the event stream, then 202 Accepted, with data describing the server's view of the request. This comes on the heels of a comment I made on Discord: > hrm > > creating a login: 204 No Content, no body > sending a message: 202 Accepted, no body > creating a channel: 200 Okay, has a body > > past me, what were you on There wasn't any principled reason for this inconsistency; it happened as the endpoints were written at different times and with different states of mind. --- docs/api/authentication.md | 16 +++++++++++++++- docs/api/channels-messages.md | 38 +++++++++++++++++++++++++++++++++----- docs/api/events.md | 5 +++++ docs/api/initial-setup.md | 16 +++++++++++++++- docs/api/invitations.md | 16 +++++++++++++++- src/channel/routes/channel/post.rs | 23 +++++++++++++++++------ src/channel/routes/channel/test.rs | 2 +- src/channel/routes/post.rs | 14 ++++++++++++-- src/channel/routes/test.rs | 16 +++++++++------- src/invite/app.rs | 4 ++-- src/invite/routes/invite/post.rs | 8 ++++---- src/login/history.rs | 6 +++++- src/login/routes/login/post.rs | 10 +++++----- src/login/routes/login/test.rs | 22 +++++++++++----------- src/setup/app.rs | 6 +++--- src/setup/routes/post.rs | 12 ++++++++---- src/test/fixtures/identity.rs | 12 ++++++------ src/test/fixtures/login.rs | 7 ++++--- src/token/app.rs | 6 ++++-- 19 files changed, 174 insertions(+), 65 deletions(-) (limited to 'src/channel/routes/test.rs') diff --git a/docs/api/authentication.md b/docs/api/authentication.md index d4c1f70..7e05443 100644 --- a/docs/api/authentication.md +++ b/docs/api/authentication.md @@ -56,7 +56,21 @@ The request must have the following fields: -This endpoint will respond with a status of `204 No Content` when successful. +This endpoint will respond with a status of `200 Okay` when successful. The body of the response will be a JSON object describing the authenticated login: + +```json +{ + "id": "Labcd1234", + "name": "Andrea" +} +``` + +The response will include the following fields: + +| Field | Type | Description | +|:------------|:-------|:--| +| `id` | string | The authenticated login's ID. | +| `name` | string | The authenticated login's name. | The response will include a `Set-Cookie` header for the `identity` cookie, providing the client with a newly-minted identity token associated with the login identified in the request. This token's value must be kept confidential. diff --git a/docs/api/channels-messages.md b/docs/api/channels-messages.md index 99a525e..69cadcb 100644 --- a/docs/api/channels-messages.md +++ b/docs/api/channels-messages.md @@ -54,12 +54,12 @@ The request must have the following fields: ### Success -This endpoint will respond with a status of `200 Okay` when successful. The body of the response will be a JSON object describing the new channel: +This endpoint will respond with a status of `202 Accepted` when successful. The body of the response will be a JSON object describing the new channel: ```json { - "name": "a unique channel name", "id": "C9876cyyz" + "name": "a unique channel name", } ``` @@ -67,8 +67,10 @@ The response will have the following fields: | Field | Type | Description | |:-------|:-------|:--| +| `id` | string | A unique identifier for the channel. This can be used to associate the channel with events, or to make API calls targeting the channel. | | `name` | string | The channel's name. | -| `id` | string | A unique identifier for the channel. This can be used to associate the channel with other events, or to make API calls targeting the channel. | + +When completed, the service will emit a [channel created](events.md#channel-created) event with the channel's ID. ### Duplicate channel name @@ -101,14 +103,35 @@ The request must have the following fields: ### Success -This endpoint will respond with a status of `202 Accepted` when successful. The response will not include a body. +This endpoint will respond with a status of `202 Accepted` when successful. The body of the response will be a JSON object describing the newly-sent message: + +```json +{ + "at": "2024-10-19T04:37:09.467325Z", + "channel": "Cfqdn1234", + "sender": "Labcd1234", + "id": "Mgh98yp75", + "body": "an elaborate example message" +} +``` + +The response will have the following fields: + +| Field | Type | Description | +|:----------|:----------|:--| +| `at` | timestamp | The moment the message was sent. | +| `channel` | string | The ID of the channel the message was sent to. | +| `sender` | string | The ID of the login that sent the message. | +| `id` | string | A unique identifier for the message. This can be used to associate the message with events, or to make API calls targeting the message. | +| `body` | string | The message's body. | + +When completed, the service will emit a [message sent](events.md#message-sent) event with the message's ID. ### Invalid channel ID This endpoint will respond with a status of `404 Not Found` if the channel ID is not valid. - ## `DELETE /api/channels/:id` Deletes a channel (and all messages in it). @@ -123,6 +146,9 @@ This endpoint requires the following path parameter: This endpoint will respond with a status of `202 Accepted` when successful. The response will not include a body. +When completed, the service will emit a [channel deleted](events.md#channel-deleted) event with the channel's ID. + + ### Invalid channel ID This endpoint will respond with a status of `404 Not Found` if the channel ID is not valid. @@ -142,6 +168,8 @@ This endpoint requires the following path parameter: This endpoint will respond with a status of `202 Accepted` when successful. The response will not include a body. +When completed, the service will emit a [message deleted](events.md#message-deleted) event with the channel's ID. + ### Invalid message ID This endpoint will respond with a status of `404 Not Found` if the message ID is not valid. diff --git a/docs/api/events.md b/docs/api/events.md index 2f48df1..b08e971 100644 --- a/docs/api/events.md +++ b/docs/api/events.md @@ -31,6 +31,11 @@ sequenceDiagram The core of the service is to facilitate conversations between logins. Conversational activity is delivered to clients using _events_. Each event notifies interested clients of activity sent to the service through its API. +## Asynchronous completion + +A number of endpoints return `202 Accepted` responses. The actions performed by those endpoints will be completed before events are delivered. To await the completion of an operation which returns this response, clients must monitor the event stream for the corresponding event. + + ## `GET /api/events` Subscribes to events. diff --git a/docs/api/initial-setup.md b/docs/api/initial-setup.md index ad57089..3c5a8a6 100644 --- a/docs/api/initial-setup.md +++ b/docs/api/initial-setup.md @@ -55,7 +55,21 @@ The request must have the following fields: -This endpoint will respond with a status of `204 No Content` when successful. +This endpoint will respond with a status of `200 Okay` when successful. The body of the response will be a JSON object describing the newly-created login: + +```json +{ + "id": "Labcd1234", + "name": "Andrea" +} +``` + +The response will include the following fields: + +| Field | Type | Description | +|:------------|:-------|:--| +| `id` | string | A unique identifier for the newly-created login. This can be used to associate the login with other events, or to make API calls targeting the login. | +| `name` | string | The login's name. | The response will include a `Set-Cookie` header for the `identity` cookie, providing the client with a newly-minted identity token associated with the initial login created for this request. See the [authentication](./authentication) section for details on how this cookie may be used. diff --git a/docs/api/invitations.md b/docs/api/invitations.md index f75e30b..d3431d7 100644 --- a/docs/api/invitations.md +++ b/docs/api/invitations.md @@ -134,7 +134,21 @@ The request must have the following fields: -This endpoint will respond with a status of `204 No Content` when successful. +This endpoint will respond with a status of `200 Okay` when successful. The body of the response will be a JSON object describing the newly-created login: + +```json +{ + "id": "Labcd1234", + "name": "Andrea" +} +``` + +The response will include the following fields: + +| Field | Type | Description | +|:------------|:-------|:--| +| `id` | string | A unique identifier for the newly-created login. This can be used to associate the login with other events, or to make API calls targeting the login. | +| `name` | string | The login's name. | The response will include a `Set-Cookie` header for the `identity` cookie, providing the client with a newly-minted identity token associated with the login created for this request. See the [authentication](./authentication.md) section for details on how this cookie may be used. diff --git a/src/channel/routes/channel/post.rs b/src/channel/routes/channel/post.rs index a71a3a0..b489a77 100644 --- a/src/channel/routes/channel/post.rs +++ b/src/channel/routes/channel/post.rs @@ -1,7 +1,7 @@ use axum::{ extract::{Json, Path, State}, http::StatusCode, - response::{IntoResponse, Response}, + response::{self, IntoResponse}, }; use crate::{ @@ -9,7 +9,7 @@ use crate::{ clock::RequestedAt, error::{Internal, NotFound}, login::Login, - message::app::SendError, + message::{app::SendError, Message}, }; pub async fn handler( @@ -18,12 +18,13 @@ pub async fn handler( RequestedAt(sent_at): RequestedAt, login: Login, Json(request): Json, -) -> Result { - app.messages() +) -> Result { + let message = app + .messages() .send(&channel, &login, &sent_at, &request.body) .await?; - Ok(StatusCode::ACCEPTED) + Ok(Response(message)) } #[derive(serde::Deserialize)] @@ -31,12 +32,22 @@ pub struct Request { pub body: String, } +#[derive(Debug)] +pub struct Response(pub Message); + +impl IntoResponse for Response { + fn into_response(self) -> response::Response { + let Self(message) = self; + (StatusCode::ACCEPTED, Json(message)).into_response() + } +} + #[derive(Debug, thiserror::Error)] #[error(transparent)] pub struct Error(#[from] pub SendError); impl IntoResponse for Error { - fn into_response(self) -> Response { + fn into_response(self) -> response::Response { let Self(error) = self; #[allow(clippy::match_wildcard_for_single_variants)] match error { diff --git a/src/channel/routes/channel/test.rs b/src/channel/routes/channel/test.rs index c6541cd..b895b69 100644 --- a/src/channel/routes/channel/test.rs +++ b/src/channel/routes/channel/test.rs @@ -27,7 +27,7 @@ async fn messages_in_order() { for (sent_at, body) in &requests { let request = post::Request { body: body.clone() }; - post::handler( + let _ = post::handler( State(app.clone()), Path(channel.id.clone()), sent_at.clone(), diff --git a/src/channel/routes/post.rs b/src/channel/routes/post.rs index d694f8b..a05c312 100644 --- a/src/channel/routes/post.rs +++ b/src/channel/routes/post.rs @@ -17,14 +17,14 @@ pub async fn handler( _: Login, // requires auth, but doesn't actually care who you are RequestedAt(created_at): RequestedAt, Json(request): Json, -) -> Result, Error> { +) -> Result { let channel = app .channels() .create(&request.name, &created_at) .await .map_err(Error)?; - Ok(Json(channel)) + Ok(Response(channel)) } #[derive(serde::Deserialize)] @@ -32,6 +32,16 @@ pub struct Request { pub name: String, } +#[derive(Debug)] +pub struct Response(pub Channel); + +impl IntoResponse for Response { + fn into_response(self) -> response::Response { + let Self(channel) = self; + (StatusCode::ACCEPTED, Json(channel)).into_response() + } +} + #[derive(Debug)] pub struct Error(pub app::CreateError); diff --git a/src/channel/routes/test.rs b/src/channel/routes/test.rs index ffd8484..7879ba0 100644 --- a/src/channel/routes/test.rs +++ b/src/channel/routes/test.rs @@ -20,9 +20,10 @@ async fn new_channel() { let name = fixtures::channel::propose(); let request = post::Request { name: name.clone() }; - let Json(response) = post::handler(State(app.clone()), creator, fixtures::now(), Json(request)) - .await - .expect("creating a channel in an empty app succeeds"); + let post::Response(response) = + post::handler(State(app.clone()), creator, fixtures::now(), Json(request)) + .await + .expect("creating a channel in an empty app succeeds"); // Verify the structure of the response @@ -96,7 +97,7 @@ async fn name_reusable_after_delete() { // Call the endpoint (first time) let request = post::Request { name: name.clone() }; - let Json(response) = post::handler( + let post::Response(response) = post::handler( State(app.clone()), creator.clone(), fixtures::now(), @@ -115,9 +116,10 @@ async fn name_reusable_after_delete() { // Call the endpoint (second time) let request = post::Request { name: name.clone() }; - let Json(response) = post::handler(State(app.clone()), creator, fixtures::now(), Json(request)) - .await - .expect("new channel in an empty app"); + let post::Response(response) = + post::handler(State(app.clone()), creator, fixtures::now(), Json(request)) + .await + .expect("new channel in an empty app"); // Verify the structure of the response diff --git a/src/invite/app.rs b/src/invite/app.rs index 4162470..ee7f74f 100644 --- a/src/invite/app.rs +++ b/src/invite/app.rs @@ -45,7 +45,7 @@ impl<'a> Invites<'a> { name: &str, password: &Password, accepted_at: &DateTime, - ) -> Result { + ) -> Result<(Login, Secret), AcceptError> { let mut tx = self.db.begin().await?; let invite = tx .invites() @@ -72,7 +72,7 @@ impl<'a> Invites<'a> { let secret = tx.tokens().issue(&login, accepted_at).await?; tx.commit().await?; - Ok(secret) + Ok((login.as_created(), secret)) } pub async fn expire(&self, relative_to: &DateTime) -> Result<(), sqlx::Error> { diff --git a/src/invite/routes/invite/post.rs b/src/invite/routes/invite/post.rs index 12c2e21..c072929 100644 --- a/src/invite/routes/invite/post.rs +++ b/src/invite/routes/invite/post.rs @@ -9,7 +9,7 @@ use crate::{ clock::RequestedAt, error::{Internal, NotFound}, invite::app, - login::Password, + login::{Login, Password}, token::extract::IdentityToken, }; @@ -19,14 +19,14 @@ pub async fn handler( identity: IdentityToken, Path(invite): Path, Json(request): Json, -) -> Result<(IdentityToken, StatusCode), Error> { - let secret = app +) -> Result<(IdentityToken, Json), Error> { + let (login, secret) = app .invites() .accept(&invite, &request.name, &request.password, &accepted_at) .await .map_err(Error)?; let identity = identity.set(secret); - Ok((identity, StatusCode::NO_CONTENT)) + Ok((identity, Json(login))) } #[derive(serde::Deserialize)] diff --git a/src/login/history.rs b/src/login/history.rs index f8d81bb..daad579 100644 --- a/src/login/history.rs +++ b/src/login/history.rs @@ -20,7 +20,6 @@ impl History { // if this returns a redacted or modified version of the login. If we implement // renames by redacting the original name, then this should return the edited // login, not the original, even if that's not how it was "as created.") - #[cfg(test)] pub fn as_created(&self) -> Login { self.login.clone() } @@ -30,6 +29,11 @@ impl History { .filter(Sequence::up_to(resume_point.into())) .collect() } + + // Snapshot of this login, as of all events recorded in this history. + pub fn as_snapshot(&self) -> Option { + self.events().collect() + } } // Events interface diff --git a/src/login/routes/login/post.rs b/src/login/routes/login/post.rs index e33acad..67eaa6d 100644 --- a/src/login/routes/login/post.rs +++ b/src/login/routes/login/post.rs @@ -8,7 +8,7 @@ use crate::{ app::App, clock::RequestedAt, error::Internal, - login::Password, + login::{Login, Password}, token::{app, extract::IdentityToken}, }; @@ -17,14 +17,14 @@ pub async fn handler( RequestedAt(now): RequestedAt, identity: IdentityToken, Json(request): Json, -) -> Result<(IdentityToken, StatusCode), Error> { - let token = app +) -> Result<(IdentityToken, Json), Error> { + let (login, secret) = app .tokens() .login(&request.name, &request.password, &now) .await .map_err(Error)?; - let identity = identity.set(token); - Ok((identity, StatusCode::NO_CONTENT)) + let identity = identity.set(secret); + Ok((identity, Json(login))) } #[derive(serde::Deserialize)] diff --git a/src/login/routes/login/test.rs b/src/login/routes/login/test.rs index d431612..c94f14c 100644 --- a/src/login/routes/login/test.rs +++ b/src/login/routes/login/test.rs @@ -1,7 +1,4 @@ -use axum::{ - extract::{Json, State}, - http::StatusCode, -}; +use axum::extract::{Json, State}; use super::post; use crate::{test::fixtures, token::app}; @@ -11,24 +8,24 @@ async fn correct_credentials() { // Set up the environment let app = fixtures::scratch_app().await; - let (name, password) = fixtures::login::create_with_password(&app, &fixtures::now()).await; + let (login, password) = fixtures::login::create_with_password(&app, &fixtures::now()).await; // Call the endpoint let identity = fixtures::identity::not_logged_in(); let logged_in_at = fixtures::now(); let request = post::Request { - name: name.clone(), + name: login.name.clone(), password, }; - let (identity, status) = + let (identity, Json(response)) = post::handler(State(app.clone()), logged_in_at, identity, Json(request)) .await .expect("logged in with valid credentials"); // Verify the return value's basic structure - assert_eq!(StatusCode::NO_CONTENT, status); + assert_eq!(login, response); let secret = identity.secret().expect("logged in with valid credentials"); // Verify the semantics @@ -40,7 +37,7 @@ async fn correct_credentials() { .await .expect("identity secret is valid"); - assert_eq!(name, validated_login.name); + assert_eq!(login, validated_login); } #[tokio::test] @@ -98,13 +95,16 @@ async fn token_expires() { // Set up the environment let app = fixtures::scratch_app().await; - let (name, password) = fixtures::login::create_with_password(&app, &fixtures::now()).await; + let (login, password) = fixtures::login::create_with_password(&app, &fixtures::now()).await; // Call the endpoint let logged_in_at = fixtures::ancient(); let identity = fixtures::identity::not_logged_in(); - let request = post::Request { name, password }; + let request = post::Request { + name: login.name.clone(), + password, + }; let (identity, _) = post::handler(State(app.clone()), logged_in_at, identity, Json(request)) .await .expect("logged in with valid credentials"); diff --git a/src/setup/app.rs b/src/setup/app.rs index 24e0010..d015813 100644 --- a/src/setup/app.rs +++ b/src/setup/app.rs @@ -4,7 +4,7 @@ use super::repo::Provider as _; use crate::{ clock::DateTime, event::{repo::Provider as _, Broadcaster, Event}, - login::{repo::Provider as _, Password}, + login::{repo::Provider as _, Login, Password}, token::{repo::Provider as _, Secret}, }; @@ -23,7 +23,7 @@ impl<'a> Setup<'a> { name: &str, password: &Password, created_at: &DateTime, - ) -> Result { + ) -> Result<(Login, Secret), Error> { let password_hash = password.hash()?; let mut tx = self.db.begin().await?; @@ -39,7 +39,7 @@ impl<'a> Setup<'a> { self.events .broadcast(login.events().map(Event::from).collect::>()); - Ok(secret) + Ok((login.as_created(), secret)) } pub async fn completed(&self) -> Result { diff --git a/src/setup/routes/post.rs b/src/setup/routes/post.rs index 9e6776f..34f4ed2 100644 --- a/src/setup/routes/post.rs +++ b/src/setup/routes/post.rs @@ -5,7 +5,11 @@ use axum::{ }; use crate::{ - app::App, clock::RequestedAt, error::Internal, login::Password, setup::app, + app::App, + clock::RequestedAt, + error::Internal, + login::{Login, Password}, + setup::app, token::extract::IdentityToken, }; @@ -14,14 +18,14 @@ pub async fn handler( RequestedAt(setup_at): RequestedAt, identity: IdentityToken, Json(request): Json, -) -> Result<(IdentityToken, StatusCode), Error> { - let secret = app +) -> Result<(IdentityToken, Json), Error> { + let (login, secret) = app .setup() .initial(&request.name, &request.password, &setup_at) .await .map_err(Error)?; let identity = identity.set(secret); - Ok((identity, StatusCode::NO_CONTENT)) + Ok((identity, Json(login))) } #[derive(serde::Deserialize)] diff --git a/src/test/fixtures/identity.rs b/src/test/fixtures/identity.rs index 56b4ffa..c434473 100644 --- a/src/test/fixtures/identity.rs +++ b/src/test/fixtures/identity.rs @@ -3,7 +3,7 @@ use uuid::Uuid; use crate::{ app::App, clock::RequestedAt, - login::Password, + login::{Login, Password}, token::{ extract::{Identity, IdentityToken}, Secret, @@ -14,11 +14,11 @@ pub fn not_logged_in() -> IdentityToken { IdentityToken::new() } -pub async fn logged_in(app: &App, login: &(String, Password), now: &RequestedAt) -> IdentityToken { - let (name, password) = login; - let token = app +pub async fn logged_in(app: &App, login: &(Login, Password), now: &RequestedAt) -> IdentityToken { + let (login, password) = login; + let (_, token) = app .tokens() - .login(name, password, now) + .login(&login.name, password, now) .await .expect("should succeed given known-valid credentials"); @@ -36,7 +36,7 @@ pub async fn from_token(app: &App, token: &IdentityToken, issued_at: &RequestedA Identity { token, login } } -pub async fn identity(app: &App, login: &(String, Password), issued_at: &RequestedAt) -> Identity { +pub async fn identity(app: &App, login: &(Login, Password), issued_at: &RequestedAt) -> Identity { let secret = logged_in(app, login, issued_at).await; from_token(app, &secret, issued_at).await } diff --git a/src/test/fixtures/login.rs b/src/test/fixtures/login.rs index e5ac716..b6766fe 100644 --- a/src/test/fixtures/login.rs +++ b/src/test/fixtures/login.rs @@ -7,14 +7,15 @@ use crate::{ login::{self, Login, Password}, }; -pub async fn create_with_password(app: &App, created_at: &RequestedAt) -> (String, Password) { +pub async fn create_with_password(app: &App, created_at: &RequestedAt) -> (Login, Password) { let (name, password) = propose(); - app.logins() + let login = app + .logins() .create(&name, &password, created_at) .await .expect("should always succeed if the login is actually new"); - (name, password) + (login, password) } pub async fn create(app: &App, created_at: &RequestedAt) -> Login { diff --git a/src/token/app.rs b/src/token/app.rs index cb5d75f..0dc1a46 100644 --- a/src/token/app.rs +++ b/src/token/app.rs @@ -30,7 +30,7 @@ impl<'a> Tokens<'a> { name: &str, password: &Password, login_at: &DateTime, - ) -> Result { + ) -> Result<(Login, Secret), LoginError> { let mut tx = self.db.begin().await?; let (login, stored_hash) = tx .auth() @@ -45,6 +45,8 @@ impl<'a> Tokens<'a> { // if the account is deleted during that time. tx.commit().await?; + let snapshot = login.as_snapshot().ok_or(LoginError::Rejected)?; + let token = if stored_hash.verify(password)? { let mut tx = self.db.begin().await?; let token = tx.tokens().issue(&login, login_at).await?; @@ -54,7 +56,7 @@ impl<'a> Tokens<'a> { Err(LoginError::Rejected)? }; - Ok(token) + Ok((snapshot, token)) } pub async fn validate( -- cgit v1.2.3 From 01f9f3549c76702fd56e58d44c5180fecddb4bfa Mon Sep 17 00:00:00 2001 From: Owen Jacobson Date: Tue, 22 Oct 2024 23:25:24 -0400 Subject: Sort out the naming of the various parts of an identity. * A `cookie::Identity` (`IdentityCookie`) is a specialized CookieJar for working with identities. * An `Identity` is a token/login pair. I hope for this to be a bit more legible. In service of this, `Login` is no longer extractable. You have to get an identity. --- src/boot/routes/get.rs | 9 ++-- src/boot/routes/test.rs | 6 +-- src/channel/routes/channel/delete.rs | 4 +- src/channel/routes/channel/post.rs | 6 +-- src/channel/routes/channel/test.rs | 52 +++++++++++++++++--- src/channel/routes/post.rs | 4 +- src/channel/routes/test.rs | 6 +-- src/event/routes/test.rs | 26 +++------- src/invite/routes/invite/post.rs | 6 +-- src/invite/routes/post.rs | 10 ++-- src/login/extract.rs | 15 ------ src/login/mod.rs | 1 - src/login/routes/login/post.rs | 6 +-- src/login/routes/login/test.rs | 29 ++++++----- src/login/routes/logout/post.rs | 6 +-- src/login/routes/logout/test.rs | 14 +++--- src/message/app.rs | 2 - src/message/routes/message.rs | 10 ++-- src/setup/routes/post.rs | 6 +-- src/test/fixtures/cookie.rs | 37 ++++++++++++++ src/test/fixtures/identity.rs | 48 ++++++++---------- src/test/fixtures/login.rs | 4 +- src/test/fixtures/mod.rs | 1 + src/token/extract/cookie.rs | 94 ++++++++++++++++++++++++++++++++++++ src/token/extract/identity.rs | 6 +-- src/token/extract/identity_token.rs | 94 ------------------------------------ src/token/extract/mod.rs | 4 +- src/ui/routes/ch/channel.rs | 6 +-- src/ui/routes/get.rs | 6 +-- 29 files changed, 281 insertions(+), 237 deletions(-) delete mode 100644 src/login/extract.rs create mode 100644 src/test/fixtures/cookie.rs create mode 100644 src/token/extract/cookie.rs delete mode 100644 src/token/extract/identity_token.rs (limited to 'src/channel/routes/test.rs') diff --git a/src/boot/routes/get.rs b/src/boot/routes/get.rs index 737b479..563fbf1 100644 --- a/src/boot/routes/get.rs +++ b/src/boot/routes/get.rs @@ -3,11 +3,14 @@ use axum::{ response::{self, IntoResponse}, }; -use crate::{app::App, boot::Snapshot, error::Internal, login::Login}; +use crate::{app::App, boot::Snapshot, error::Internal, login::Login, token::extract::Identity}; -pub async fn handler(State(app): State, login: Login) -> Result { +pub async fn handler(State(app): State, identity: Identity) -> Result { let snapshot = app.boot().snapshot().await?; - Ok(Response { login, snapshot }) + Ok(Response { + login: identity.login, + snapshot, + }) } #[derive(serde::Serialize)] diff --git a/src/boot/routes/test.rs b/src/boot/routes/test.rs index 4023753..0430854 100644 --- a/src/boot/routes/test.rs +++ b/src/boot/routes/test.rs @@ -6,10 +6,10 @@ use crate::test::fixtures; #[tokio::test] async fn returns_identity() { let app = fixtures::scratch_app().await; - let login = fixtures::login::fictitious(); - let response = get::handler(State(app), login.clone()) + let identity = fixtures::identity::fictitious(); + let response = get::handler(State(app), identity.clone()) .await .expect("boot always succeeds"); - assert_eq!(login, response.login); + assert_eq!(identity.login, response.login); } diff --git a/src/channel/routes/channel/delete.rs b/src/channel/routes/channel/delete.rs index 5f40ddf..91eb506 100644 --- a/src/channel/routes/channel/delete.rs +++ b/src/channel/routes/channel/delete.rs @@ -9,14 +9,14 @@ use crate::{ channel::app, clock::RequestedAt, error::{Internal, NotFound}, - login::Login, + token::extract::Identity, }; pub async fn handler( State(app): State, Path(channel): Path, RequestedAt(deleted_at): RequestedAt, - _: Login, + _: Identity, ) -> Result { app.channels().delete(&channel, &deleted_at).await?; diff --git a/src/channel/routes/channel/post.rs b/src/channel/routes/channel/post.rs index d0cae05..b51e691 100644 --- a/src/channel/routes/channel/post.rs +++ b/src/channel/routes/channel/post.rs @@ -8,20 +8,20 @@ use crate::{ app::App, clock::RequestedAt, error::{Internal, NotFound}, - login::Login, message::{app::SendError, Body, Message}, + token::extract::Identity, }; pub async fn handler( State(app): State, Path(channel): Path, RequestedAt(sent_at): RequestedAt, - login: Login, + identity: Identity, Json(request): Json, ) -> Result { let message = app .messages() - .send(&channel, &login, &sent_at, &request.body) + .send(&channel, &identity.login, &sent_at, &request.body) .await?; Ok(Response(message)) diff --git a/src/channel/routes/channel/test.rs b/src/channel/routes/channel/test.rs index b895b69..9a2227d 100644 --- a/src/channel/routes/channel/test.rs +++ b/src/channel/routes/channel/test.rs @@ -14,7 +14,7 @@ async fn messages_in_order() { // Set up the environment let app = fixtures::scratch_app().await; - let sender = fixtures::login::create(&app, &fixtures::now()).await; + let sender = fixtures::identity::create(&app, &fixtures::now()).await; let channel = fixtures::channel::create(&app, &fixtures::now()).await; // Call the endpoint (twice) @@ -35,7 +35,7 @@ async fn messages_in_order() { Json(request), ) .await - .expect("sending to a valid channel"); + .expect("sending to a valid channel succeeds"); } // Verify the semantics @@ -44,7 +44,7 @@ async fn messages_in_order() { .events() .subscribe(None) .await - .expect("subscribing to a valid channel") + .expect("subscribing to a valid channel succeeds") .filter_map(fixtures::message::events) .take(requests.len()); @@ -55,7 +55,7 @@ async fn messages_in_order() { assert!(matches!( event, message::Event::Sent(event) - if event.message.sender == sender.id + if event.message.sender == sender.login.id && event.message.body == message )); } @@ -66,7 +66,7 @@ async fn nonexistent_channel() { // Set up the environment let app = fixtures::scratch_app().await; - let login = fixtures::login::create(&app, &fixtures::now()).await; + let sender = fixtures::identity::create(&app, &fixtures::now()).await; // Call the endpoint @@ -79,11 +79,49 @@ async fn nonexistent_channel() { State(app), Path(channel.clone()), sent_at, - login, + sender, Json(request), ) .await - .expect_err("sending to a nonexistent channel"); + .expect_err("sending to a nonexistent channel fails"); + + // Verify the structure of the response + + assert!(matches!( + error, + SendError::ChannelNotFound(error_channel) if channel == error_channel + )); +} + +#[tokio::test] +async fn deleted_channel() { + // Set up the environment + + let app = fixtures::scratch_app().await; + let sender = fixtures::identity::create(&app, &fixtures::now()).await; + let channel = fixtures::channel::create(&app, &fixtures::now()).await; + + app.channels() + .delete(&channel.id, &fixtures::now()) + .await + .expect("deleting a new channel succeeds"); + + // Call the endpoint + + let sent_at = fixtures::now(); + let channel = channel::Id::generate(); + let request = post::Request { + body: fixtures::message::propose(), + }; + let post::Error(error) = post::handler( + State(app), + Path(channel.clone()), + sent_at, + sender, + Json(request), + ) + .await + .expect_err("sending to a deleted channel fails"); // Verify the structure of the response diff --git a/src/channel/routes/post.rs b/src/channel/routes/post.rs index 9781dd7..810445c 100644 --- a/src/channel/routes/post.rs +++ b/src/channel/routes/post.rs @@ -9,13 +9,13 @@ use crate::{ channel::{app, Channel}, clock::RequestedAt, error::Internal, - login::Login, name::Name, + token::extract::Identity, }; pub async fn handler( State(app): State, - _: Login, // requires auth, but doesn't actually care who you are + _: Identity, // requires auth, but doesn't actually care who you are RequestedAt(created_at): RequestedAt, Json(request): Json, ) -> Result { diff --git a/src/channel/routes/test.rs b/src/channel/routes/test.rs index 7879ba0..77f283b 100644 --- a/src/channel/routes/test.rs +++ b/src/channel/routes/test.rs @@ -14,7 +14,7 @@ async fn new_channel() { // Set up the environment let app = fixtures::scratch_app().await; - let creator = fixtures::login::create(&app, &fixtures::now()).await; + let creator = fixtures::identity::create(&app, &fixtures::now()).await; // Call the endpoint @@ -65,7 +65,7 @@ async fn duplicate_name() { // Set up the environment let app = fixtures::scratch_app().await; - let creator = fixtures::login::create(&app, &fixtures::now()).await; + let creator = fixtures::identity::create(&app, &fixtures::now()).await; let channel = fixtures::channel::create(&app, &fixtures::now()).await; // Call the endpoint @@ -91,7 +91,7 @@ async fn name_reusable_after_delete() { // Set up the environment let app = fixtures::scratch_app().await; - let creator = fixtures::login::create(&app, &fixtures::now()).await; + let creator = fixtures::identity::create(&app, &fixtures::now()).await; let name = fixtures::channel::propose(); // Call the endpoint (first time) diff --git a/src/event/routes/test.rs b/src/event/routes/test.rs index e6a8b9d..49f8094 100644 --- a/src/event/routes/test.rs +++ b/src/event/routes/test.rs @@ -22,8 +22,7 @@ async fn includes_historical_message() { // Call the endpoint - let subscriber_creds = fixtures::login::create_with_password(&app, &fixtures::now()).await; - let subscriber = fixtures::identity::identity(&app, &subscriber_creds, &fixtures::now()).await; + let subscriber = fixtures::identity::create(&app, &fixtures::now()).await; let get::Response(events) = get::handler(State(app), subscriber, None, Query::default()) .await .expect("subscribe never fails"); @@ -49,8 +48,7 @@ async fn includes_live_message() { // Call the endpoint - let subscriber_creds = fixtures::login::create_with_password(&app, &fixtures::now()).await; - let subscriber = fixtures::identity::identity(&app, &subscriber_creds, &fixtures::now()).await; + let subscriber = fixtures::identity::create(&app, &fixtures::now()).await; let get::Response(events) = get::handler(State(app.clone()), subscriber, None, Query::default()) .await @@ -95,8 +93,7 @@ async fn includes_multiple_channels() { // Call the endpoint - let subscriber_creds = fixtures::login::create_with_password(&app, &fixtures::now()).await; - let subscriber = fixtures::identity::identity(&app, &subscriber_creds, &fixtures::now()).await; + let subscriber = fixtures::identity::create(&app, &fixtures::now()).await; let get::Response(events) = get::handler(State(app), subscriber, None, Query::default()) .await .expect("subscribe never fails"); @@ -133,8 +130,7 @@ async fn sequential_messages() { // Call the endpoint - let subscriber_creds = fixtures::login::create_with_password(&app, &fixtures::now()).await; - let subscriber = fixtures::identity::identity(&app, &subscriber_creds, &fixtures::now()).await; + let subscriber = fixtures::identity::create(&app, &fixtures::now()).await; let get::Response(events) = get::handler(State(app), subscriber, None, Query::default()) .await .expect("subscribe never fails"); @@ -180,8 +176,7 @@ async fn resumes_from() { // Call the endpoint - let subscriber_creds = fixtures::login::create_with_password(&app, &fixtures::now()).await; - let subscriber = fixtures::identity::identity(&app, &subscriber_creds, &fixtures::now()).await; + let subscriber = fixtures::identity::create(&app, &fixtures::now()).await; let resume_at = { // First subscription @@ -258,8 +253,7 @@ async fn serial_resume() { // Call the endpoint - let subscriber_creds = fixtures::login::create_with_password(&app, &fixtures::now()).await; - let subscriber = fixtures::identity::identity(&app, &subscriber_creds, &fixtures::now()).await; + let subscriber = fixtures::identity::create(&app, &fixtures::now()).await; let resume_at = { let initial_messages = [ @@ -382,7 +376,7 @@ async fn terminates_on_token_expiry() { let subscriber_creds = fixtures::login::create_with_password(&app, &fixtures::now()).await; let subscriber = - fixtures::identity::identity(&app, &subscriber_creds, &fixtures::ancient()).await; + fixtures::identity::logged_in(&app, &subscriber_creds, &fixtures::ancient()).await; let get::Response(events) = get::handler(State(app.clone()), subscriber, None, Query::default()) @@ -426,11 +420,7 @@ async fn terminates_on_logout() { // Subscribe via the endpoint - let subscriber_creds = fixtures::login::create_with_password(&app, &fixtures::now()).await; - let subscriber_token = - fixtures::identity::logged_in(&app, &subscriber_creds, &fixtures::now()).await; - let subscriber = - fixtures::identity::from_token(&app, &subscriber_token, &fixtures::now()).await; + let subscriber = fixtures::identity::create(&app, &fixtures::now()).await; let get::Response(events) = get::handler( State(app.clone()), diff --git a/src/invite/routes/invite/post.rs b/src/invite/routes/invite/post.rs index a41207a..3ca4e6b 100644 --- a/src/invite/routes/invite/post.rs +++ b/src/invite/routes/invite/post.rs @@ -11,16 +11,16 @@ use crate::{ invite::app, login::{Login, Password}, name::Name, - token::extract::IdentityToken, + token::extract::IdentityCookie, }; pub async fn handler( State(app): State, RequestedAt(accepted_at): RequestedAt, - identity: IdentityToken, + identity: IdentityCookie, Path(invite): Path, Json(request): Json, -) -> Result<(IdentityToken, Json), Error> { +) -> Result<(IdentityCookie, Json), Error> { let (login, secret) = app .invites() .accept(&invite, &request.name, &request.password, &accepted_at) diff --git a/src/invite/routes/post.rs b/src/invite/routes/post.rs index 80b1c27..eb7d706 100644 --- a/src/invite/routes/post.rs +++ b/src/invite/routes/post.rs @@ -1,17 +1,19 @@ use axum::extract::{Json, State}; -use crate::{app::App, clock::RequestedAt, error::Internal, invite::Invite, login::Login}; +use crate::{ + app::App, clock::RequestedAt, error::Internal, invite::Invite, token::extract::Identity, +}; pub async fn handler( State(app): State, RequestedAt(issued_at): RequestedAt, - login: Login, - // Require `{}` as the only valid request for this endpoint. + identity: Identity, _: Json, ) -> Result, Internal> { - let invite = app.invites().create(&login, &issued_at).await?; + let invite = app.invites().create(&identity.login, &issued_at).await?; Ok(Json(invite)) } +// Require `{}` as the only valid request for this endpoint. #[derive(Default, serde::Deserialize)] pub struct Request {} diff --git a/src/login/extract.rs b/src/login/extract.rs deleted file mode 100644 index c2d97f2..0000000 --- a/src/login/extract.rs +++ /dev/null @@ -1,15 +0,0 @@ -use axum::{extract::FromRequestParts, http::request::Parts}; - -use super::Login; -use crate::{app::App, token::extract::Identity}; - -#[async_trait::async_trait] -impl FromRequestParts for Login { - type Rejection = >::Rejection; - - async fn from_request_parts(parts: &mut Parts, state: &App) -> Result { - let identity = Identity::from_request_parts(parts, state).await?; - - Ok(identity.login) - } -} diff --git a/src/login/mod.rs b/src/login/mod.rs index 64a3698..279e9a6 100644 --- a/src/login/mod.rs +++ b/src/login/mod.rs @@ -1,6 +1,5 @@ pub mod app; pub mod event; -pub mod extract; mod history; mod id; pub mod password; diff --git a/src/login/routes/login/post.rs b/src/login/routes/login/post.rs index 20430db..96da5c5 100644 --- a/src/login/routes/login/post.rs +++ b/src/login/routes/login/post.rs @@ -10,15 +10,15 @@ use crate::{ error::Internal, login::{Login, Password}, name::Name, - token::{app, extract::IdentityToken}, + token::{app, extract::IdentityCookie}, }; pub async fn handler( State(app): State, RequestedAt(now): RequestedAt, - identity: IdentityToken, + identity: IdentityCookie, Json(request): Json, -) -> Result<(IdentityToken, Json), Error> { +) -> Result<(IdentityCookie, Json), Error> { let (login, secret) = app .tokens() .login(&request.name, &request.password, &now) diff --git a/src/login/routes/login/test.rs b/src/login/routes/login/test.rs index c94f14c..7399796 100644 --- a/src/login/routes/login/test.rs +++ b/src/login/routes/login/test.rs @@ -8,14 +8,14 @@ async fn correct_credentials() { // Set up the environment let app = fixtures::scratch_app().await; - let (login, password) = fixtures::login::create_with_password(&app, &fixtures::now()).await; + let (name, password) = fixtures::login::create_with_password(&app, &fixtures::now()).await; // Call the endpoint - let identity = fixtures::identity::not_logged_in(); + let identity = fixtures::cookie::not_logged_in(); let logged_in_at = fixtures::now(); let request = post::Request { - name: login.name.clone(), + name: name.clone(), password, }; let (identity, Json(response)) = @@ -25,8 +25,10 @@ async fn correct_credentials() { // Verify the return value's basic structure - assert_eq!(login, response); - let secret = identity.secret().expect("logged in with valid credentials"); + assert_eq!(name, response.name); + let secret = identity + .secret() + .expect("logged in with valid credentials issues an identity cookie"); // Verify the semantics @@ -37,7 +39,7 @@ async fn correct_credentials() { .await .expect("identity secret is valid"); - assert_eq!(login, validated_login); + assert_eq!(response, validated_login); } #[tokio::test] @@ -48,7 +50,7 @@ async fn invalid_name() { // Call the endpoint - let identity = fixtures::identity::not_logged_in(); + let identity = fixtures::cookie::not_logged_in(); let logged_in_at = fixtures::now(); let (name, password) = fixtures::login::propose(); let request = post::Request { @@ -58,7 +60,7 @@ async fn invalid_name() { let post::Error(error) = post::handler(State(app.clone()), logged_in_at, identity, Json(request)) .await - .expect_err("logged in with an incorrect password"); + .expect_err("logged in with an incorrect password fails"); // Verify the return value's basic structure @@ -75,7 +77,7 @@ async fn incorrect_password() { // Call the endpoint let logged_in_at = fixtures::now(); - let identity = fixtures::identity::not_logged_in(); + let identity = fixtures::cookie::not_logged_in(); let request = post::Request { name: login.name, password: fixtures::login::propose_password(), @@ -95,16 +97,13 @@ async fn token_expires() { // Set up the environment let app = fixtures::scratch_app().await; - let (login, password) = fixtures::login::create_with_password(&app, &fixtures::now()).await; + let (name, password) = fixtures::login::create_with_password(&app, &fixtures::now()).await; // Call the endpoint let logged_in_at = fixtures::ancient(); - let identity = fixtures::identity::not_logged_in(); - let request = post::Request { - name: login.name.clone(), - password, - }; + let identity = fixtures::cookie::not_logged_in(); + let request = post::Request { name, password }; let (identity, _) = post::handler(State(app.clone()), logged_in_at, identity, Json(request)) .await .expect("logged in with valid credentials"); diff --git a/src/login/routes/logout/post.rs b/src/login/routes/logout/post.rs index 6b7a62a..bb09b9f 100644 --- a/src/login/routes/logout/post.rs +++ b/src/login/routes/logout/post.rs @@ -8,15 +8,15 @@ use crate::{ app::App, clock::RequestedAt, error::{Internal, Unauthorized}, - token::{app, extract::IdentityToken}, + token::{app, extract::IdentityCookie}, }; pub async fn handler( State(app): State, RequestedAt(now): RequestedAt, - identity: IdentityToken, + identity: IdentityCookie, Json(_): Json, -) -> Result<(IdentityToken, StatusCode), Error> { +) -> Result<(IdentityCookie, StatusCode), Error> { if let Some(secret) = identity.secret() { let (token, _) = app.tokens().validate(&secret, &now).await?; app.tokens().logout(&token).await?; diff --git a/src/login/routes/logout/test.rs b/src/login/routes/logout/test.rs index 91837fe..775fa9f 100644 --- a/src/login/routes/logout/test.rs +++ b/src/login/routes/logout/test.rs @@ -12,9 +12,9 @@ async fn successful() { let app = fixtures::scratch_app().await; let now = fixtures::now(); - let login = fixtures::login::create_with_password(&app, &fixtures::now()).await; - let identity = fixtures::identity::logged_in(&app, &login, &now).await; - let secret = fixtures::identity::secret(&identity); + let creds = fixtures::login::create_with_password(&app, &fixtures::now()).await; + let identity = fixtures::cookie::logged_in(&app, &creds, &now).await; + let secret = fixtures::cookie::secret(&identity); // Call the endpoint @@ -49,10 +49,10 @@ async fn no_identity() { // Call the endpoint - let identity = fixtures::identity::not_logged_in(); + let identity = fixtures::cookie::not_logged_in(); let (identity, status) = post::handler(State(app), fixtures::now(), identity, Json::default()) .await - .expect("logged out with no token"); + .expect("logged out with no token succeeds"); // Verify the return value's basic structure @@ -68,10 +68,10 @@ async fn invalid_token() { // Call the endpoint - let identity = fixtures::identity::fictitious(); + let identity = fixtures::cookie::fictitious(); let post::Error(error) = post::handler(State(app), fixtures::now(), identity, Json::default()) .await - .expect_err("logged out with an invalid token"); + .expect_err("logged out with an invalid token fails"); // Verify the return value's basic structure diff --git a/src/message/app.rs b/src/message/app.rs index 852b958..eed6ba4 100644 --- a/src/message/app.rs +++ b/src/message/app.rs @@ -136,8 +136,6 @@ impl From for SendError { #[derive(Debug, thiserror::Error)] pub enum DeleteError { - #[error("channel {0} not found")] - ChannelNotFound(channel::Id), #[error("message {0} not found")] NotFound(Id), #[error("message {0} deleted")] diff --git a/src/message/routes/message.rs b/src/message/routes/message.rs index fbef35a..f83cb39 100644 --- a/src/message/routes/message.rs +++ b/src/message/routes/message.rs @@ -9,15 +9,15 @@ pub mod delete { app::App, clock::RequestedAt, error::{Internal, NotFound}, - login::Login, message::{self, app::DeleteError}, + token::extract::Identity, }; pub async fn handler( State(app): State, Path(message): Path, RequestedAt(deleted_at): RequestedAt, - _: Login, + _: Identity, ) -> Result { app.messages().delete(&message, &deleted_at).await?; @@ -33,9 +33,9 @@ pub mod delete { let Self(error) = self; #[allow(clippy::match_wildcard_for_single_variants)] match error { - DeleteError::ChannelNotFound(_) - | DeleteError::NotFound(_) - | DeleteError::Deleted(_) => NotFound(error).into_response(), + DeleteError::NotFound(_) | DeleteError::Deleted(_) => { + NotFound(error).into_response() + } other => Internal::from(other).into_response(), } } diff --git a/src/setup/routes/post.rs b/src/setup/routes/post.rs index fb2280a..f7b256e 100644 --- a/src/setup/routes/post.rs +++ b/src/setup/routes/post.rs @@ -11,15 +11,15 @@ use crate::{ login::{Login, Password}, name::Name, setup::app, - token::extract::IdentityToken, + token::extract::IdentityCookie, }; pub async fn handler( State(app): State, RequestedAt(setup_at): RequestedAt, - identity: IdentityToken, + identity: IdentityCookie, Json(request): Json, -) -> Result<(IdentityToken, Json), Error> { +) -> Result<(IdentityCookie, Json), Error> { let (login, secret) = app .setup() .initial(&request.name, &request.password, &setup_at) diff --git a/src/test/fixtures/cookie.rs b/src/test/fixtures/cookie.rs new file mode 100644 index 0000000..58777c8 --- /dev/null +++ b/src/test/fixtures/cookie.rs @@ -0,0 +1,37 @@ +use uuid::Uuid; + +use crate::{ + app::App, + clock::RequestedAt, + login::Password, + name::Name, + token::{extract::IdentityCookie, Secret}, +}; + +pub fn not_logged_in() -> IdentityCookie { + IdentityCookie::new() +} + +pub async fn logged_in( + app: &App, + credentials: &(Name, Password), + now: &RequestedAt, +) -> IdentityCookie { + let (name, password) = credentials; + let (_, token) = app + .tokens() + .login(name, password, now) + .await + .expect("should succeed given known-valid credentials"); + + IdentityCookie::new().set(token) +} + +pub fn secret(identity: &IdentityCookie) -> Secret { + identity.secret().expect("identity contained a secret") +} + +pub fn fictitious() -> IdentityCookie { + let token = Uuid::new_v4().to_string(); + IdentityCookie::new().set(token) +} diff --git a/src/test/fixtures/identity.rs b/src/test/fixtures/identity.rs index c434473..e438f2b 100644 --- a/src/test/fixtures/identity.rs +++ b/src/test/fixtures/identity.rs @@ -1,31 +1,21 @@ -use uuid::Uuid; - use crate::{ app::App, clock::RequestedAt, - login::{Login, Password}, + login::Password, + name::Name, + test::fixtures, token::{ - extract::{Identity, IdentityToken}, - Secret, + self, + extract::{Identity, IdentityCookie}, }, }; -pub fn not_logged_in() -> IdentityToken { - IdentityToken::new() -} - -pub async fn logged_in(app: &App, login: &(Login, Password), now: &RequestedAt) -> IdentityToken { - let (login, password) = login; - let (_, token) = app - .tokens() - .login(&login.name, password, now) - .await - .expect("should succeed given known-valid credentials"); - - IdentityToken::new().set(token) +pub async fn create(app: &App, created_at: &RequestedAt) -> Identity { + let credentials = fixtures::login::create_with_password(app, created_at).await; + logged_in(app, &credentials, created_at).await } -pub async fn from_token(app: &App, token: &IdentityToken, issued_at: &RequestedAt) -> Identity { +pub async fn from_cookie(app: &App, token: &IdentityCookie, issued_at: &RequestedAt) -> Identity { let secret = token.secret().expect("identity token has a secret"); let (token, login) = app .tokens() @@ -36,16 +26,18 @@ pub async fn from_token(app: &App, token: &IdentityToken, issued_at: &RequestedA Identity { token, login } } -pub async fn identity(app: &App, login: &(Login, Password), issued_at: &RequestedAt) -> Identity { - let secret = logged_in(app, login, issued_at).await; - from_token(app, &secret, issued_at).await +pub async fn logged_in( + app: &App, + credentials: &(Name, Password), + issued_at: &RequestedAt, +) -> Identity { + let secret = fixtures::cookie::logged_in(app, credentials, issued_at).await; + from_cookie(app, &secret, issued_at).await } -pub fn secret(identity: &IdentityToken) -> Secret { - identity.secret().expect("identity contained a secret") -} +pub fn fictitious() -> Identity { + let token = token::Id::generate(); + let login = fixtures::login::fictitious(); -pub fn fictitious() -> IdentityToken { - let token = Uuid::new_v4().to_string(); - IdentityToken::new().set(token) + Identity { token, login } } diff --git a/src/test/fixtures/login.rs b/src/test/fixtures/login.rs index 714b936..e308289 100644 --- a/src/test/fixtures/login.rs +++ b/src/test/fixtures/login.rs @@ -8,7 +8,7 @@ use crate::{ name::Name, }; -pub async fn create_with_password(app: &App, created_at: &RequestedAt) -> (Login, Password) { +pub async fn create_with_password(app: &App, created_at: &RequestedAt) -> (Name, Password) { let (name, password) = propose(); let login = app .logins() @@ -16,7 +16,7 @@ pub async fn create_with_password(app: &App, created_at: &RequestedAt) -> (Login .await .expect("should always succeed if the login is actually new"); - (login, password) + (login.name, password) } pub async fn create(app: &App, created_at: &RequestedAt) -> Login { diff --git a/src/test/fixtures/mod.rs b/src/test/fixtures/mod.rs index 9658831..5609ebc 100644 --- a/src/test/fixtures/mod.rs +++ b/src/test/fixtures/mod.rs @@ -3,6 +3,7 @@ use chrono::{TimeDelta, Utc}; use crate::{app::App, clock::RequestedAt, db}; pub mod channel; +pub mod cookie; pub mod event; pub mod future; pub mod identity; diff --git a/src/token/extract/cookie.rs b/src/token/extract/cookie.rs new file mode 100644 index 0000000..af5787d --- /dev/null +++ b/src/token/extract/cookie.rs @@ -0,0 +1,94 @@ +use std::fmt; + +use axum::{ + extract::FromRequestParts, + http::request::Parts, + response::{IntoResponseParts, ResponseParts}, +}; +use axum_extra::extract::cookie::{Cookie, CookieJar}; + +use crate::token::Secret; + +// The usage pattern here - receive the extractor as an argument, return it in +// the response - is heavily modelled after CookieJar's own intended usage. +#[derive(Clone)] +pub struct Identity { + cookies: CookieJar, +} + +impl fmt::Debug for Identity { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("IdentityCookie") + .field("identity", &self.secret()) + .finish() + } +} + +impl Identity { + const COOKIE_NAME: &str = "identity"; + + // Creates a new, unpopulated identity token store. + #[cfg(test)] + pub fn new() -> Self { + Self { + cookies: CookieJar::new(), + } + } + + // Get the identity secret sent in the request, if any. If the identity + // was not sent, or if it has previously been [clear]ed, then this will + // return [None]. If the identity has previously been [set], then this + // will return that secret, regardless of what the request originally + // included. + pub fn secret(&self) -> Option { + self.cookies + .get(Self::COOKIE_NAME) + .map(Cookie::value) + .map(Secret::from) + } + + // Positively set the identity secret, and ensure that it will be sent + // back to the client when this extractor is included in a response. + pub fn set(self, secret: impl Into) -> Self { + let secret = secret.into().reveal(); + let identity_cookie = Cookie::build((Self::COOKIE_NAME, secret)) + .http_only(true) + .path("/") + .permanent() + .build(); + + Self { + cookies: self.cookies.add(identity_cookie), + } + } + + // Remove the identity secret and ensure that it will be cleared when this + // extractor is included in a response. + pub fn clear(self) -> Self { + Self { + cookies: self.cookies.remove(Self::COOKIE_NAME), + } + } +} + +#[async_trait::async_trait] +impl FromRequestParts for Identity +where + S: Send + Sync, +{ + type Rejection = >::Rejection; + + async fn from_request_parts(parts: &mut Parts, state: &S) -> Result { + let cookies = CookieJar::from_request_parts(parts, state).await?; + Ok(Self { cookies }) + } +} + +impl IntoResponseParts for Identity { + type Error = ::Error; + + fn into_response_parts(self, res: ResponseParts) -> Result { + let Self { cookies } = self; + cookies.into_response_parts(res) + } +} diff --git a/src/token/extract/identity.rs b/src/token/extract/identity.rs index 8b3cd94..a69f509 100644 --- a/src/token/extract/identity.rs +++ b/src/token/extract/identity.rs @@ -4,7 +4,7 @@ use axum::{ response::{IntoResponse, Response}, }; -use super::IdentityToken; +use super::IdentityCookie; use crate::{ app::App, @@ -25,10 +25,10 @@ impl FromRequestParts for Identity { type Rejection = LoginError; async fn from_request_parts(parts: &mut Parts, state: &App) -> Result { - let Ok(identity_token) = IdentityToken::from_request_parts(parts, state).await; + let Ok(cookie) = IdentityCookie::from_request_parts(parts, state).await; let RequestedAt(used_at) = RequestedAt::from_request_parts(parts, state).await?; - let secret = identity_token.secret().ok_or(LoginError::Unauthorized)?; + let secret = cookie.secret().ok_or(LoginError::Unauthorized)?; let app = State::::from_request_parts(parts, state).await?; match app.tokens().validate(&secret, &used_at).await { diff --git a/src/token/extract/identity_token.rs b/src/token/extract/identity_token.rs deleted file mode 100644 index a1e900e..0000000 --- a/src/token/extract/identity_token.rs +++ /dev/null @@ -1,94 +0,0 @@ -use std::fmt; - -use axum::{ - extract::FromRequestParts, - http::request::Parts, - response::{IntoResponseParts, ResponseParts}, -}; -use axum_extra::extract::cookie::{Cookie, CookieJar}; - -use crate::token::Secret; - -// The usage pattern here - receive the extractor as an argument, return it in -// the response - is heavily modelled after CookieJar's own intended usage. -#[derive(Clone)] -pub struct IdentityToken { - cookies: CookieJar, -} - -impl fmt::Debug for IdentityToken { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("IdentityToken") - .field("identity", &self.secret()) - .finish() - } -} - -impl IdentityToken { - // Creates a new, unpopulated identity token store. - #[cfg(test)] - pub fn new() -> Self { - Self { - cookies: CookieJar::new(), - } - } - - // Get the identity secret sent in the request, if any. If the identity - // was not sent, or if it has previously been [clear]ed, then this will - // return [None]. If the identity has previously been [set], then this - // will return that secret, regardless of what the request originally - // included. - pub fn secret(&self) -> Option { - self.cookies - .get(IDENTITY_COOKIE) - .map(Cookie::value) - .map(Secret::from) - } - - // Positively set the identity secret, and ensure that it will be sent - // back to the client when this extractor is included in a response. - pub fn set(self, secret: impl Into) -> Self { - let secret = secret.into().reveal(); - let identity_cookie = Cookie::build((IDENTITY_COOKIE, secret)) - .http_only(true) - .path("/") - .permanent() - .build(); - - Self { - cookies: self.cookies.add(identity_cookie), - } - } - - // Remove the identity secret and ensure that it will be cleared when this - // extractor is included in a response. - pub fn clear(self) -> Self { - Self { - cookies: self.cookies.remove(IDENTITY_COOKIE), - } - } -} - -const IDENTITY_COOKIE: &str = "identity"; - -#[async_trait::async_trait] -impl FromRequestParts for IdentityToken -where - S: Send + Sync, -{ - type Rejection = >::Rejection; - - async fn from_request_parts(parts: &mut Parts, state: &S) -> Result { - let cookies = CookieJar::from_request_parts(parts, state).await?; - Ok(Self { cookies }) - } -} - -impl IntoResponseParts for IdentityToken { - type Error = ::Error; - - fn into_response_parts(self, res: ResponseParts) -> Result { - let Self { cookies } = self; - cookies.into_response_parts(res) - } -} diff --git a/src/token/extract/mod.rs b/src/token/extract/mod.rs index b4800ae..fc0f52b 100644 --- a/src/token/extract/mod.rs +++ b/src/token/extract/mod.rs @@ -1,4 +1,4 @@ +mod cookie; mod identity; -mod identity_token; -pub use self::{identity::Identity, identity_token::IdentityToken}; +pub use self::{cookie::Identity as IdentityCookie, identity::Identity}; diff --git a/src/ui/routes/ch/channel.rs b/src/ui/routes/ch/channel.rs index 353d000..a338f1f 100644 --- a/src/ui/routes/ch/channel.rs +++ b/src/ui/routes/ch/channel.rs @@ -8,7 +8,7 @@ pub mod get { app::App, channel, error::Internal, - login::Login, + token::extract::Identity, ui::{ assets::{Asset, Assets}, error::NotFound, @@ -17,10 +17,10 @@ pub mod get { pub async fn handler( State(app): State, - login: Option, + identity: Option, Path(channel): Path, ) -> Result { - login.ok_or(Error::NotLoggedIn)?; + let _ = identity.ok_or(Error::NotLoggedIn)?; app.channels() .get(&channel) .await diff --git a/src/ui/routes/get.rs b/src/ui/routes/get.rs index 97737e1..2fcb51c 100644 --- a/src/ui/routes/get.rs +++ b/src/ui/routes/get.rs @@ -2,12 +2,12 @@ use axum::response::{self, IntoResponse, Redirect}; use crate::{ error::Internal, - login::Login, + token::extract::Identity, ui::assets::{Asset, Assets}, }; -pub async fn handler(login: Option) -> Result { - login.ok_or(Error::NotLoggedIn)?; +pub async fn handler(identity: Option) -> Result { + let _ = identity.ok_or(Error::NotLoggedIn)?; Assets::index().map_err(Error::Internal) } -- cgit v1.2.3 From 08a2f47bcdd774a1e52ca77dc2377c8ca5f8a5f0 Mon Sep 17 00:00:00 2001 From: Owen Jacobson Date: Wed, 23 Oct 2024 01:21:59 -0400 Subject: Channel creation tests for expiry, conflicting names --- src/channel/routes/test.rs | 98 ++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 81 insertions(+), 17 deletions(-) (limited to 'src/channel/routes/test.rs') diff --git a/src/channel/routes/test.rs b/src/channel/routes/test.rs index 77f283b..216eba1 100644 --- a/src/channel/routes/test.rs +++ b/src/channel/routes/test.rs @@ -6,6 +6,7 @@ use futures::stream::StreamExt as _; use super::post; use crate::{ channel::app, + name::Name, test::fixtures::{self, future::Immediately as _}, }; @@ -86,6 +87,39 @@ async fn duplicate_name() { )); } +#[tokio::test] +async fn conflicting_canonical_name() { + // Set up the environment + + let app = fixtures::scratch_app().await; + let creator = fixtures::identity::create(&app, &fixtures::now()).await; + + let existing_name = Name::from("rijksmuseum"); + app.channels() + .create(&existing_name, &fixtures::now()) + .await + .expect("creating a channel in an empty environment succeeds"); + + let conflicting_name = Name::from("r\u{0133}ksmuseum"); + + // Call the endpoint + + let request = post::Request { + name: conflicting_name.clone(), + }; + let post::Error(error) = + post::handler(State(app.clone()), creator, fixtures::now(), Json(request)) + .await + .expect_err("duplicate channel name should fail the request"); + + // Verify the structure of the response + + assert!(matches!( + error, + app::CreateError::DuplicateName(name) if conflicting_name == name + )); +} + #[tokio::test] async fn name_reusable_after_delete() { // Set up the environment @@ -119,7 +153,7 @@ async fn name_reusable_after_delete() { let post::Response(response) = post::handler(State(app.clone()), creator, fixtures::now(), Json(request)) .await - .expect("new channel in an empty app"); + .expect("creation succeeds after original channel deleted"); // Verify the structure of the response @@ -127,9 +161,6 @@ async fn name_reusable_after_delete() { // Verify the semantics - let snapshot = app.boot().snapshot().await.expect("boot always succeeds"); - assert!(snapshot.channels.iter().any(|channel| channel == &response)); - let channel = app .channels() .get(&response.id) @@ -137,21 +168,54 @@ async fn name_reusable_after_delete() { .expect("searching for channels by ID never fails") .expect("the newly-created channel exists"); assert_eq!(response, channel); +} - let mut events = app - .events() - .subscribe(None) - .await - .expect("subscribing never fails") - .filter_map(fixtures::channel::events) - .filter_map(fixtures::channel::created) - .filter(|event| future::ready(event.channel == response)); +#[tokio::test] +async fn name_reusable_after_expiry() { + // Set up the environment - let event = events - .next() - .immediately() + let app = fixtures::scratch_app().await; + let creator = fixtures::identity::create(&app, &fixtures::ancient()).await; + let name = fixtures::channel::propose(); + + // Call the endpoint (first time) + + let request = post::Request { name: name.clone() }; + let post::Response(_) = post::handler( + State(app.clone()), + creator.clone(), + fixtures::ancient(), + Json(request), + ) + .await + .expect("new channel in an empty app"); + + // Delete the channel + + app.channels() + .expire(&fixtures::now()) .await - .expect("creation event published"); + .expect("expiry always succeeds"); - assert_eq!(event.channel, response); + // Call the endpoint (second time) + + let request = post::Request { name: name.clone() }; + let post::Response(response) = + post::handler(State(app.clone()), creator, fixtures::now(), Json(request)) + .await + .expect("creation succeeds after original channel expired"); + + // Verify the structure of the response + + assert_eq!(name, response.name); + + // Verify the semantics + + let channel = app + .channels() + .get(&response.id) + .await + .expect("searching for channels by ID never fails") + .expect("the newly-created channel exists"); + assert_eq!(response, channel); } -- cgit v1.2.3