diff options
178 files changed, 5018 insertions, 2318 deletions
diff --git a/.sqlx/query-023b1e263b68a483704ae5f6b07e69ab792b7365f2eb2831f7a2ac13e2ecf323.json b/.sqlx/query-023b1e263b68a483704ae5f6b07e69ab792b7365f2eb2831f7a2ac13e2ecf323.json deleted file mode 100644 index cc23359..0000000 --- a/.sqlx/query-023b1e263b68a483704ae5f6b07e69ab792b7365f2eb2831f7a2ac13e2ecf323.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "db_name": "SQLite", - "query": "\n insert\n into channel (id, name, created_at, created_sequence)\n values ($1, $2, $3, $4)\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": 4 - }, - "nullable": [ - false, - false, - false, - false - ] - }, - "hash": "023b1e263b68a483704ae5f6b07e69ab792b7365f2eb2831f7a2ac13e2ecf323" -} diff --git a/.sqlx/query-836a37fa3fbcacbc880c7c9e603b3087a17906db95d14a35034889a253f23418.json b/.sqlx/query-0f0e4a6ac32b39f3bd7f4832389259b91bbffa182e32b224635031eead2fa82d.json index 2ac20b6..fd5a165 100644 --- a/.sqlx/query-836a37fa3fbcacbc880c7c9e603b3087a17906db95d14a35034889a253f23418.json +++ b/.sqlx/query-0f0e4a6ac32b39f3bd7f4832389259b91bbffa182e32b224635031eead2fa82d.json @@ -1,6 +1,6 @@ { "db_name": "SQLite", - "query": "\n\t\t\t\tinsert into message\n\t\t\t\t\t(id, channel, sender, sent_at, sent_sequence, body)\n\t\t\t\tvalues ($1, $2, $3, $4, $5, $6)\n\t\t\t\treturning\n\t\t\t\t\tid as \"id: Id\",\n channel as \"channel: channel::Id\",\n sender as \"sender: login::Id\",\n sent_at as \"sent_at: DateTime\",\n sent_sequence as \"sent_sequence: Sequence\",\n\t\t\t\t\tbody\n\t\t\t", + "query": "\n insert into message\n (id, channel, sender, sent_at, sent_sequence, body)\n values ($1, $2, $3, $4, $5, $6)\n returning\n id as \"id: Id\",\n channel as \"channel: channel::Id\",\n sender as \"sender: login::Id\",\n sent_at as \"sent_at: DateTime\",\n sent_sequence as \"sent_sequence: Sequence\",\n body as \"body: Body\"\n ", "describe": { "columns": [ { @@ -29,7 +29,7 @@ "type_info": "Integer" }, { - "name": "body", + "name": "body: Body", "ordinal": 5, "type_info": "Text" } @@ -43,8 +43,8 @@ false, false, false, - false + true ] }, - "hash": "836a37fa3fbcacbc880c7c9e603b3087a17906db95d14a35034889a253f23418" + "hash": "0f0e4a6ac32b39f3bd7f4832389259b91bbffa182e32b224635031eead2fa82d" } 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-693b6758b8e8a21f8e8017573526a2ef050389298851a2c0da9adec7d05fc862.json b/.sqlx/query-1946af14f5d3da9af51fc0e3d4f25cff1556aec7083bc484172c58cbd655a316.json index c0791f7..f765fda 100644 --- a/.sqlx/query-693b6758b8e8a21f8e8017573526a2ef050389298851a2c0da9adec7d05fc862.json +++ b/.sqlx/query-1946af14f5d3da9af51fc0e3d4f25cff1556aec7083bc484172c58cbd655a316.json @@ -1,6 +1,6 @@ { "db_name": "SQLite", - "query": "\n\t\t\t\tinsert into invite (id, issuer, issued_at)\n\t\t\t\tvalues ($1, $2, $3)\n\t\t\t\treturning\n\t\t\t\t\tid as \"id: Id\",\n\t\t\t\t\tissuer as \"issuer: login::Id\",\n\t\t\t\t\tissued_at as \"issued_at: DateTime\"\n\t\t\t", + "query": "\n insert into invite (id, issuer, issued_at)\n values ($1, $2, $3)\n returning\n id as \"id: Id\",\n issuer as \"issuer: login::Id\",\n issued_at as \"issued_at: DateTime\"\n ", "describe": { "columns": [ { @@ -28,5 +28,5 @@ false ] }, - "hash": "693b6758b8e8a21f8e8017573526a2ef050389298851a2c0da9adec7d05fc862" + "hash": "1946af14f5d3da9af51fc0e3d4f25cff1556aec7083bc484172c58cbd655a316" } diff --git a/.sqlx/query-24bc0257eff3357322481e1314f70d13e8b0ca22b7652f1063ec7796cf307269.json b/.sqlx/query-24bc0257eff3357322481e1314f70d13e8b0ca22b7652f1063ec7796cf307269.json new file mode 100644 index 0000000..9f09a28 --- /dev/null +++ b/.sqlx/query-24bc0257eff3357322481e1314f70d13e8b0ca22b7652f1063ec7796cf307269.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 as \"body: 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: 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, + true, + true, + true + ] + }, + "hash": "24bc0257eff3357322481e1314f70d13e8b0ca22b7652f1063ec7796cf307269" +} diff --git a/.sqlx/query-2773f12ef58c251596dd00f0bd048975fb06f090a11622cc74ced47a3d7ad44a.json b/.sqlx/query-2773f12ef58c251596dd00f0bd048975fb06f090a11622cc74ced47a3d7ad44a.json new file mode 100644 index 0000000..2de9614 --- /dev/null +++ b/.sqlx/query-2773f12ef58c251596dd00f0bd048975fb06f090a11622cc74ced47a3d7ad44a.json @@ -0,0 +1,12 @@ +{ + "db_name": "SQLite", + "query": "\n insert into channel_deleted (id, deleted_at, deleted_sequence)\n values ($1, $2, $3)\n ", + "describe": { + "columns": [], + "parameters": { + "Right": 3 + }, + "nullable": [] + }, + "hash": "2773f12ef58c251596dd00f0bd048975fb06f090a11622cc74ced47a3d7ad44a" +} diff --git a/.sqlx/query-2e0aa3126267465ee1ae01e6856eff74a544f0a1c3692766e48a3182df5ada98.json b/.sqlx/query-2e0aa3126267465ee1ae01e6856eff74a544f0a1c3692766e48a3182df5ada98.json new file mode 100644 index 0000000..227d242 --- /dev/null +++ b/.sqlx/query-2e0aa3126267465ee1ae01e6856eff74a544f0a1c3692766e48a3182df5ada98.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 as \"body: 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: 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, + true, + false, + false + ] + }, + "hash": "2e0aa3126267465ee1ae01e6856eff74a544f0a1c3692766e48a3182df5ada98" +} diff --git a/.sqlx/query-2f26bccedd1226764e49f00a94e43226ee6aebdd14d7be97a708d66263a30abf.json b/.sqlx/query-2f26bccedd1226764e49f00a94e43226ee6aebdd14d7be97a708d66263a30abf.json new file mode 100644 index 0000000..686afb9 --- /dev/null +++ b/.sqlx/query-2f26bccedd1226764e49f00a94e43226ee6aebdd14d7be97a708d66263a30abf.json @@ -0,0 +1,12 @@ +{ + "db_name": "SQLite", + "query": "\n insert into message_deleted (id, deleted_at, deleted_sequence)\n values ($1, $2, $3)\n ", + "describe": { + "columns": [], + "parameters": { + "Right": 3 + }, + "nullable": [] + }, + "hash": "2f26bccedd1226764e49f00a94e43226ee6aebdd14d7be97a708d66263a30abf" +} diff --git a/.sqlx/query-31e741181f0d09540063ef29117e7e70d3df2beaa1b1e2e081b0d362c07ceae8.json b/.sqlx/query-31e741181f0d09540063ef29117e7e70d3df2beaa1b1e2e081b0d362c07ceae8.json new file mode 100644 index 0000000..1105391 --- /dev/null +++ b/.sqlx/query-31e741181f0d09540063ef29117e7e70d3df2beaa1b1e2e081b0d362c07ceae8.json @@ -0,0 +1,12 @@ +{ + "db_name": "SQLite", + "query": "\n update channel_name\n set canonical_name = $1\n where id = $2\n ", + "describe": { + "columns": [], + "parameters": { + "Right": 2 + }, + "nullable": [] + }, + "hash": "31e741181f0d09540063ef29117e7e70d3df2beaa1b1e2e081b0d362c07ceae8" +} 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-3fbec32aeb32c49e088f246c00151035dcf174cec137326b63e0cb0e4ae5cb60.json b/.sqlx/query-3fbec32aeb32c49e088f246c00151035dcf174cec137326b63e0cb0e4ae5cb60.json deleted file mode 100644 index 01e72b2..0000000 --- a/.sqlx/query-3fbec32aeb32c49e088f246c00151035dcf174cec137326b63e0cb0e4ae5cb60.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "db_name": "SQLite", - "query": "\n insert\n into login (id, name, password_hash, created_sequence, created_at)\n values ($1, $2, $3, $4, $5)\n returning\n id as \"id: Id\",\n name,\n created_sequence as \"created_sequence: Sequence\",\n created_at as \"created_at: DateTime\"\n ", - "describe": { - "columns": [ - { - "name": "id: Id", - "ordinal": 0, - "type_info": "Text" - }, - { - "name": "name", - "ordinal": 1, - "type_info": "Text" - }, - { - "name": "created_sequence: Sequence", - "ordinal": 2, - "type_info": "Integer" - }, - { - "name": "created_at: DateTime", - "ordinal": 3, - "type_info": "Text" - } - ], - "parameters": { - "Right": 5 - }, - "nullable": [ - false, - false, - false, - false - ] - }, - "hash": "3fbec32aeb32c49e088f246c00151035dcf174cec137326b63e0cb0e4ae5cb60" -} diff --git a/.sqlx/query-4224d5c1c4009e0d31b96bc7b1d9f6a2215c7c135720c1222170a1f6692c3a8a.json b/.sqlx/query-4224d5c1c4009e0d31b96bc7b1d9f6a2215c7c135720c1222170a1f6692c3a8a.json deleted file mode 100644 index 767c217..0000000 --- a/.sqlx/query-4224d5c1c4009e0d31b96bc7b1d9f6a2215c7c135720c1222170a1f6692c3a8a.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "db_name": "SQLite", - "query": "\n select\n id as \"id: Id\",\n name,\n created_sequence as \"created_sequence: Sequence\",\n created_at as \"created_at: DateTime\"\n from login\n where coalesce(login.created_sequence > $1, true)\n ", - "describe": { - "columns": [ - { - "name": "id: Id", - "ordinal": 0, - "type_info": "Text" - }, - { - "name": "name", - "ordinal": 1, - "type_info": "Text" - }, - { - "name": "created_sequence: Sequence", - "ordinal": 2, - "type_info": "Integer" - }, - { - "name": "created_at: DateTime", - "ordinal": 3, - "type_info": "Text" - } - ], - "parameters": { - "Right": 1 - }, - "nullable": [ - false, - false, - false, - false - ] - }, - "hash": "4224d5c1c4009e0d31b96bc7b1d9f6a2215c7c135720c1222170a1f6692c3a8a" -} diff --git a/.sqlx/query-454ca70caa83eee2dac585cf421524e41055cddf76dd4e4016142f61e0a4903f.json b/.sqlx/query-454ca70caa83eee2dac585cf421524e41055cddf76dd4e4016142f61e0a4903f.json new file mode 100644 index 0000000..ebddeb8 --- /dev/null +++ b/.sqlx/query-454ca70caa83eee2dac585cf421524e41055cddf76dd4e4016142f61e0a4903f.json @@ -0,0 +1,12 @@ +{ + "db_name": "SQLite", + "query": "\n delete from channel_name\n where id = $1\n ", + "describe": { + "columns": [], + "parameters": { + "Right": 1 + }, + "nullable": [] + }, + "hash": "454ca70caa83eee2dac585cf421524e41055cddf76dd4e4016142f61e0a4903f" +} diff --git a/.sqlx/query-4623f989492e9eae6788ee9472f1138395b50cdfc9a28e9791e5484890f0201b.json b/.sqlx/query-4623f989492e9eae6788ee9472f1138395b50cdfc9a28e9791e5484890f0201b.json new file mode 100644 index 0000000..bfab6d4 --- /dev/null +++ b/.sqlx/query-4623f989492e9eae6788ee9472f1138395b50cdfc9a28e9791e5484890f0201b.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 as \"body: 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: 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, + true, + false, + false, + false, + false + ] + }, + "hash": "4623f989492e9eae6788ee9472f1138395b50cdfc9a28e9791e5484890f0201b" +} 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-4c27c8f7ed9b6315433dc2b5f787a61d82693fe0426b46f9971fcde5e44f38b0.json b/.sqlx/query-4c27c8f7ed9b6315433dc2b5f787a61d82693fe0426b46f9971fcde5e44f38b0.json new file mode 100644 index 0000000..8962098 --- /dev/null +++ b/.sqlx/query-4c27c8f7ed9b6315433dc2b5f787a61d82693fe0426b46f9971fcde5e44f38b0.json @@ -0,0 +1,12 @@ +{ + "db_name": "SQLite", + "query": "\n insert into channel_name (id, display_name, canonical_name)\n values ($1, $2, $3)\n ", + "describe": { + "columns": [], + "parameters": { + "Right": 3 + }, + "nullable": [] + }, + "hash": "4c27c8f7ed9b6315433dc2b5f787a61d82693fe0426b46f9971fcde5e44f38b0" +} diff --git a/.sqlx/query-558491955176ee2f12d80ce11deb37b5fea52bc9ac224957eb4f892aeaf84eaa.json b/.sqlx/query-558491955176ee2f12d80ce11deb37b5fea52bc9ac224957eb4f892aeaf84eaa.json new file mode 100644 index 0000000..5f21bf5 --- /dev/null +++ b/.sqlx/query-558491955176ee2f12d80ce11deb37b5fea52bc9ac224957eb4f892aeaf84eaa.json @@ -0,0 +1,12 @@ +{ + "db_name": "SQLite", + "query": "\n delete from invite\n where issued_at < $1\n ", + "describe": { + "columns": [], + "parameters": { + "Right": 1 + }, + "nullable": [] + }, + "hash": "558491955176ee2f12d80ce11deb37b5fea52bc9ac224957eb4f892aeaf84eaa" +} diff --git a/.sqlx/query-584aea21a5ceb0ce6e48bc224bfc431f2e517755983f3510565e18ecb0e6e637.json b/.sqlx/query-584aea21a5ceb0ce6e48bc224bfc431f2e517755983f3510565e18ecb0e6e637.json new file mode 100644 index 0000000..f443d9a --- /dev/null +++ b/.sqlx/query-584aea21a5ceb0ce6e48bc224bfc431f2e517755983f3510565e18ecb0e6e637.json @@ -0,0 +1,38 @@ +{ + "db_name": "SQLite", + "query": "\n select\n invite.id as \"invite_id: Id\",\n issuer.id as \"issuer_id: login::Id\",\n issuer.display_name as \"issuer_name: nfc::String\",\n invite.issued_at as \"invite_issued_at: DateTime\"\n from invite\n join login as issuer on (invite.issuer = issuer.id)\n where invite.id = $1\n ", + "describe": { + "columns": [ + { + "name": "invite_id: Id", + "ordinal": 0, + "type_info": "Text" + }, + { + "name": "issuer_id: login::Id", + "ordinal": 1, + "type_info": "Text" + }, + { + "name": "issuer_name: nfc::String", + "ordinal": 2, + "type_info": "Text" + }, + { + "name": "invite_issued_at: DateTime", + "ordinal": 3, + "type_info": "Text" + } + ], + "parameters": { + "Right": 1 + }, + "nullable": [ + false, + false, + false, + false + ] + }, + "hash": "584aea21a5ceb0ce6e48bc224bfc431f2e517755983f3510565e18ecb0e6e637" +} diff --git a/.sqlx/query-642fb12657410a4bee58d316293ea1bcc4913987ee751951e9d2f31bf495f305.json b/.sqlx/query-642fb12657410a4bee58d316293ea1bcc4913987ee751951e9d2f31bf495f305.json new file mode 100644 index 0000000..5442790 --- /dev/null +++ b/.sqlx/query-642fb12657410a4bee58d316293ea1bcc4913987ee751951e9d2f31bf495f305.json @@ -0,0 +1,26 @@ +{ + "db_name": "SQLite", + "query": "\n select\n id as \"id: Id\",\n display_name as \"display_name: String\"\n from channel_name\n ", + "describe": { + "columns": [ + { + "name": "id: Id", + "ordinal": 0, + "type_info": "Text" + }, + { + "name": "display_name: String", + "ordinal": 1, + "type_info": "Text" + } + ], + "parameters": { + "Right": 0 + }, + "nullable": [ + false, + false + ] + }, + "hash": "642fb12657410a4bee58d316293ea1bcc4913987ee751951e9d2f31bf495f305" +} diff --git a/.sqlx/query-d704486ba77fb40e4dd40ff96acc7783f88618a18797958d558ef6687dc29750.json b/.sqlx/query-659c2537dfa447799709d06f2da65c19b0ec4f1eac4d81756b0c9368b54fc24c.json index 2004e8f..232a15e 100644 --- a/.sqlx/query-d704486ba77fb40e4dd40ff96acc7783f88618a18797958d558ef6687dc29750.json +++ b/.sqlx/query-659c2537dfa447799709d06f2da65c19b0ec4f1eac4d81756b0c9368b54fc24c.json @@ -1,6 +1,6 @@ { "db_name": "SQLite", - "query": "\n\t\t\t\tdelete from invite\n\t\t\t\twhere id = $1\n\t\t\t\treturning 1 as \"deleted: bool\"\n\t\t\t", + "query": "\n delete from invite\n where id = $1\n returning 1 as \"deleted: bool\"\n ", "describe": { "columns": [ { @@ -16,5 +16,5 @@ null ] }, - "hash": "d704486ba77fb40e4dd40ff96acc7783f88618a18797958d558ef6687dc29750" + "hash": "659c2537dfa447799709d06f2da65c19b0ec4f1eac4d81756b0c9368b54fc24c" } diff --git a/.sqlx/query-676a7dda6314cae4d13ff51241dc35263ccfee9f3424111e7fa6014071f98a1e.json b/.sqlx/query-676a7dda6314cae4d13ff51241dc35263ccfee9f3424111e7fa6014071f98a1e.json new file mode 100644 index 0000000..fd601e9 --- /dev/null +++ b/.sqlx/query-676a7dda6314cae4d13ff51241dc35263ccfee9f3424111e7fa6014071f98a1e.json @@ -0,0 +1,26 @@ +{ + "db_name": "SQLite", + "query": "\n select\n id as \"id: Id\",\n display_name as \"display_name: String\"\n from login\n ", + "describe": { + "columns": [ + { + "name": "id: Id", + "ordinal": 0, + "type_info": "Text" + }, + { + "name": "display_name: String", + "ordinal": 1, + "type_info": "Text" + } + ], + "parameters": { + "Right": 0 + }, + "nullable": [ + false, + false + ] + }, + "hash": "676a7dda6314cae4d13ff51241dc35263ccfee9f3424111e7fa6014071f98a1e" +} diff --git a/.sqlx/query-6d34d8232e7247155c697f7ef7a26f6b14e1d30c3fb44ece8fb149c92317fa91.json b/.sqlx/query-6d34d8232e7247155c697f7ef7a26f6b14e1d30c3fb44ece8fb149c92317fa91.json new file mode 100644 index 0000000..93a4093 --- /dev/null +++ b/.sqlx/query-6d34d8232e7247155c697f7ef7a26f6b14e1d30c3fb44ece8fb149c92317fa91.json @@ -0,0 +1,26 @@ +{ + "db_name": "SQLite", + "query": "\n update token\n set last_used_at = $1\n where secret = $2\n returning\n id as \"token: Id\",\n login as \"login: login::Id\"\n ", + "describe": { + "columns": [ + { + "name": "token: Id", + "ordinal": 0, + "type_info": "Text" + }, + { + "name": "login: login::Id", + "ordinal": 1, + "type_info": "Text" + } + ], + "parameters": { + "Right": 2 + }, + "nullable": [ + false, + false + ] + }, + "hash": "6d34d8232e7247155c697f7ef7a26f6b14e1d30c3fb44ece8fb149c92317fa91" +} diff --git a/.sqlx/query-736bf4e90f23163d7d3a551d5a848b53bc8febe8d4417b5162f8ca330daac885.json b/.sqlx/query-736bf4e90f23163d7d3a551d5a848b53bc8febe8d4417b5162f8ca330daac885.json deleted file mode 100644 index f7c0552..0000000 --- a/.sqlx/query-736bf4e90f23163d7d3a551d5a848b53bc8febe8d4417b5162f8ca330daac885.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "db_name": "SQLite", - "query": "\n\t\t\t\tdelete from invite\n\t\t\t\twhere issued_at < $1\n\t\t\t", - "describe": { - "columns": [], - "parameters": { - "Right": 1 - }, - "nullable": [] - }, - "hash": "736bf4e90f23163d7d3a551d5a848b53bc8febe8d4417b5162f8ca330daac885" -} diff --git a/.sqlx/query-78d24fa907f3dcc0c129880e83b4ef41bad03b57937a27f98aebbef5268ef5f5.json b/.sqlx/query-78d24fa907f3dcc0c129880e83b4ef41bad03b57937a27f98aebbef5268ef5f5.json new file mode 100644 index 0000000..09440ca --- /dev/null +++ b/.sqlx/query-78d24fa907f3dcc0c129880e83b4ef41bad03b57937a27f98aebbef5268ef5f5.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 as \"body: 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: 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, + true, + false, + false, + false, + false + ] + }, + "hash": "78d24fa907f3dcc0c129880e83b4ef41bad03b57937a27f98aebbef5268ef5f5" +} 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-873b8b58360d717ea2099272b013b1ac76a28471e63d0492132b9c12c63a1f9c.json b/.sqlx/query-873b8b58360d717ea2099272b013b1ac76a28471e63d0492132b9c12c63a1f9c.json deleted file mode 100644 index edd3825..0000000 --- a/.sqlx/query-873b8b58360d717ea2099272b013b1ac76a28471e63d0492132b9c12c63a1f9c.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "db_name": "SQLite", - "query": "\n update token\n set last_used_at = $1\n where secret = $2\n ", - "describe": { - "columns": [], - "parameters": { - "Right": 2 - }, - "nullable": [] - }, - "hash": "873b8b58360d717ea2099272b013b1ac76a28471e63d0492132b9c12c63a1f9c" -} diff --git a/.sqlx/query-903e7ec4fafd5ce124a0e40717bf42e5d43b041acb198710e75417ac40991ec6.json b/.sqlx/query-903e7ec4fafd5ce124a0e40717bf42e5d43b041acb198710e75417ac40991ec6.json new file mode 100644 index 0000000..cf1afec --- /dev/null +++ b/.sqlx/query-903e7ec4fafd5ce124a0e40717bf42e5d43b041acb198710e75417ac40991ec6.json @@ -0,0 +1,50 @@ +{ + "db_name": "SQLite", + "query": "\n select\n id as \"id: login::Id\",\n display_name as \"display_name: String\",\n canonical_name as \"canonical_name: String\",\n created_sequence as \"created_sequence: Sequence\",\n created_at as \"created_at: DateTime\",\n password_hash as \"password_hash: StoredHash\"\n from login\n where canonical_name = $1\n ", + "describe": { + "columns": [ + { + "name": "id: login::Id", + "ordinal": 0, + "type_info": "Text" + }, + { + "name": "display_name: String", + "ordinal": 1, + "type_info": "Text" + }, + { + "name": "canonical_name: String", + "ordinal": 2, + "type_info": "Text" + }, + { + "name": "created_sequence: Sequence", + "ordinal": 3, + "type_info": "Integer" + }, + { + "name": "created_at: DateTime", + "ordinal": 4, + "type_info": "Text" + }, + { + "name": "password_hash: StoredHash", + "ordinal": 5, + "type_info": "Text" + } + ], + "parameters": { + "Right": 1 + }, + "nullable": [ + false, + false, + false, + false, + false, + false + ] + }, + "hash": "903e7ec4fafd5ce124a0e40717bf42e5d43b041acb198710e75417ac40991ec6" +} diff --git a/.sqlx/query-9f611a3351f22ed16d67d41602b8befafe751e9caeb0d5f279731e04c6925f46.json b/.sqlx/query-9f611a3351f22ed16d67d41602b8befafe751e9caeb0d5f279731e04c6925f46.json new file mode 100644 index 0000000..2d1f49e --- /dev/null +++ b/.sqlx/query-9f611a3351f22ed16d67d41602b8befafe751e9caeb0d5f279731e04c6925f46.json @@ -0,0 +1,44 @@ +{ + "db_name": "SQLite", + "query": "\n select\n id as \"id: Id\",\n display_name as \"display_name: String\",\n canonical_name as \"canonical_name: String\",\n created_sequence as \"created_sequence: Sequence\",\n created_at as \"created_at: DateTime\"\n from login\n where coalesce(created_sequence <= $1, true)\n order by canonical_name\n ", + "describe": { + "columns": [ + { + "name": "id: Id", + "ordinal": 0, + "type_info": "Text" + }, + { + "name": "display_name: String", + "ordinal": 1, + "type_info": "Text" + }, + { + "name": "canonical_name: String", + "ordinal": 2, + "type_info": "Text" + }, + { + "name": "created_sequence: Sequence", + "ordinal": 3, + "type_info": "Integer" + }, + { + "name": "created_at: DateTime", + "ordinal": 4, + "type_info": "Text" + } + ], + "parameters": { + "Right": 1 + }, + "nullable": [ + false, + false, + false, + false, + false + ] + }, + "hash": "9f611a3351f22ed16d67d41602b8befafe751e9caeb0d5f279731e04c6925f46" +} 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-a40496319887752f5845c0c2e965e2294c1a6932d72a8b04d258d06d0f8938bd.json b/.sqlx/query-a40496319887752f5845c0c2e965e2294c1a6932d72a8b04d258d06d0f8938bd.json new file mode 100644 index 0000000..647e5ad --- /dev/null +++ b/.sqlx/query-a40496319887752f5845c0c2e965e2294c1a6932d72a8b04d258d06d0f8938bd.json @@ -0,0 +1,56 @@ +{ + "db_name": "SQLite", + "query": "\n select\n id as \"id: Id\",\n name.display_name as \"display_name: String\",\n name.canonical_name as \"canonical_name: String\",\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_name as name\n using (id)\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": "display_name: String", + "ordinal": 1, + "type_info": "Text" + }, + { + "name": "canonical_name: String", + "ordinal": 2, + "type_info": "Text" + }, + { + "name": "created_at: DateTime", + "ordinal": 3, + "type_info": "Text" + }, + { + "name": "created_sequence: Sequence", + "ordinal": 4, + "type_info": "Integer" + }, + { + "name": "deleted_at?: DateTime", + "ordinal": 5, + "type_info": "Text" + }, + { + "name": "deleted_sequence?: Sequence", + "ordinal": 6, + "type_info": "Integer" + } + ], + "parameters": { + "Right": 1 + }, + "nullable": [ + false, + true, + true, + false, + false, + true, + true + ] + }, + "hash": "a40496319887752f5845c0c2e965e2294c1a6932d72a8b04d258d06d0f8938bd" +} diff --git a/.sqlx/query-a4b34593fdf71bb911beb850cfa88adb346b1770e32785166bd43cb853143a7f.json b/.sqlx/query-a4b34593fdf71bb911beb850cfa88adb346b1770e32785166bd43cb853143a7f.json new file mode 100644 index 0000000..e886759 --- /dev/null +++ b/.sqlx/query-a4b34593fdf71bb911beb850cfa88adb346b1770e32785166bd43cb853143a7f.json @@ -0,0 +1,56 @@ +{ + "db_name": "SQLite", + "query": "\n select\n channel.id as \"id: Id\",\n name.display_name as \"display_name?: String\",\n name.canonical_name as \"canonical_name?: String\",\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_name as name\n using (id)\n left join channel_deleted as deleted\n using (id)\n left join message\n on channel.id = message.channel\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": "display_name?: String", + "ordinal": 1, + "type_info": "Null" + }, + { + "name": "canonical_name?: String", + "ordinal": 2, + "type_info": "Null" + }, + { + "name": "created_at: DateTime", + "ordinal": 3, + "type_info": "Text" + }, + { + "name": "created_sequence: Sequence", + "ordinal": 4, + "type_info": "Integer" + }, + { + "name": "deleted_at?: DateTime", + "ordinal": 5, + "type_info": "Text" + }, + { + "name": "deleted_sequence?: Sequence", + "ordinal": 6, + "type_info": "Integer" + } + ], + "parameters": { + "Right": 1 + }, + "nullable": [ + false, + false, + false, + false, + false, + false, + false + ] + }, + "hash": "a4b34593fdf71bb911beb850cfa88adb346b1770e32785166bd43cb853143a7f" +} diff --git a/.sqlx/query-9386cdaa2cb41f5a7e19d2fc8c187294a4661c18c2d820f4379dfd82138a8f77.json b/.sqlx/query-ac7ab464e44e4412cd83744730699683e63ae1ea404418a17c6af60148f03fe8.json index e9c3967..7d9bbbc 100644 --- a/.sqlx/query-9386cdaa2cb41f5a7e19d2fc8c187294a4661c18c2d820f4379dfd82138a8f77.json +++ b/.sqlx/query-ac7ab464e44e4412cd83744730699683e63ae1ea404418a17c6af60148f03fe8.json @@ -1,6 +1,6 @@ { "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 ", + "query": "\n select\n id as \"id: Id\",\n display_name as \"display_name: String\",\n canonical_name as \"canonical_name: String\",\n created_sequence as \"created_sequence: Sequence\",\n created_at as \"created_at: DateTime\"\n from login\n where coalesce(login.created_sequence > $1, true)\n ", "describe": { "columns": [ { @@ -9,12 +9,12 @@ "type_info": "Text" }, { - "name": "name", + "name": "display_name: String", "ordinal": 1, "type_info": "Text" }, { - "name": "created_at: DateTime", + "name": "canonical_name: String", "ordinal": 2, "type_info": "Text" }, @@ -22,6 +22,11 @@ "name": "created_sequence: Sequence", "ordinal": 3, "type_info": "Integer" + }, + { + "name": "created_at: DateTime", + "ordinal": 4, + "type_info": "Text" } ], "parameters": { @@ -31,8 +36,9 @@ false, false, false, + false, false ] }, - "hash": "9386cdaa2cb41f5a7e19d2fc8c187294a4661c18c2d820f4379dfd82138a8f77" + "hash": "ac7ab464e44e4412cd83744730699683e63ae1ea404418a17c6af60148f03fe8" } diff --git a/.sqlx/query-ad1485f0a5514bcfaf68477723ae0f13e93a1f18213e208d3a181936a36da5fb.json b/.sqlx/query-ad1485f0a5514bcfaf68477723ae0f13e93a1f18213e208d3a181936a36da5fb.json new file mode 100644 index 0000000..ce757ba --- /dev/null +++ b/.sqlx/query-ad1485f0a5514bcfaf68477723ae0f13e93a1f18213e208d3a181936a36da5fb.json @@ -0,0 +1,56 @@ +{ + "db_name": "SQLite", + "query": "\n select\n id as \"id: Id\",\n name.display_name as \"display_name?: String\",\n name.canonical_name as \"canonical_name?: String\",\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_name as name\n using (id)\n left join channel_deleted as deleted\n using (id)\n where channel.created_sequence <= $1\n order by name.canonical_name\n ", + "describe": { + "columns": [ + { + "name": "id: Id", + "ordinal": 0, + "type_info": "Text" + }, + { + "name": "display_name?: String", + "ordinal": 1, + "type_info": "Null" + }, + { + "name": "canonical_name?: String", + "ordinal": 2, + "type_info": "Null" + }, + { + "name": "created_at: DateTime", + "ordinal": 3, + "type_info": "Text" + }, + { + "name": "created_sequence: Sequence", + "ordinal": 4, + "type_info": "Integer" + }, + { + "name": "deleted_at?: DateTime", + "ordinal": 5, + "type_info": "Text" + }, + { + "name": "deleted_sequence?: Sequence", + "ordinal": 6, + "type_info": "Integer" + } + ], + "parameters": { + "Right": 1 + }, + "nullable": [ + false, + false, + false, + false, + false, + false, + false + ] + }, + "hash": "ad1485f0a5514bcfaf68477723ae0f13e93a1f18213e208d3a181936a36da5fb" +} diff --git a/.sqlx/query-ae9d1c997891f7e917cde554a251e76e93d3a43d1447faa4ec4085f7b3f60404.json b/.sqlx/query-ae9d1c997891f7e917cde554a251e76e93d3a43d1447faa4ec4085f7b3f60404.json deleted file mode 100644 index cb345dc..0000000 --- a/.sqlx/query-ae9d1c997891f7e917cde554a251e76e93d3a43d1447faa4ec4085f7b3f60404.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "db_name": "SQLite", - "query": "\n select\n token.id as \"token_id: Id\",\n login.id as \"login_id: login::Id\",\n login.name as \"login_name\"\n from login\n join token on login.id = token.login\n where token.secret = $1\n ", - "describe": { - "columns": [ - { - "name": "token_id: Id", - "ordinal": 0, - "type_info": "Text" - }, - { - "name": "login_id: login::Id", - "ordinal": 1, - "type_info": "Text" - }, - { - "name": "login_name", - "ordinal": 2, - "type_info": "Text" - } - ], - "parameters": { - "Right": 1 - }, - "nullable": [ - false, - false, - false - ] - }, - "hash": "ae9d1c997891f7e917cde554a251e76e93d3a43d1447faa4ec4085f7b3f60404" -} 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-b09438f4b1247a4e3991751de1fa77f2a18537d30e61ccbdcc947d0dba2b3da3.json b/.sqlx/query-b09438f4b1247a4e3991751de1fa77f2a18537d30e61ccbdcc947d0dba2b3da3.json deleted file mode 100644 index 7c83aa1..0000000 --- a/.sqlx/query-b09438f4b1247a4e3991751de1fa77f2a18537d30e61ccbdcc947d0dba2b3da3.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "db_name": "SQLite", - "query": "\n select\n id as \"id: Id\",\n name,\n created_sequence as \"created_sequence: Sequence\",\n created_at as \"created_at: DateTime\"\n from login\n where coalesce(created_sequence <= $1, true)\n order by created_sequence\n ", - "describe": { - "columns": [ - { - "name": "id: Id", - "ordinal": 0, - "type_info": "Text" - }, - { - "name": "name", - "ordinal": 1, - "type_info": "Text" - }, - { - "name": "created_sequence: Sequence", - "ordinal": 2, - "type_info": "Integer" - }, - { - "name": "created_at: DateTime", - "ordinal": 3, - "type_info": "Text" - } - ], - "parameters": { - "Right": 1 - }, - "nullable": [ - false, - false, - false, - false - ] - }, - "hash": "b09438f4b1247a4e3991751de1fa77f2a18537d30e61ccbdcc947d0dba2b3da3" -} diff --git a/.sqlx/query-b67d56f20dab413e31a64842bfc6c82b1464afa98845e537e850d05deb328f06.json b/.sqlx/query-b67d56f20dab413e31a64842bfc6c82b1464afa98845e537e850d05deb328f06.json new file mode 100644 index 0000000..677495b --- /dev/null +++ b/.sqlx/query-b67d56f20dab413e31a64842bfc6c82b1464afa98845e537e850d05deb328f06.json @@ -0,0 +1,12 @@ +{ + "db_name": "SQLite", + "query": "\n update login\n set canonical_name = $1\n where id = $2\n ", + "describe": { + "columns": [], + "parameters": { + "Right": 2 + }, + "nullable": [] + }, + "hash": "b67d56f20dab413e31a64842bfc6c82b1464afa98845e537e850d05deb328f06" +} 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-b991b34b491306780a1b6efa157b6ee50f32e1136ad9cbd91caa0add2ab3cdaa.json b/.sqlx/query-c31c02aa8c4e615c463835d188879a394d36e66f90edb27d2665f081ff95087f.json index 3901207..aa20875 100644 --- a/.sqlx/query-b991b34b491306780a1b6efa157b6ee50f32e1136ad9cbd91caa0add2ab3cdaa.json +++ b/.sqlx/query-c31c02aa8c4e615c463835d188879a394d36e66f90edb27d2665f081ff95087f.json @@ -1,6 +1,6 @@ { "db_name": "SQLite", - "query": "\n\t\t\t\tselect\n\t\t\t\t\tid as \"id: login::Id\",\n\t\t\t\t\tname,\n\t\t\t\t\tpassword_hash as \"password_hash: StoredHash\",\n created_sequence as \"created_sequence: Sequence\",\n created_at as \"created_at: DateTime\"\n\t\t\t\tfrom login\n\t\t\t\twhere name = $1\n\t\t\t", + "query": "\n select\n id as \"id: login::Id\",\n display_name as \"display_name: String\",\n canonical_name as \"canonical_name: String\",\n created_sequence as \"created_sequence: Sequence\",\n created_at as \"created_at: DateTime\"\n from login\n where id = $1\n ", "describe": { "columns": [ { @@ -9,12 +9,12 @@ "type_info": "Text" }, { - "name": "name", + "name": "display_name: String", "ordinal": 1, "type_info": "Text" }, { - "name": "password_hash: StoredHash", + "name": "canonical_name: String", "ordinal": 2, "type_info": "Text" }, @@ -40,5 +40,5 @@ false ] }, - "hash": "b991b34b491306780a1b6efa157b6ee50f32e1136ad9cbd91caa0add2ab3cdaa" + "hash": "c31c02aa8c4e615c463835d188879a394d36e66f90edb27d2665f081ff95087f" } 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-d1c869c323d1ab45216279ae5ca13b72436960622863420d3f1d73a422fe5b42.json b/.sqlx/query-d1c869c323d1ab45216279ae5ca13b72436960622863420d3f1d73a422fe5b42.json new file mode 100644 index 0000000..658728c --- /dev/null +++ b/.sqlx/query-d1c869c323d1ab45216279ae5ca13b72436960622863420d3f1d73a422fe5b42.json @@ -0,0 +1,12 @@ +{ + "db_name": "SQLite", + "query": "\n insert\n into channel (id, created_at, created_sequence)\n values ($1, $2, $3)\n ", + "describe": { + "columns": [], + "parameters": { + "Right": 3 + }, + "nullable": [] + }, + "hash": "d1c869c323d1ab45216279ae5ca13b72436960622863420d3f1d73a422fe5b42" +} diff --git a/.sqlx/query-ec1bfce459faaf3d4adbed040105e9e7fa30a6aac5580036d052a1270e13a311.json b/.sqlx/query-d49d4ab5f1bf4c78fa619680b04a506cd63a85741923f841b7c36c46b70a538f.json index f38401c..3ec71e8 100644 --- a/.sqlx/query-ec1bfce459faaf3d4adbed040105e9e7fa30a6aac5580036d052a1270e13a311.json +++ b/.sqlx/query-d49d4ab5f1bf4c78fa619680b04a506cd63a85741923f841b7c36c46b70a538f.json @@ -1,6 +1,6 @@ { "db_name": "SQLite", - "query": "\n\t\t\t\tselect\n\t\t\t\t\tid as \"id: Id\",\n\t\t\t\t\tissuer as \"issuer: login::Id\",\n\t\t\t\t\tissued_at as \"issued_at: DateTime\"\n\t\t\t\tfrom invite\n\t\t\t\twhere id = $1\n\t\t\t", + "query": "\n select\n id as \"id: Id\",\n issuer as \"issuer: login::Id\",\n issued_at as \"issued_at: DateTime\"\n from invite\n where id = $1\n ", "describe": { "columns": [ { @@ -28,5 +28,5 @@ false ] }, - "hash": "ec1bfce459faaf3d4adbed040105e9e7fa30a6aac5580036d052a1270e13a311" + "hash": "d49d4ab5f1bf4c78fa619680b04a506cd63a85741923f841b7c36c46b70a538f" } diff --git a/.sqlx/query-df22d29fc47244ee696b3eaab9d1be6f740ec4a7fc713056befc4ac700259951.json b/.sqlx/query-df22d29fc47244ee696b3eaab9d1be6f740ec4a7fc713056befc4ac700259951.json deleted file mode 100644 index 5a34da8..0000000 --- a/.sqlx/query-df22d29fc47244ee696b3eaab9d1be6f740ec4a7fc713056befc4ac700259951.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "db_name": "SQLite", - "query": "\n\t\t\t\tselect\n\t\t\t\t\tissuer.id as \"issuer_id: login::Id\",\n\t\t\t\t\tissuer.name as \"issuer_name\",\n\t\t\t\t\tinvite.issued_at as \"invite_issued_at: DateTime\"\n\t\t\t\tfrom invite\n\t\t\t\tjoin login as issuer on (invite.issuer = issuer.id)\n\t\t\t\twhere invite.id = $1\n\t\t\t", - "describe": { - "columns": [ - { - "name": "issuer_id: login::Id", - "ordinal": 0, - "type_info": "Text" - }, - { - "name": "issuer_name", - "ordinal": 1, - "type_info": "Text" - }, - { - "name": "invite_issued_at: DateTime", - "ordinal": 2, - "type_info": "Text" - } - ], - "parameters": { - "Right": 1 - }, - "nullable": [ - false, - false, - false - ] - }, - "hash": "df22d29fc47244ee696b3eaab9d1be6f740ec4a7fc713056befc4ac700259951" -} diff --git a/.sqlx/query-e01508e57cc9cecc83640a5518d6364c8dbfdb45f205fecf0734fe272be493b0.json b/.sqlx/query-e01508e57cc9cecc83640a5518d6364c8dbfdb45f205fecf0734fe272be493b0.json new file mode 100644 index 0000000..4efac0c --- /dev/null +++ b/.sqlx/query-e01508e57cc9cecc83640a5518d6364c8dbfdb45f205fecf0734fe272be493b0.json @@ -0,0 +1,12 @@ +{ + "db_name": "SQLite", + "query": "\n insert\n into login (id, display_name, canonical_name, password_hash, created_sequence, created_at)\n values ($1, $2, $3, $4, $5, $6)\n ", + "describe": { + "columns": [], + "parameters": { + "Right": 6 + }, + "nullable": [] + }, + "hash": "e01508e57cc9cecc83640a5518d6364c8dbfdb45f205fecf0734fe272be493b0" +} diff --git a/.sqlx/query-e36d7cd00f040807c3994b5010f2f77b943ec225244fcfc24013b12a48084a1e.json b/.sqlx/query-e36d7cd00f040807c3994b5010f2f77b943ec225244fcfc24013b12a48084a1e.json new file mode 100644 index 0000000..6700c43 --- /dev/null +++ b/.sqlx/query-e36d7cd00f040807c3994b5010f2f77b943ec225244fcfc24013b12a48084a1e.json @@ -0,0 +1,56 @@ +{ + "db_name": "SQLite", + "query": "\n select\n id as \"id: Id\",\n name.display_name as \"display_name?: String\",\n name.canonical_name as \"canonical_name?: String\",\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_name as name\n using (id)\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": "display_name?: String", + "ordinal": 1, + "type_info": "Null" + }, + { + "name": "canonical_name?: String", + "ordinal": 2, + "type_info": "Null" + }, + { + "name": "created_at: DateTime", + "ordinal": 3, + "type_info": "Text" + }, + { + "name": "created_sequence: Sequence", + "ordinal": 4, + "type_info": "Integer" + }, + { + "name": "deleted_at?: DateTime", + "ordinal": 5, + "type_info": "Text" + }, + { + "name": "deleted_sequence?: Sequence", + "ordinal": 6, + "type_info": "Integer" + } + ], + "parameters": { + "Right": 1 + }, + "nullable": [ + false, + false, + false, + false, + false, + false, + false + ] + }, + "hash": "e36d7cd00f040807c3994b5010f2f77b943ec225244fcfc24013b12a48084a1e" +} 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-e718f4064cbb3d1b27049450121451dbcf01e8bec8a987b58c699b27b5d737af.json b/.sqlx/query-e718f4064cbb3d1b27049450121451dbcf01e8bec8a987b58c699b27b5d737af.json new file mode 100644 index 0000000..0c21ec1 --- /dev/null +++ b/.sqlx/query-e718f4064cbb3d1b27049450121451dbcf01e8bec8a987b58c699b27b5d737af.json @@ -0,0 +1,12 @@ +{ + "db_name": "SQLite", + "query": "\n update message\n set body = ''\n where id = $1\n ", + "describe": { + "columns": [], + "parameters": { + "Right": 1 + }, + "nullable": [] + }, + "hash": "e718f4064cbb3d1b27049450121451dbcf01e8bec8a987b58c699b27b5d737af" +} 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/.sqlx/query-fce8f4fbd59a8b3b8531e10599914331682d58ace57214bfa26ccaa089592a24.json b/.sqlx/query-fce8f4fbd59a8b3b8531e10599914331682d58ace57214bfa26ccaa089592a24.json new file mode 100644 index 0000000..7aab764 --- /dev/null +++ b/.sqlx/query-fce8f4fbd59a8b3b8531e10599914331682d58ace57214bfa26ccaa089592a24.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 as \"body: 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: 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, + true, + false, + false, + true, + true + ] + }, + "hash": "fce8f4fbd59a8b3b8531e10599914331682d58ace57214bfa26ccaa089592a24" +} @@ -297,9 +297,9 @@ checksum = "428d9aa8fbc0670b7b8d6030a7fadd0f86151cae55e4dbbece15f3780a3dfaf3" [[package]] name = "cc" -version = "1.1.25" +version = "1.1.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8d9e0b4957f635b8d3da819d0db5603620467ecf1f692d22a8c2717ce27e6d8" +checksum = "b16803a61b81d9eabb7eae2588776c4c1e584b738ede45fdbb4c972cec1e9945" dependencies = [ "shlex", ] @@ -327,9 +327,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.19" +version = "4.5.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7be5744db7978a28d9df86a214130d106a89ce49644cbc4e3f0c22c3fba30615" +checksum = "b97f376d85a664d5837dbae44bf546e6477a679ff6610010f17276f686d867e8" dependencies = [ "clap_builder", "clap_derive", @@ -337,9 +337,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.19" +version = "4.5.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a5fbc17d3ef8278f55b282b2a2e75ae6f6c7d4bb70ed3d0382375104bfafdb4b" +checksum = "19bc80abd44e4bed93ca373a0704ccbd1b710dc5749406201bb018272808dc54" dependencies = [ "anstream", "anstyle", @@ -813,7 +813,7 @@ dependencies = [ "headers", "hex-literal", "itertools", - "mime_guess", + "mime", "password-hash", "rand", "rand_core", @@ -825,6 +825,9 @@ dependencies = [ "thiserror", "tokio", "tokio-stream", + "unicode-casefold", + "unicode-normalization", + "unix_path", "uuid", ] @@ -903,9 +906,9 @@ checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" [[package]] name = "hyper" -version = "1.4.1" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50dfd22e0e76d0f662d429a5f80fcaf3855009297eab6a0a9f8543834744ba05" +checksum = "bbbff0a806a4728c99295b254c8838933b5b082d75e3cb70c8dab21fdfbcfa9a" dependencies = [ "bytes", "futures-channel", @@ -1002,9 +1005,9 @@ checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b" [[package]] name = "js-sys" -version = "0.3.70" +version = "0.3.72" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1868808506b929d7b0cfa8f75951347aa71bb21144b7791bae35d9bccfcfe37a" +checksum = "6a88f1bda2bd75b0452a14784937d796722fdebfe50df998aeb3f0b7603019a9" dependencies = [ "wasm-bindgen", ] @@ -1020,9 +1023,9 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.159" +version = "0.2.161" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "561d97a539a36e26a9a5fad1ea11a3039a67714694aaa379433e580854bc3dc5" +checksum = "8e9489c2807c139ffd9c1794f4af0ebe86a828db53ecdc7fea2111d0fed085d1" [[package]] name = "libm" @@ -1092,16 +1095,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" [[package]] -name = "mime_guess" -version = "2.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e" -dependencies = [ - "mime", - "unicase", -] - -[[package]] name = "minimal-lexical" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -1323,9 +1316,9 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.86" +version = "1.0.88" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e719e8df665df0d1c8fbfd238015744736151d4445ec0836b8e628aae103b77" +checksum = "7c3a7fc5db1e57d5a779a352c8cdb57b29aa4c40cc69c3a68a7fedc815fbf2f9" dependencies = [ "unicode-ident", ] @@ -1467,9 +1460,9 @@ dependencies = [ [[package]] name = "rustversion" -version = "1.0.17" +version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "955d28af4278de8121b7ebeb796b6a45735dc01436d898801014aced2773a3d6" +checksum = "0e819f2bc632f285be6d7cd36e25940d45b2391dd6d9b939e79de557f7014248" [[package]] name = "ryu" @@ -1527,9 +1520,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.128" +version = "1.0.131" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ff5456707a1de34e7e37f2a6fd3d3f808c318259cbd01ab6377795054b483d8" +checksum = "67d42a0bd4ac281beff598909bb56a86acaf979b84483e1c79c10dcaf98f8cf3" dependencies = [ "itoa", "memchr", @@ -2096,21 +2089,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825" [[package]] -name = "unicase" -version = "2.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7d2d4dafb69621809a81864c9c1b864479e1235c0dd4e199924b9742439ed89" -dependencies = [ - "version_check", -] - -[[package]] name = "unicode-bidi" version = "0.3.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5ab17db44d7388991a428b2ee655ce0c212e862eff1768a455c58f9aad6e7893" [[package]] +name = "unicode-casefold" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f66b1c8f8caa2ab31dc6d3f35386f16efdab89668f93411e565ac368908e8f" + +[[package]] name = "unicode-ident" version = "1.0.13" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -2138,6 +2128,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39ec24b3121d976906ece63c9daad25b85969647682eee313cb5779fdd69e14e" [[package]] +name = "unix_path" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af8e291873ae77c4c8d9c9b34d0bee68a35b048fb39c263a5155e0e353783eaf" +dependencies = [ + "unix_str", +] + +[[package]] +name = "unix_str" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ace0b4755d0a2959962769239d56267f8a024fef2d9b32666b3dcd0946b0906" + +[[package]] name = "url" version = "2.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -2156,9 +2161,9 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" [[package]] name = "uuid" -version = "1.10.0" +version = "1.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81dfa00651efa65069b0b6b651f4aaa31ba9e3c3ce0137aaad053604ee7e0314" +checksum = "f8c5f0a0af699448548ad1a2fbf920fb4bee257eae39953ba95cb84891a0446a" dependencies = [ "getrandom", ] @@ -2199,9 +2204,9 @@ checksum = "b8dad83b4f25e74f184f64c43b150b91efe7647395b42289f38e50566d82855b" [[package]] name = "wasm-bindgen" -version = "0.2.93" +version = "0.2.95" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a82edfc16a6c469f5f44dc7b571814045d60404b55a0ee849f9bcfa2e63dd9b5" +checksum = "128d1e363af62632b8eb57219c8fd7877144af57558fb2ef0368d0087bddeb2e" dependencies = [ "cfg-if", "once_cell", @@ -2210,9 +2215,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-backend" -version = "0.2.93" +version = "0.2.95" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9de396da306523044d3302746f1208fa71d7532227f15e347e2d93e4145dd77b" +checksum = "cb6dd4d3ca0ddffd1dd1c9c04f94b868c37ff5fac97c30b97cff2d74fce3a358" dependencies = [ "bumpalo", "log", @@ -2225,9 +2230,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.93" +version = "0.2.95" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "585c4c91a46b072c92e908d99cb1dcdf95c5218eeb6f3bf1efa991ee7a68cccf" +checksum = "e79384be7f8f5a9dd5d7167216f022090cf1f9ec128e6e6a482a2cb5c5422c56" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -2235,9 +2240,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.93" +version = "0.2.95" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "afc340c74d9005395cf9dd098506f7f44e38f2b4a21c6aaacf9a105ea5e1e836" +checksum = "26c6ab57572f7a24a4985830b120de1594465e5d500f24afe89e16b4e833ef68" dependencies = [ "proc-macro2", "quote", @@ -2248,9 +2253,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-shared" -version = "0.2.93" +version = "0.2.95" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c62a0a307cb4a311d3a07867860911ca130c3494e8c2719593806c08bc5d0484" +checksum = "65fc09f10666a9f147042251e0dda9c18f166ff7de300607007e96bdebc1068d" [[package]] name = "whoami" @@ -2,6 +2,8 @@ name = "hi" version = "0.1.0" edition = "2021" +rust-version = "1.82" +default-run = "hi" [dependencies] argon2 = "0.5.3" @@ -9,12 +11,12 @@ async-trait = "0.1.83" axum = { version = "0.7.7", features = ["form"] } axum-extra = { version = "0.9.4", features = ["cookie", "query", "typed-header"] } chrono = { version = "0.4.38", features = ["serde"] } -clap = { version = "4.5.19", features = ["derive", "env"] } +clap = { version = "4.5.20", features = ["derive", "env"] } futures = "0.3.31" headers = "0.4.0" hex-literal = "0.4.1" itertools = "0.13.0" -mime_guess = "2.0.5" +mime = "0.3.17" password-hash = { version = "0.5.0", features = ["std"] } rand = "0.8.5" rand_core = { version = "0.6.4", features = ["getrandom"] } @@ -23,14 +25,17 @@ rand_core = { version = "0.6.4", features = ["getrandom"] } rusqlite = { version = "=0.32.1", features = ["backup"] } rust-embed = "8.5.0" serde = { version = "1.0.210", features = ["derive"] } -serde_json = "1.0.128" +serde_json = "1.0.131" # Pinned to maintain libsqlite3 version match between this and rusqlite. See # also: <https://docs.rs/sqlx/latest/sqlx/sqlite/index.html> sqlx = { version = "=0.8.2", features = ["chrono", "runtime-tokio", "sqlite"] } thiserror = "1.0.64" tokio = { version = "1.40.0", features = ["rt", "macros", "rt-multi-thread"] } tokio-stream = { version = "0.1.16", features = ["sync"] } -uuid = { version = "1.10.0", features = ["v4"] } +unicode-casefold = "0.2.0" +unicode-normalization = "0.1.24" +unix_path = "1.0.1" +uuid = { version = "1.11.0", features = ["v4"] } [dev-dependencies] faker_rand = "0.1.1" @@ -1,5 +1,44 @@ -// generated by `sqlx migrate build-script` -fn main() { +use std::{io, process::Command}; + +fn main() -> Result<(), io::Error> { // trigger recompilation when a new migration is added - println!("cargo:rerun-if-changed=migrations"); + println!("cargo::rerun-if-changed=migrations"); + + // rerun npm install whenever packages or npm config are changed + println!("cargo::rerun-if-changed=.npmrc"); + println!("cargo::rerun-if-changed=package.json"); + // `node_modules` and `package-lock.json` are always touched if `npm install` + // runs, leading to spurious rebuilds. + // + // See: <https://github.com/npm/cli/issues/7874> + // println!("cargo::rerun-if-changed=package-lock.json"); + // println!("cargo::rerun-if-changed=node_modules"); + let status = Command::new("npm").args(["install"]).status()?; + if !status.success() { + return Err(io::Error::other(format!( + "'npm install' exited with status {status:?}" + ))); + } + + // rerun `npm run build` whenever the UI changes. + // + // `node_modules` is always touched if `npm install` runs, leading to spurious + // rebuilds. (This duplicate is purely organizational; it reflects that the ui + // depends on node_modules.) + // + // See: <https://github.com/npm/cli/issues/7874> + // println!("cargo::rerun-if-changed=node_modules"); + println!("cargo::rerun-if-changed=postcss.config.js"); + println!("cargo::rerun-if-changed=svelte.config.js"); + println!("cargo::rerun-if-changed=tailwind.config.js"); + println!("cargo::rerun-if-changed=vite.config.js"); + println!("cargo::rerun-if-changed=ui"); + let status = Command::new("npm").args(["run", "build"]).status()?; + if !status.success() { + return Err(io::Error::other(format!( + "'npm run build' exited with status {status:?}" + ))); + } + + Ok(()) } diff --git a/docs/api/authentication.md b/docs/api/authentication.md index d4c1f70..135e91b 100644 --- a/docs/api/authentication.md +++ b/docs/api/authentication.md @@ -13,6 +13,23 @@ stateDiagram-v2 Authentication associates each authenticated request with a login. +To create logins, see [initial setup](./initial-setup.md) and [invitations](./invitations.md). + + +## Names + +<!-- This prose is duplicated in channels-messages.md. If you change it here, consider changing it there, too. --> +The service handles login names using two separate forms. + +The first form is as given in the request used to create the login. This form of the login name is used throughout the API, and the service will preserve the name as entered (other than applying normalization), so that users' preferences around capitalization and accent marks are preserved. + +The second form is a "canonical" form, used internally by the service to control uniqueness and match names to logins. The canonical form is both case-folded and normalized. + +The canonical form is not available to API clients, but its use has practical consequences: + +* Names that differ only by case or only by code point sequence are treated as the same name. If the name is in use, changing the capitalization or changing the sequence of combining marks will not allow the creation of a second "identical" login. +* The login API accepts any name that canonicalizes to the form stored in the database, making login names effectively case-insensitive. + ## Identity tokens @@ -32,8 +49,6 @@ Unless the endpoint's documentation says otherwise, all endpoints require authen Authenticates the user using their login name and password. The login must exist before calling this endpoint. -To create logins, see [initial setup](./initial-setup.md) and [invitations](./invitations.md). - **This endpoint does not require an `identity` cookie.** ### Request @@ -56,7 +71,21 @@ The request must have the following fields: <!-- This prose is duplicated by 03-initial-setup.md and in 04-invitations.md, with small changes for context. If you edit it here, edit it there, too. --> -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 d032ac1..9ef4e66 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,31 @@ 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. + +## Names + +<!-- This prose is duplicated in authentication.md. If you change it here, consider changing it there, too. --> +The service handles channel names using two separate forms. + +The first form is as given in the request used to create the channel. This form of the channel name is used throughout the API, and the service will preserve the name as entered (other than applying normalization), so that users' preferences around capitalization and accent marks are preserved. + +The second form is a "canonical" form, used internally by the service to control uniqueness and match names to channels. The canonical form is both case-folded and normalized. + +The canonical form is not available to API clients, but its use has practical consequences. Names that differ only by case or only by code point sequence are treated as the same name. If the name is in use, changing the capitalization or changing the sequence of combining marks will not allow the creation of a second "identical" channel. + + +## 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` @@ -49,12 +66,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", } ``` @@ -62,8 +79,12 @@ 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. | + +The returned name may not be identical to the name requested, as the name will be converted to [normalization form C](http://www.unicode.org/reports/tr15/) automatically. The returned name will include this normalization; the service will use the normalized name elsewhere, and does not store the originally requested name. + +When completed, the service will emit a [channel created](events.md#channel-created) event with the channel's ID. ### Duplicate channel name @@ -96,7 +117,31 @@ 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. | + +The returned message body may not be identical to the body as sent, as the body will be converted to [normalization form C](http://www.unicode.org/reports/tr15/) automatically. The returned body will include this normalization; the service will use the normalized body elsewhere, and does not store the originally submitted body. + +When completed, the service will emit a [message sent](events.md#message-sent) event with the message's ID. ### Invalid channel ID @@ -105,7 +150,9 @@ This endpoint will respond with a status of `404 Not Found` if the channel ID is ## `DELETE /api/channels/:id` -Deletes a channel (and all messages in it). +Deletes a channel. + +Deleting a channel prevents it from receiving any further messages, and deletes the messages it contains at that point. This endpoint requires the following path parameter: @@ -117,6 +164,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. In addition, the service will emit a [message deleted](events.md#message-deleted) event for each message deleted. + + ### Invalid channel ID This endpoint will respond with a status of `404 Not Found` if the channel ID is not valid. @@ -136,6 +186,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 9fe9ca9..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. @@ -133,11 +138,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 `""`. Tombstone events for channels use an empty string as the name, and not `null` or with the `name` field removed entirely, to simplify client development. While clients _should_ treat deleted channels specially, for example by rendering them as "channel deleted" markers, they don't have to be - they make sense if interpreted as channels with empty names, too. + +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 +194,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 `""`. Tombstone events for messages use an empty string as the `body`, and not `null` or with the `body` field removed entirely, to simplify client development. While clients _should_ treat deleted messages specially, for example by rendering them as "message deleted" markers, they don't have to be - they make sense if interpreted as messages with empty bodies, too. + +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/docs/api/initial-setup.md b/docs/api/initial-setup.md index ad57089..306d798 100644 --- a/docs/api/initial-setup.md +++ b/docs/api/initial-setup.md @@ -55,7 +55,25 @@ The request must have the following fields: <!-- This prose is duplicated from authentication.md, with small changes for context. If you edit it here, edit it there, too. --> -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 returned name may not be identical to the name requested, as the name will be converted to [normalization form C](http://www.unicode.org/reports/tr15/) automatically. The returned name will include this normalization; the service will use the normalized name elsewhere, and does not store the originally requested name. + +The provided password will also be converted to normalization form C. However, the normalized password is not returned to the client. 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 0f21a0e..ddbef8a 100644 --- a/docs/api/invitations.md +++ b/docs/api/invitations.md @@ -91,17 +91,11 @@ The response will include the following fields: | Field | Type | Description | |:------------|:-------|:--| -| `issuer` | object | The details of the login that issued the invitation. | +| `id` | string | The ID of the invitation. | +| `issuer` | string | The login name of the invitation's issuer. | | `issued_at` | string | The timestamp from which the invitation will expire. | -The `issuer` object will include the following fields: - -| Field | Type | Description | -|:-------|:-------|:--| -| `id` | string | The login ID of the invitation's issuer. | -| `name` | string | The login name of the invitation's issuer. | - -Clients should present the issuer's name to the user when presenting an invitation, so as to personalize the invitation and help them understand their connection with the service. +Clients should present the `issuer` to the user when presenting an invitation, so as to personalize the invitation and help them understand their connection with the service. ### Invitation not found @@ -140,7 +134,25 @@ The request must have the following fields: <!-- This prose is duplicated from authentication.md, with small changes for context. If you edit it here, edit it there, too. --> -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 returned name may not be identical to the name requested, as the name will be converted to [normalization form C](http://www.unicode.org/reports/tr15/) automatically. The returned name will include this normalization; the service will use the normalized name elsewhere, and does not store the originally requested name. + +The provided password will also be converted to normalization form C. However, the normalized password is not returned to the client. 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/docs/internal-server-errors.md b/docs/internal-server-errors.md new file mode 100644 index 0000000..4f679b7 --- /dev/null +++ b/docs/internal-server-errors.md @@ -0,0 +1,30 @@ +# Internal Server Errors + +When `hi` encounters a problem that prevents a request from completing, it may report a `500 Internal Server Error` to clients, along with an error code. The actual error will be printed to standard error, with the error code. The following sections describe errors we've encountered, the likely operational consequences, and recommend approaches for addressing them. + +## database is locked + +The server attempted two write transactions at the same time, and encountered [sqlite's write locks](https://www.sqlite.org/rescode.html#busy). This is unfortunately unavoidable, but generally only occurs as a result of extremely bad luck, or very high load. + +This error will almost always resolve itself if clients re-try their requests; no further action is needed. + +This is a known issue. If you are encountering this consistently (or if you can trigger it on demand), let us know. We are aware of sqlite's features for mitigating this issue but have been unsuccessful in applying them; we're working on it, but patches _are_ welcome, if you have the opportunity. + +## stored canonical form […] does not match computed canonical form […] for name […] + +When `hi` applies the `migrations/20241019191531_canonical_names.sql` migration (from commit `3f9648eed48cd8b6cd35d0ae2ee5bbe25fa735ac`), this can leave existing names in a state where the stored canonical form is not the correct canonicalization of the stored display names of channels and logins. `hi` will abort requests when it encounters this situation, to avoid incorrect behaviours such as duplicate channels or duplicate logins. + +As channel and login names may be presented during client startup, this can render the service unusable until repaired. Treat this as an immediate outage if you see it. + +You can verify that login names are unique by running the following commands as the user the `hi` server runs as: + +* `sqlite3 .hi 'select display_name from login'` +* `sqlite3 .hi 'select display_name from channel_name'` + +Substitute `.hi` with the path to your `hi` database if it differs from the default. + +If the names are unique, you can repair the database: + +* Stop the `hi` server. +* Run `hi-recanonicalize`, as the same user the `hi` server runs as, with the same database options. +* Start the `hi` server. diff --git a/git-hooks/pre-commit b/git-hooks/pre-commit index cafdb8d..4485005 100755 --- a/git-hooks/pre-commit +++ b/git-hooks/pre-commit @@ -4,8 +4,8 @@ # run. It gets old fast. That's why this uses `cargo check` and not `cargo # test`, for example. -# Make sure the UI is up to date. -tools/build-ui +# Make sure package-lock.json is up to date with package.json +npm ci --dry-run # Make sure Cargo.lock is up to date with Cargo.toml. cargo update --locked --workspace # Make sure there are no screamers in the code. diff --git a/migrations/20241017005219_retain_deleted.sql b/migrations/20241017005219_retain_deleted.sql new file mode 100644 index 0000000..aed87f4 --- /dev/null +++ b/migrations/20241017005219_retain_deleted.sql @@ -0,0 +1,77 @@ +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 + null + unique, + created_sequence bigint + unique + not null, + created_at text + not null +); + +insert into channel (id, name, created_sequence, created_at) +select id, name, created_sequence, created_at 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 + 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/migrations/20241019191531_canonical_names.sql b/migrations/20241019191531_canonical_names.sql new file mode 100644 index 0000000..ab7cbf4 --- /dev/null +++ b/migrations/20241019191531_canonical_names.sql @@ -0,0 +1,189 @@ +alter table login +rename to old_login; +alter table token +rename to old_token; +alter table invite +rename to old_invite; +alter table channel +rename to old_channel; +alter table channel_deleted +rename to old_channel_deleted; +alter table message +rename to old_message; +alter table message_deleted +rename to old_message_deleted; + +create table login ( + id text + not null + primary key, + display_name text + not null, + canonical_name text + not null + unique, + password_hash text + not null, + created_sequence bigint + unique + not null, + created_at text + not null +); + +insert into login (id, display_name, canonical_name, password_hash, created_sequence, created_at) +select + id, + -- This isn't strictly correct, as existing names are not guaranteed to be + -- normalized, and as sqlite's built-in `lower` only operates on ASCII, but + -- without any way to do case folding and normalization in sqlite3, and + -- without any way to call out into Rust to do the work, this is the best we + -- can do. Normalization issues will produce errors at runtime when the + -- relevant rows are loaded. + name as display_name, + lower(name) as canonical_name, + password_hash, + created_sequence, + created_at +from old_login; + +create table token ( + id text + not null + primary key, + secret text + not null + unique, + login text + not null + references login (id), + issued_at text + not null, + last_used_at text + not null +); + +insert into token (id, secret, login, issued_at, last_used_at) +select id, secret, login, issued_at, last_used_at from old_token; + +create table invite ( + id text + primary key + not null, + issuer text + not null + references login (id), + issued_at text + not null +); + +insert into invite (id, issuer, issued_at) +select id, issuer, issued_at +from old_invite; + +create table channel ( + id text + not null + primary key, + created_sequence bigint + unique + not null, + created_at text + not null +); + +create table channel_name ( + id text + not null + primary key + references channel (id), + display_name + not null, + canonical_name + not null + unique +); + +insert into channel (id, created_sequence, created_at) +select id, created_sequence, created_at from old_channel; + +insert into channel_name (id, display_name, canonical_name) +select + id, + -- This isn't strictly correct, for the same reasons as above. + name as display_name, + name as canonical_name +from old_channel +where name is not null; + +create table channel_deleted ( + id text + not null + primary key + references channel (id), + deleted_sequence bigint + unique + not null, + deleted_at text + not null +); + +insert into channel_deleted (id, deleted_sequence, deleted_at) +select id, deleted_sequence, deleted_at +from old_channel_deleted; + +create table message ( + id text + not null + primary key, + -- Starting from the code changes in this rev, values in this column will be + -- in NFC. However, we don't actually need to normalize historical values; + -- they're delivered to clients "verbatim" with respect to how they were sent, + -- which causes no harm. + 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 + 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 +); + +insert into message_deleted (id, deleted_sequence, deleted_at) +select id, deleted_sequence, deleted_at +from old_message_deleted; + +drop table old_message_deleted; +drop table old_message; +drop table old_channel_deleted; +drop table old_channel; +drop table old_invite; +drop table old_token; +drop table old_login; + +create index token_issued_at +on token (issued_at); +create index message_sent_at +on message (sent_at); diff --git a/migrations/20241023040731_missing_indices.sql b/migrations/20241023040731_missing_indices.sql new file mode 100644 index 0000000..4bfd76d --- /dev/null +++ b/migrations/20241023040731_missing_indices.sql @@ -0,0 +1,17 @@ +create index message_deleted_deleted_at +on message_deleted (deleted_at); + +create index message_channel +on message(channel); + +create index channel_created_sequence +on channel (created_sequence); + +create index channel_created_at +on channel (created_at); + +create index token_last_used_at +on token (last_used_at); + +create index invite_issued_at +on invite (issued_at); diff --git a/package-lock.json b/package-lock.json index 723553f..5e97f90 100644 --- a/package-lock.json +++ b/package-lock.json @@ -14,23 +14,23 @@ "devDependencies": { "@skeletonlabs/skeleton": "^2.10.2", "@skeletonlabs/tw-plugin": "^0.4.0", - "@sveltejs/adapter-auto": "^3.0.0", + "@sveltejs/adapter-auto": "^3.2.5", "@sveltejs/adapter-static": "^3.0.5", - "@sveltejs/kit": "^2.0.0", - "@sveltejs/vite-plugin-svelte": "^3.0.0", + "@sveltejs/kit": "^2.7.1", + "@sveltejs/vite-plugin-svelte": "^3.1.2", "@tailwindcss/forms": "^0.5.9", - "@types/eslint": "^9.6.0", + "@types/eslint": "^9.6.1", "autoprefixer": "^10.4.20", - "eslint": "^9.0.0", + "eslint": "^9.13.0", "eslint-config-prettier": "^9.1.0", - "eslint-plugin-svelte": "^2.36.0", - "globals": "^15.0.0", + "eslint-plugin-svelte": "^2.45.1", + "globals": "^15.11.0", "postcss": "^8.4.47", - "prettier": "^3.1.1", - "prettier-plugin-svelte": "^3.1.2", - "svelte": "^4.2.7", - "tailwindcss": "^3.4.12", - "vite": "^5.0.3" + "prettier": "^3.3.3", + "prettier-plugin-svelte": "^3.2.7", + "svelte": "^4.2.19", + "tailwindcss": "^3.4.14", + "vite": "^5.4.9" } }, "node_modules/@alloc/quick-lru": { @@ -504,6 +504,16 @@ "node": "^18.18.0 || ^20.9.0 || >=21.1.0" } }, + "node_modules/@eslint/core": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.7.0.tgz", + "integrity": "sha512-xp5Jirz5DyPYlPiKat8jaq0EmYvDXKKpzTbxXMpT9eqlRJkRKIz9AGMdlvYjih+im+QlhWrpvVjl8IPC/lHlUw==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, "node_modules/@eslint/eslintrc": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-3.1.0.tgz", @@ -542,9 +552,9 @@ } }, "node_modules/@eslint/js": { - "version": "9.10.0", - "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.10.0.tgz", - "integrity": "sha512-fuXtbiP5GWIn8Fz+LWoOMVf/Jxm+aajZYkhi6CuEm4SxymFM+eUWzbO9qXT+L0iCkL5+KGYMCSGxo686H19S1g==", + "version": "9.13.0", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.13.0.tgz", + "integrity": "sha512-IFLyoY4d72Z5y/6o/BazFBezupzI/taV8sGumxTAVw3lXG9A6md1Dc34T9s1FoD/an9pJH8RHbAxsaEbBed9lA==", "dev": true, "license": "MIT", "engines": { @@ -562,9 +572,9 @@ } }, "node_modules/@eslint/plugin-kit": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.1.0.tgz", - "integrity": "sha512-autAXT203ixhqei9xt+qkYOvY8l6LAFIdT2UXc/RPNeUVfqRF1BV94GTJyVPFKT8nFM6MyVJhjLj9E8JWvf5zQ==", + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.2.1.tgz", + "integrity": "sha512-HFZ4Mp26nbWk9d/BpvP0YNL6W4UoZF0VFcTw/aPPA8RpOxeFQgK+ClABGgAUXs9Y/RGX/l1vOmrqz1MQt9MNuw==", "dev": true, "license": "Apache-2.0", "dependencies": { @@ -574,6 +584,30 @@ "node": "^18.18.0 || ^20.9.0 || >=21.1.0" } }, + "node_modules/@humanfs/core": { + "version": "0.19.0", + "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.0.tgz", + "integrity": "sha512-2cbWIHbZVEweE853g8jymffCA+NCMiuqeECeBBLm8dg2oFdjuGJhgN4UAbI+6v0CKbbhvtXA4qV8YR5Ji86nmw==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanfs/node": { + "version": "0.16.5", + "resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.5.tgz", + "integrity": "sha512-KSPA4umqSG4LHYRodq31VDwKAvaTF4xmVlzM8Aeh4PlU1JQ3IG0wiA8C25d3RQ9nJyM3mBHyI53K06VVL/oFFg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@humanfs/core": "^0.19.0", + "@humanwhocodes/retry": "^0.3.0" + }, + "engines": { + "node": ">=18.18.0" + } + }, "node_modules/@humanwhocodes/module-importer": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", @@ -589,9 +623,9 @@ } }, "node_modules/@humanwhocodes/retry": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.3.0.tgz", - "integrity": "sha512-d2CGZR2o7fS6sWB7DG/3a95bGKQyHMACZ5aW8qGkkqQpUoZV6C0X7Pc7l4ZNMZkfNBf4VWNe9E1jRsf0G146Ew==", + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.3.1.tgz", + "integrity": "sha512-JBxkERygn7Bv/GbN5Rv8Ul6LVknS+5Bp6RgDC/O8gEBU/yeH5Ui5C/OlWrTb6qct7LjjfT6Re2NxB0ln0yYybA==", "dev": true, "license": "Apache-2.0", "engines": { @@ -620,35 +654,6 @@ "node": ">=12" } }, - "node_modules/@isaacs/cliui/node_modules/ansi-regex": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.1.0.tgz", - "integrity": "sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/ansi-regex?sponsor=1" - } - }, - "node_modules/@isaacs/cliui/node_modules/strip-ansi": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz", - "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-regex": "^6.0.1" - }, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/strip-ansi?sponsor=1" - } - }, "node_modules/@jridgewell/gen-mapping": { "version": "0.3.5", "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.5.tgz", @@ -747,9 +752,9 @@ } }, "node_modules/@polka/url": { - "version": "1.0.0-next.27", - "resolved": "https://registry.npmjs.org/@polka/url/-/url-1.0.0-next.27.tgz", - "integrity": "sha512-MU0SYgcrBdSVLu7Tfow3VY4z1odzlaTYRjt3WQ0z8XbjDWReuy+EALt2HdjhrwD2HPiW2GY+KTSw4HLv4C/EOA==", + "version": "1.0.0-next.28", + "resolved": "https://registry.npmjs.org/@polka/url/-/url-1.0.0-next.28.tgz", + "integrity": "sha512-8LduaNlMZGwdZ6qWrKlfa+2M4gahzFkprZiAt2TF8uS0qQgBizKXpXURqvTJ4WtmupWxaLqjRb2UCTe72mu+Aw==", "dev": true, "license": "MIT" }, @@ -1024,16 +1029,16 @@ } }, "node_modules/@sveltejs/kit": { - "version": "2.5.28", - "resolved": "https://registry.npmjs.org/@sveltejs/kit/-/kit-2.5.28.tgz", - "integrity": "sha512-/O7pvFGBsQPcFa9UrW8eUC5uHTOXLsUp3SN0dY6YmRAL9nfPSrJsSJk//j5vMpinSshzUjteAFcfQTU+04Ka1w==", + "version": "2.7.1", + "resolved": "https://registry.npmjs.org/@sveltejs/kit/-/kit-2.7.1.tgz", + "integrity": "sha512-TBVnkwgYQT3EafGQK6Eyh5FlLEBlRhCmqPTwcdOs+QdnyUc3eCAxRWtXlFxIWtmk6pqv11zdng8qTpThdTogew==", "dev": true, "hasInstallScript": true, "license": "MIT", "dependencies": { "@types/cookie": "^0.6.0", "cookie": "^0.6.0", - "devalue": "^5.0.0", + "devalue": "^5.1.0", "esm-env": "^1.0.0", "import-meta-resolve": "^4.1.0", "kleur": "^4.1.5", @@ -1041,7 +1046,7 @@ "mrmime": "^2.0.0", "sade": "^1.8.1", "set-cookie-parser": "^2.6.0", - "sirv": "^2.0.4", + "sirv": "^3.0.0", "tiny-glob": "^0.2.9" }, "bin": { @@ -1148,9 +1153,9 @@ "license": "MIT" }, "node_modules/acorn": { - "version": "8.12.1", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.12.1.tgz", - "integrity": "sha512-tcpGyI9zbizT9JbV6oYE477V6mTlXvvi0T0G3SNIYE2apm/G5huBa1+K89VGeovbg+jycCrfhl3ADxErOuO6Jg==", + "version": "8.13.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.13.0.tgz", + "integrity": "sha512-8zSiw54Oxrdym50NlZ9sUusyO1Z1ZchgRLWRaK6c86XJFClyCgFKetdowBg5bKxyp/u+CDBJG4Mpp0m3HLZl9w==", "license": "MIT", "bin": { "acorn": "bin/acorn" @@ -1187,13 +1192,16 @@ } }, "node_modules/ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.1.0.tgz", + "integrity": "sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA==", "dev": true, "license": "MIT", "engines": { - "node": ">=8" + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" } }, "node_modules/ansi-styles": { @@ -1248,9 +1256,9 @@ "license": "Python-2.0" }, "node_modules/aria-query": { - "version": "5.3.1", - "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.1.tgz", - "integrity": "sha512-Z/ZeOgVl7bcSYZ/u/rh0fOpvEpq//LZmdbkXyc7syVzjPAhfOa9ebsdTSjEBDU4vs5nC98Kfduj1uFo0qyET3g==", + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.2.tgz", + "integrity": "sha512-COROpnaoap1E2F000S62r6A60uHZnmlvomhfyT2DlTcrY1OrBKn2UhH7qn5wTC9zMvD0AY7csdPSNwKP+7WiQw==", "license": "Apache-2.0", "engines": { "node": ">= 0.4" @@ -1365,9 +1373,9 @@ } }, "node_modules/browserslist": { - "version": "4.23.3", - "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.23.3.tgz", - "integrity": "sha512-btwCFJVjI4YWDNfau8RhZ+B1Q/VLoUITrm3RlP6y1tYGWIOa+InuYiRGXUBXo8nA1qKmHMyLB/iVQg5TT4eFoA==", + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.24.0.tgz", + "integrity": "sha512-Rmb62sR1Zpjql25eSanFGEhAxcFwfA1K0GuQcLoaJBAcENegrQut3hYdhXFF1obQfiDyqIW/cLM5HSJ/9k884A==", "dev": true, "funding": [ { @@ -1385,8 +1393,8 @@ ], "license": "MIT", "dependencies": { - "caniuse-lite": "^1.0.30001646", - "electron-to-chromium": "^1.5.4", + "caniuse-lite": "^1.0.30001663", + "electron-to-chromium": "^1.5.28", "node-releases": "^2.0.18", "update-browserslist-db": "^1.1.0" }, @@ -1418,9 +1426,9 @@ } }, "node_modules/caniuse-lite": { - "version": "1.0.30001662", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001662.tgz", - "integrity": "sha512-sgMUVwLmGseH8ZIrm1d51UbrhqMCH3jvS7gF/M6byuHOnKyLOBL7W8yz5V02OHwgLGA36o/AFhWzzh4uc5aqTA==", + "version": "1.0.30001669", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001669.tgz", + "integrity": "sha512-DlWzFDJqstqtIVx1zeSpIMLjunf5SmwOw0N2Ck/QSQdS8PLS4+9HrLaYei4w8BIAL7IB/UEDu889d8vhCTPA0w==", "dev": true, "funding": [ { @@ -1651,9 +1659,9 @@ } }, "node_modules/devalue": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/devalue/-/devalue-5.0.0.tgz", - "integrity": "sha512-gO+/OMXF7488D+u3ue+G7Y4AA3ZmUnB3eHJXmBTgNHvr4ZNzl36A0ZtG+XCRNYCkYx/bFmw4qtkoFLa+wSrwAA==", + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/devalue/-/devalue-5.1.1.tgz", + "integrity": "sha512-maua5KUiapvEwiEAe+XnlZ3Rh0GD+qI1J/nb9vrJc3muPXvcF/8gXYTWF76+5DAqHyDUtOIImEuo0YKE9mshVw==", "dev": true, "license": "MIT" }, @@ -1679,9 +1687,9 @@ "license": "MIT" }, "node_modules/electron-to-chromium": { - "version": "1.5.27", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.27.tgz", - "integrity": "sha512-o37j1vZqCoEgBuWWXLHQgTN/KDKe7zwpiY5CPeq2RvUqOyJw9xnrULzZAEVQ5p4h+zjMk7hgtOoPdnLxr7m/jw==", + "version": "1.5.41", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.41.tgz", + "integrity": "sha512-dfdv/2xNjX0P8Vzme4cfzHqnPm5xsZXwsolTYr0eyW18IUmNyG08vL+fttvinTfhKfIKdRoqkDIC9e9iWQCNYQ==", "dev": true, "license": "ISC" }, @@ -1755,29 +1763,32 @@ } }, "node_modules/eslint": { - "version": "9.10.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.10.0.tgz", - "integrity": "sha512-Y4D0IgtBZfOcOUAIQTSXBKoNGfY0REGqHJG6+Q81vNippW5YlKjHFj4soMxamKK1NXHUWuBZTLdU3Km+L/pcHw==", + "version": "9.13.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.13.0.tgz", + "integrity": "sha512-EYZK6SX6zjFHST/HRytOdA/zE72Cq/bfw45LSyuwrdvcclb/gqV8RRQxywOBEWO2+WDpva6UZa4CcDeJKzUCFA==", "dev": true, "license": "MIT", "dependencies": { "@eslint-community/eslint-utils": "^4.2.0", "@eslint-community/regexpp": "^4.11.0", "@eslint/config-array": "^0.18.0", + "@eslint/core": "^0.7.0", "@eslint/eslintrc": "^3.1.0", - "@eslint/js": "9.10.0", - "@eslint/plugin-kit": "^0.1.0", + "@eslint/js": "9.13.0", + "@eslint/plugin-kit": "^0.2.0", + "@humanfs/node": "^0.16.5", "@humanwhocodes/module-importer": "^1.0.1", - "@humanwhocodes/retry": "^0.3.0", - "@nodelib/fs.walk": "^1.2.8", + "@humanwhocodes/retry": "^0.3.1", + "@types/estree": "^1.0.6", + "@types/json-schema": "^7.0.15", "ajv": "^6.12.4", "chalk": "^4.0.0", "cross-spawn": "^7.0.2", "debug": "^4.3.2", "escape-string-regexp": "^4.0.0", - "eslint-scope": "^8.0.2", - "eslint-visitor-keys": "^4.0.0", - "espree": "^10.1.0", + "eslint-scope": "^8.1.0", + "eslint-visitor-keys": "^4.1.0", + "espree": "^10.2.0", "esquery": "^1.5.0", "esutils": "^2.0.2", "fast-deep-equal": "^3.1.3", @@ -1787,13 +1798,11 @@ "ignore": "^5.2.0", "imurmurhash": "^0.1.4", "is-glob": "^4.0.0", - "is-path-inside": "^3.0.3", "json-stable-stringify-without-jsonify": "^1.0.1", "lodash.merge": "^4.6.2", "minimatch": "^3.1.2", "natural-compare": "^1.4.0", "optionator": "^0.9.3", - "strip-ansi": "^6.0.1", "text-table": "^0.2.0" }, "bin": { @@ -1844,9 +1853,9 @@ } }, "node_modules/eslint-plugin-svelte": { - "version": "2.44.0", - "resolved": "https://registry.npmjs.org/eslint-plugin-svelte/-/eslint-plugin-svelte-2.44.0.tgz", - "integrity": "sha512-wav4MOs02vBb1WjvTCYItwJCxMkuk2Z4p+K/eyjL0N/z7ahXLP+0LtQQjiKc2ezuif7GnZLbD1F3o1VHzSvdVg==", + "version": "2.45.1", + "resolved": "https://registry.npmjs.org/eslint-plugin-svelte/-/eslint-plugin-svelte-2.45.1.tgz", + "integrity": "sha512-mYAKNDRji0YWl7o00KQi0enREcrtzcN7xwK/8lwk5uLRoKLjzPXc+WjngsYpPV35I3AF7UlXc1+JfyNMJS+njA==", "dev": true, "license": "MIT", "dependencies": { @@ -1860,7 +1869,7 @@ "postcss-safe-parser": "^6.0.0", "postcss-selector-parser": "^6.1.0", "semver": "^7.6.2", - "svelte-eslint-parser": "^0.41.1" + "svelte-eslint-parser": "^0.42.0" }, "engines": { "node": "^14.17.0 || >=16.0.0" @@ -1879,9 +1888,9 @@ } }, "node_modules/eslint-scope": { - "version": "8.0.2", - "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-8.0.2.tgz", - "integrity": "sha512-6E4xmrTw5wtxnLA5wYL3WDfhZ/1bUBGOXV0zQvVRDOtrR8D0p6W7fs3JweNYhwRYeGvd/1CKX2se0/2s7Q/nJA==", + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-8.1.0.tgz", + "integrity": "sha512-14dSvlhaVhKKsa9Fx1l8A17s7ah7Ef7wCakJ10LYk6+GYmP9yDti2oq2SEwcyndt6knfcZyhyxwY3i9yL78EQw==", "dev": true, "license": "BSD-2-Clause", "dependencies": { @@ -1896,9 +1905,9 @@ } }, "node_modules/eslint-visitor-keys": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.0.0.tgz", - "integrity": "sha512-OtIRv/2GyiF6o/d8K7MYKKbXrOUBIK6SfkIRM4Z0dY3w+LiQ0vy3F57m0Z71bjbyeiWFiHJ8brqnmE6H6/jEuw==", + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.1.0.tgz", + "integrity": "sha512-Q7lok0mqMUSf5a/AdAZkA5a/gHcO6snwQClVNNvFKCAVlxXucdU8pKydU5ZVZjBx5xr37vGbFFWtLQYreLzrZg==", "dev": true, "license": "Apache-2.0", "engines": { @@ -1916,15 +1925,15 @@ "license": "MIT" }, "node_modules/espree": { - "version": "10.1.0", - "resolved": "https://registry.npmjs.org/espree/-/espree-10.1.0.tgz", - "integrity": "sha512-M1M6CpiE6ffoigIOWYO9UDP8TMUw9kqb21tf+08IgDYjCsOvCuDt4jQcZmoYxx+w7zlKw9/N0KXfto+I8/FrXA==", + "version": "10.2.0", + "resolved": "https://registry.npmjs.org/espree/-/espree-10.2.0.tgz", + "integrity": "sha512-upbkBJbckcCNBDBDXEbuhjbP68n+scUd3k/U2EkyM9nw+I/jPiL4cLF/Al06CF96wRltFda16sxDFrxsI1v0/g==", "dev": true, "license": "BSD-2-Clause", "dependencies": { "acorn": "^8.12.0", "acorn-jsx": "^5.3.2", - "eslint-visitor-keys": "^4.0.0" + "eslint-visitor-keys": "^4.1.0" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -2151,9 +2160,9 @@ } }, "node_modules/form-data": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", - "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==", + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.1.tgz", + "integrity": "sha512-tzN8e4TX8+kkxGPK8D5u0FNmjPUjw3lwC9lSLxxoB/+GtsJG91CO8bSWy73APlgAZzZbXEYZJuxjkHH2w+Ezhw==", "license": "MIT", "dependencies": { "asynckit": "^0.4.0", @@ -2264,9 +2273,9 @@ } }, "node_modules/globals": { - "version": "15.9.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-15.9.0.tgz", - "integrity": "sha512-SmSKyLLKFbSr6rptvP8izbyxJL4ILwqO9Jg23UA0sDlGlu58V59D1//I3vlc0KJphVdUR7vMjHIplYnzBxorQA==", + "version": "15.11.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-15.11.0.tgz", + "integrity": "sha512-yeyNSjdbyVaWurlwCpcA6XNBrHTMIeDdj0/hnvX/OLJ9ekOXYbLsLinH/MucQyGvNnXhidTdNhTtJaffL2sMfw==", "dev": true, "license": "MIT", "engines": { @@ -2433,16 +2442,6 @@ "node": ">=0.12.0" } }, - "node_modules/is-path-inside": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-3.0.3.tgz", - "integrity": "sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, "node_modules/is-reference": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/is-reference/-/is-reference-3.0.2.tgz", @@ -2614,9 +2613,9 @@ "license": "ISC" }, "node_modules/magic-string": { - "version": "0.30.11", - "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.11.tgz", - "integrity": "sha512-+Wri9p0QHMy+545hKww7YAu5NyzF8iomPL/RQazugQ9+Ez4Ic3mERMd8ZTX5rfK944j+560ZJi8iAwgak1Ac7A==", + "version": "0.30.12", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.12.tgz", + "integrity": "sha512-Ea8I3sQMVXr8JhN4z+H/d8zwo+tYDgHE9+5G4Wnrwhs0gaK9fXTKx0Tw5Xwsd/bCPTTZNRAdpyzvoeORe9LYpw==", "license": "MIT", "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.0" @@ -2881,9 +2880,9 @@ } }, "node_modules/package-json-from-dist": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.0.tgz", - "integrity": "sha512-dATvCeZN/8wQsGywez1mzHtTlP22H8OEfPrVMLNr4/eGa+ijtLn/6M5f0dY8UKNrC2O9UCU6SSoG3qRKnt7STw==", + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz", + "integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==", "dev": true, "license": "BlueOak-1.0.0" }, @@ -2956,9 +2955,9 @@ } }, "node_modules/picocolors": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.0.tgz", - "integrity": "sha512-TQ92mBOW0l3LeMeyLV6mzy/kWr8lkd/hp3mTg7wYK7zJhuBStmGMBG0BdeDZS/dZx1IukaX6Bk11zcln25o1Aw==", + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", "dev": true, "license": "ISC" }, @@ -3210,9 +3209,9 @@ } }, "node_modules/prettier-plugin-svelte": { - "version": "3.2.6", - "resolved": "https://registry.npmjs.org/prettier-plugin-svelte/-/prettier-plugin-svelte-3.2.6.tgz", - "integrity": "sha512-Y1XWLw7vXUQQZmgv1JAEiLcErqUniAF2wO7QJsw8BVMvpLET2dI5WpEIEJx1r11iHVdSMzQxivyfrH9On9t2IQ==", + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/prettier-plugin-svelte/-/prettier-plugin-svelte-3.2.7.tgz", + "integrity": "sha512-/Dswx/ea0lV34If1eDcG3nulQ63YNr5KPDfMsjbdtpSWOxKKJ7nAc2qlVuYwEvCr4raIuredNoR7K4JCkmTGaQ==", "dev": true, "license": "MIT", "peerDependencies": { @@ -3449,9 +3448,9 @@ } }, "node_modules/sirv": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/sirv/-/sirv-2.0.4.tgz", - "integrity": "sha512-94Bdh3cC2PKrbgSOUqTiGPWVZeSiXfKOVZNJniWoqrWrRkB1CJzBU3NEbiTsPcYy1lDsANA/THzS+9WBiy5nfQ==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/sirv/-/sirv-3.0.0.tgz", + "integrity": "sha512-BPwJGUeDaDCHihkORDchNyyTvWFhcusy1XMmhEVTQTwGeybFbp8YEmB+njbPnth1FibULBSBVwCQni25XlCUDg==", "dev": true, "license": "MIT", "dependencies": { @@ -3460,7 +3459,7 @@ "totalist": "^3.0.0" }, "engines": { - "node": ">= 10" + "node": ">=18" } }, "node_modules/source-map-js": { @@ -3506,6 +3505,16 @@ "node": ">=8" } }, + "node_modules/string-width-cjs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/string-width-cjs/node_modules/emoji-regex": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", @@ -3513,20 +3522,20 @@ "dev": true, "license": "MIT" }, - "node_modules/string-width/node_modules/ansi-regex": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.1.0.tgz", - "integrity": "sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA==", + "node_modules/string-width-cjs/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", "dev": true, "license": "MIT", - "engines": { - "node": ">=12" + "dependencies": { + "ansi-regex": "^5.0.1" }, - "funding": { - "url": "https://github.com/chalk/ansi-regex?sponsor=1" + "engines": { + "node": ">=8" } }, - "node_modules/string-width/node_modules/strip-ansi": { + "node_modules/strip-ansi": { "version": "7.1.0", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz", "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==", @@ -3542,7 +3551,8 @@ "url": "https://github.com/chalk/strip-ansi?sponsor=1" } }, - "node_modules/strip-ansi": { + "node_modules/strip-ansi-cjs": { + "name": "strip-ansi", "version": "6.0.1", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", @@ -3555,16 +3565,12 @@ "node": ">=8" } }, - "node_modules/strip-ansi-cjs": { - "name": "strip-ansi", - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "node_modules/strip-ansi-cjs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "dev": true, "license": "MIT", - "dependencies": { - "ansi-regex": "^5.0.1" - }, "engines": { "node": ">=8" } @@ -3657,9 +3663,9 @@ } }, "node_modules/svelte-eslint-parser": { - "version": "0.41.1", - "resolved": "https://registry.npmjs.org/svelte-eslint-parser/-/svelte-eslint-parser-0.41.1.tgz", - "integrity": "sha512-08ndI6zTghzI8SuJAFpvMbA/haPSGn3xz19pjre19yYMw8Nw/wQJ2PrZBI/L8ijGTgtkWCQQiLLy+Z1tfaCwNA==", + "version": "0.42.0", + "resolved": "https://registry.npmjs.org/svelte-eslint-parser/-/svelte-eslint-parser-0.42.0.tgz", + "integrity": "sha512-e7LyqFPTuF43ZYhKOf0Gq1lzP+G64iWVJXAIcwVxohGx5FFyqdUkw7DEXNjZ+Fm+TAA98zPmDqWvgD1OpyMi5A==", "dev": true, "license": "MIT", "dependencies": { @@ -3759,9 +3765,9 @@ } }, "node_modules/tailwindcss": { - "version": "3.4.12", - "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.12.tgz", - "integrity": "sha512-Htf/gHj2+soPb9UayUNci/Ja3d8pTmu9ONTfh4QY8r3MATTZOzmv6UYWF7ZwikEIC8okpfqmGqrmDehua8mF8w==", + "version": "3.4.14", + "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.14.tgz", + "integrity": "sha512-IcSvOcTRcUtQQ7ILQL5quRDg7Xs93PdJEk1ZLbhhvJc7uj/OAhYOnruEiwnGgBvUtaUAJ8/mhSw1o8L2jCiENA==", "dev": true, "license": "MIT", "dependencies": { @@ -3846,9 +3852,9 @@ } }, "node_modules/tailwindcss/node_modules/yaml": { - "version": "2.5.1", - "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.5.1.tgz", - "integrity": "sha512-bLQOjaX/ADgQ20isPJRvF0iRUHIxVhYvr53Of7wGcWlO2jvtUlH5m87DsmulFVxRpNLOnI4tB6p/oh8D7kpn9Q==", + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.6.0.tgz", + "integrity": "sha512-a6ae//JvKDEra2kdi1qzCyrJW/WZCgFi8ydDV+eXExl95t+5R+ijnqHJbz9tmMh8FUjx3iv2fCQ4dclAQlO2UQ==", "dev": true, "license": "ISC", "bin": { @@ -3943,9 +3949,9 @@ } }, "node_modules/update-browserslist-db": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.1.0.tgz", - "integrity": "sha512-EdRAaAyk2cUE1wOf2DkEhzxqOQvFOoRJFNS6NeyJ01Gp2beMRpBAINjM2iDXE3KCuKhwnvHIQCJm6ThL2Z+HzQ==", + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.1.1.tgz", + "integrity": "sha512-R8UzCaa9Az+38REPiJ1tXlImTJXlVfgHZsglwBD/k6nj76ctsH1E3q4doGrukiLQd3sGQYu56r5+lo5r94l29A==", "dev": true, "funding": [ { @@ -3963,8 +3969,8 @@ ], "license": "MIT", "dependencies": { - "escalade": "^3.1.2", - "picocolors": "^1.0.1" + "escalade": "^3.2.0", + "picocolors": "^1.1.0" }, "bin": { "update-browserslist-db": "cli.js" @@ -3991,9 +3997,9 @@ "license": "MIT" }, "node_modules/vite": { - "version": "5.4.6", - "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.6.tgz", - "integrity": "sha512-IeL5f8OO5nylsgzd9tq4qD2QqI0k2CQLGrWD0rCN0EQJZpBK5vJAx0I+GDkMOXxQX/OfFHMuLIx6ddAxGX/k+Q==", + "version": "5.4.9", + "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.9.tgz", + "integrity": "sha512-20OVpJHh0PAM0oSOELa5GaZNWeDjcAvQjGXy2Uyr+Tp+/D2/Hdz6NLgpJLsarPTA2QJ6v8mX2P1ZfbsSKvdMkg==", "dev": true, "license": "MIT", "dependencies": { @@ -4128,6 +4134,16 @@ "url": "https://github.com/chalk/wrap-ansi?sponsor=1" } }, + "node_modules/wrap-ansi-cjs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/wrap-ansi-cjs/node_modules/emoji-regex": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", @@ -4150,17 +4166,17 @@ "node": ">=8" } }, - "node_modules/wrap-ansi/node_modules/ansi-regex": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.1.0.tgz", - "integrity": "sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA==", + "node_modules/wrap-ansi-cjs/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", "dev": true, "license": "MIT", - "engines": { - "node": ">=12" + "dependencies": { + "ansi-regex": "^5.0.1" }, - "funding": { - "url": "https://github.com/chalk/ansi-regex?sponsor=1" + "engines": { + "node": ">=8" } }, "node_modules/wrap-ansi/node_modules/ansi-styles": { @@ -4176,22 +4192,6 @@ "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, - "node_modules/wrap-ansi/node_modules/strip-ansi": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz", - "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-regex": "^6.0.1" - }, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/strip-ansi?sponsor=1" - } - }, "node_modules/yaml": { "version": "1.10.2", "resolved": "https://registry.npmjs.org/yaml/-/yaml-1.10.2.tgz", diff --git a/package.json b/package.json index ac8a0d0..ec8a66c 100644 --- a/package.json +++ b/package.json @@ -12,23 +12,23 @@ "devDependencies": { "@skeletonlabs/skeleton": "^2.10.2", "@skeletonlabs/tw-plugin": "^0.4.0", - "@sveltejs/adapter-auto": "^3.0.0", + "@sveltejs/adapter-auto": "^3.2.5", "@sveltejs/adapter-static": "^3.0.5", - "@sveltejs/kit": "^2.0.0", - "@sveltejs/vite-plugin-svelte": "^3.0.0", + "@sveltejs/kit": "^2.7.1", + "@sveltejs/vite-plugin-svelte": "^3.1.2", "@tailwindcss/forms": "^0.5.9", - "@types/eslint": "^9.6.0", + "@types/eslint": "^9.6.1", "autoprefixer": "^10.4.20", - "eslint": "^9.0.0", + "eslint": "^9.13.0", "eslint-config-prettier": "^9.1.0", - "eslint-plugin-svelte": "^2.36.0", - "globals": "^15.0.0", + "eslint-plugin-svelte": "^2.45.1", + "globals": "^15.11.0", "postcss": "^8.4.47", - "prettier": "^3.1.1", - "prettier-plugin-svelte": "^3.1.2", - "svelte": "^4.2.7", - "tailwindcss": "^3.4.12", - "vite": "^5.0.3" + "prettier": "^3.3.3", + "prettier-plugin-svelte": "^3.2.7", + "svelte": "^4.2.19", + "tailwindcss": "^3.4.14", + "vite": "^5.4.9" }, "type": "module", "dependencies": { @@ -5,14 +5,12 @@ use crate::{ channel::app::Channels, event::{self, app::Events}, invite::app::Invites, + login::app::Logins, message::app::Messages, setup::app::Setup, token::{self, app::Tokens}, }; -#[cfg(test)] -use crate::login::app::Logins; - #[derive(Clone)] pub struct App { db: SqlitePool, @@ -49,6 +47,11 @@ impl App { Invites::new(&self.db) } + #[cfg(not(test))] + pub const fn logins(&self) -> Logins { + Logins::new(&self.db) + } + #[cfg(test)] pub const fn logins(&self) -> Logins { Logins::new(&self.db, &self.events) diff --git a/src/bin/hi-recanonicalize.rs b/src/bin/hi-recanonicalize.rs new file mode 100644 index 0000000..4081276 --- /dev/null +++ b/src/bin/hi-recanonicalize.rs @@ -0,0 +1,9 @@ +use clap::Parser; + +use hi::cli; + +#[tokio::main] +async fn main() -> Result<(), cli::recanonicalize::Error> { + let args = cli::recanonicalize::Args::parse(); + args.run().await +} diff --git a/src/main.rs b/src/bin/hi.rs index d0830ff..d0830ff 100644 --- a/src/main.rs +++ b/src/bin/hi.rs diff --git a/src/boot/app.rs b/src/boot/app.rs index ef48b2f..e716b58 100644 --- a/src/boot/app.rs +++ b/src/boot/app.rs @@ -2,8 +2,11 @@ use sqlx::sqlite::SqlitePool; use super::Snapshot; use crate::{ - channel::repo::Provider as _, event::repo::Provider as _, login::repo::Provider as _, + channel::{self, repo::Provider as _}, + event::repo::Provider as _, + login::{self, repo::Provider as _}, message::repo::Provider as _, + name, }; pub struct Boot<'a> { @@ -15,12 +18,12 @@ impl<'a> Boot<'a> { Self { db } } - pub async fn snapshot(&self) -> Result<Snapshot, sqlx::Error> { + pub async fn snapshot(&self) -> Result<Snapshot, Error> { let mut tx = self.db.begin().await?; let resume_point = tx.sequence().current().await?; let logins = tx.logins().all(resume_point.into()).await?; - let channels = tx.channels().all(resume_point.into()).await?; + let channels = tx.channels().all(resume_point).await?; let messages = tx.messages().all(resume_point.into()).await?; tx.commit().await?; @@ -48,3 +51,30 @@ impl<'a> Boot<'a> { }) } } + +#[derive(Debug, thiserror::Error)] +#[error(transparent)] +pub enum Error { + Name(#[from] name::Error), + Database(#[from] sqlx::Error), +} + +impl From<login::repo::LoadError> for Error { + fn from(error: login::repo::LoadError) -> Self { + use login::repo::LoadError; + match error { + LoadError::Name(error) => error.into(), + LoadError::Database(error) => error.into(), + } + } +} + +impl From<channel::repo::LoadError> for Error { + fn from(error: channel::repo::LoadError) -> Self { + use channel::repo::LoadError; + match error { + LoadError::Name(error) => error.into(), + LoadError::Database(error) => error.into(), + } + } +} diff --git a/src/boot/routes.rs b/src/boot/routes.rs deleted file mode 100644 index 80f70bd..0000000 --- a/src/boot/routes.rs +++ /dev/null @@ -1,27 +0,0 @@ -use axum::{ - extract::{Json, State}, - routing::get, - Router, -}; - -use super::Snapshot; -use crate::{app::App, error::Internal, login::Login}; - -#[cfg(test)] -mod test; - -pub fn router() -> Router<App> { - Router::new().route("/api/boot", get(boot)) -} - -async fn boot(State(app): State<App>, login: Login) -> Result<Json<Boot>, Internal> { - let snapshot = app.boot().snapshot().await?; - Ok(Boot { login, snapshot }.into()) -} - -#[derive(serde::Serialize)] -struct Boot { - login: Login, - #[serde(flatten)] - snapshot: Snapshot, -} diff --git a/src/boot/routes/get.rs b/src/boot/routes/get.rs new file mode 100644 index 0000000..563fbf1 --- /dev/null +++ b/src/boot/routes/get.rs @@ -0,0 +1,27 @@ +use axum::{ + extract::{Json, State}, + response::{self, IntoResponse}, +}; + +use crate::{app::App, boot::Snapshot, error::Internal, login::Login, token::extract::Identity}; + +pub async fn handler(State(app): State<App>, identity: Identity) -> Result<Response, Internal> { + let snapshot = app.boot().snapshot().await?; + Ok(Response { + login: identity.login, + snapshot, + }) +} + +#[derive(serde::Serialize)] +pub struct Response { + pub login: Login, + #[serde(flatten)] + pub snapshot: Snapshot, +} + +impl IntoResponse for Response { + fn into_response(self) -> response::Response { + Json(self).into_response() + } +} diff --git a/src/boot/routes/mod.rs b/src/boot/routes/mod.rs new file mode 100644 index 0000000..e4d5ac8 --- /dev/null +++ b/src/boot/routes/mod.rs @@ -0,0 +1,11 @@ +use axum::{routing::get, Router}; + +use crate::app::App; + +mod get; +#[cfg(test)] +mod test; + +pub fn router() -> Router<App> { + Router::new().route("/api/boot", get(get::handler)) +} diff --git a/src/boot/routes/test.rs b/src/boot/routes/test.rs index 5f2ba6f..8808b70 100644 --- a/src/boot/routes/test.rs +++ b/src/boot/routes/test.rs @@ -1,14 +1,134 @@ -use axum::extract::{Json, State}; +use axum::extract::State; -use crate::{boot::routes, test::fixtures}; +use super::get; +use crate::test::fixtures; #[tokio::test] async fn returns_identity() { let app = fixtures::scratch_app().await; - let login = fixtures::login::fictitious(); - let Json(response) = routes::boot(State(app), login.clone()) + + let viewer = fixtures::identity::fictitious(); + let response = get::handler(State(app), viewer.clone()) + .await + .expect("boot always succeeds"); + + assert_eq!(viewer.login, response.login); +} + +#[tokio::test] +async fn includes_logins() { + let app = fixtures::scratch_app().await; + let spectator = fixtures::login::create(&app, &fixtures::now()).await; + + let viewer = fixtures::identity::fictitious(); + let response = get::handler(State(app), viewer) + .await + .expect("boot always succeeds"); + + assert!(response.snapshot.logins.contains(&spectator)); +} + +#[tokio::test] +async fn includes_channels() { + let app = fixtures::scratch_app().await; + let channel = fixtures::channel::create(&app, &fixtures::now()).await; + + let viewer = fixtures::identity::fictitious(); + let response = get::handler(State(app), viewer) + .await + .expect("boot always succeeds"); + + assert!(response.snapshot.channels.contains(&channel)); +} + +#[tokio::test] +async fn includes_messages() { + let app = fixtures::scratch_app().await; + let sender = fixtures::login::create(&app, &fixtures::now()).await; + let channel = fixtures::channel::create(&app, &fixtures::now()).await; + let message = fixtures::message::send(&app, &channel, &sender, &fixtures::now()).await; + + let viewer = fixtures::identity::fictitious(); + let response = get::handler(State(app), viewer) + .await + .expect("boot always succeeds"); + + assert!(response.snapshot.messages.contains(&message)); +} + +#[tokio::test] +async fn excludes_expired_messages() { + let app = fixtures::scratch_app().await; + let sender = fixtures::login::create(&app, &fixtures::ancient()).await; + let channel = fixtures::channel::create(&app, &fixtures::ancient()).await; + let expired_message = + fixtures::message::send(&app, &channel, &sender, &fixtures::ancient()).await; + + app.messages() + .expire(&fixtures::now()) + .await + .expect("expiry never fails"); + + let viewer = fixtures::identity::fictitious(); + let response = get::handler(State(app), viewer) + .await + .expect("boot always succeeds"); + + assert!(!response.snapshot.messages.contains(&expired_message)); +} + +#[tokio::test] +async fn excludes_deleted_messages() { + let app = fixtures::scratch_app().await; + let sender = fixtures::login::create(&app, &fixtures::now()).await; + let channel = fixtures::channel::create(&app, &fixtures::now()).await; + let deleted_message = fixtures::message::send(&app, &channel, &sender, &fixtures::now()).await; + + app.messages() + .delete(&deleted_message.id, &fixtures::now()) + .await + .expect("deleting valid message succeeds"); + + let viewer = fixtures::identity::fictitious(); + let response = get::handler(State(app), viewer) + .await + .expect("boot always succeeds"); + + assert!(!response.snapshot.messages.contains(&deleted_message)); +} + +#[tokio::test] +async fn excludes_expired_channels() { + let app = fixtures::scratch_app().await; + let expired_channel = fixtures::channel::create(&app, &fixtures::ancient()).await; + + app.channels() + .expire(&fixtures::now()) + .await + .expect("expiry never fails"); + + let viewer = fixtures::identity::fictitious(); + let response = get::handler(State(app), viewer) + .await + .expect("boot always succeeds"); + + assert!(!response.snapshot.channels.contains(&expired_channel)); +} + +#[tokio::test] +async fn excludes_deleted_channels() { + let app = fixtures::scratch_app().await; + let deleted_channel = fixtures::channel::create(&app, &fixtures::now()).await; + + app.channels() + .delete(&deleted_channel.id, &fixtures::now()) + .await + .expect("deleting a valid channel succeeds"); + + let viewer = fixtures::identity::fictitious(); + let response = get::handler(State(app), viewer) .await .expect("boot always succeeds"); - assert_eq!(login, response.login); + assert!(!response.snapshot.channels.contains(&deleted_channel)); } diff --git a/src/channel/app.rs b/src/channel/app.rs index 5d6cada..7bfa0f7 100644 --- a/src/channel/app.rs +++ b/src/channel/app.rs @@ -2,12 +2,16 @@ use chrono::TimeDelta; use itertools::Itertools; use sqlx::sqlite::SqlitePool; -use super::{repo::Provider as _, Channel, History, Id}; +use super::{ + repo::{LoadError, Provider as _}, + Channel, History, Id, +}; use crate::{ clock::DateTime, db::{Duplicate as _, NotFound as _}, event::{repo::Provider as _, Broadcaster, Event, Sequence}, message::repo::Provider as _, + name::{self, Name}, }; pub struct Channels<'a> { @@ -20,14 +24,14 @@ impl<'a> Channels<'a> { Self { db, events } } - pub async fn create(&self, name: &str, created_at: &DateTime) -> Result<Channel, CreateError> { + pub async fn create(&self, name: &Name, created_at: &DateTime) -> Result<Channel, CreateError> { let mut tx = self.db.begin().await?; let created = tx.sequence().next(created_at).await?; let channel = tx .channels() .create(name, &created) .await - .duplicate(|| CreateError::DuplicateName(name.into()))?; + .duplicate(|| CreateError::DuplicateName(name.clone()))?; tx.commit().await?; self.events @@ -38,12 +42,12 @@ impl<'a> Channels<'a> { // This function is careless with respect to time, and gets you the channel as // it exists in the specific moment when you call it. - pub async fn get(&self, channel: &Id) -> Result<Option<Channel>, sqlx::Error> { + pub async fn get(&self, channel: &Id) -> Result<Option<Channel>, Error> { let mut tx = self.db.begin().await?; 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 +58,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 +77,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() @@ -85,7 +92,7 @@ impl<'a> Channels<'a> { Ok(()) } - pub async fn expire(&self, relative_to: &DateTime) -> Result<(), sqlx::Error> { + pub async fn expire(&self, relative_to: &DateTime) -> Result<(), ExpireError> { // Somewhat arbitrarily, expire after 90 days. let expire_at = relative_to.to_owned() - TimeDelta::days(90); @@ -115,26 +122,80 @@ 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(()) + } + + pub async fn recanonicalize(&self) -> Result<(), sqlx::Error> { + let mut tx = self.db.begin().await?; + tx.channels().recanonicalize().await?; + tx.commit().await?; + + Ok(()) + } } #[derive(Debug, thiserror::Error)] pub enum CreateError { #[error("channel named {0} already exists")] - DuplicateName(String), + DuplicateName(Name), + #[error(transparent)] + Database(#[from] sqlx::Error), #[error(transparent)] - DatabaseError(#[from] sqlx::Error), + Name(#[from] name::Error), +} + +impl From<LoadError> for CreateError { + fn from(error: LoadError) -> Self { + match error { + LoadError::Database(error) => error.into(), + LoadError::Name(error) => error.into(), + } + } } #[derive(Debug, thiserror::Error)] pub enum Error { #[error("channel {0} not found")] NotFound(Id), + #[error("channel {0} deleted")] + Deleted(Id), #[error(transparent)] - DatabaseError(#[from] sqlx::Error), + Database(#[from] sqlx::Error), + #[error(transparent)] + Name(#[from] name::Error), +} + +impl From<LoadError> for Error { + fn from(error: LoadError) -> Self { + match error { + LoadError::Database(error) => error.into(), + LoadError::Name(error) => error.into(), + } + } } #[derive(Debug, thiserror::Error)] -pub enum InternalError { +pub enum ExpireError { #[error(transparent)] - DatabaseError(#[from] sqlx::Error), + Database(#[from] sqlx::Error), + #[error(transparent)] + Name(#[from] name::Error), +} + +impl From<LoadError> for ExpireError { + fn from(error: LoadError) -> Self { + match error { + LoadError::Database(error) => error.into(), + LoadError::Name(error) => error.into(), + } + } } 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<Channel> { + self.events().collect() + } } // Event factories diff --git a/src/channel/repo.rs b/src/channel/repo.rs index 2f57581..a49db52 100644 --- a/src/channel/repo.rs +++ b/src/channel/repo.rs @@ -1,9 +1,12 @@ +use futures::stream::{StreamExt as _, TryStreamExt as _}; use sqlx::{sqlite::Sqlite, SqliteConnection, Transaction}; use crate::{ channel::{Channel, History, Id}, clock::DateTime, + db::NotFound, event::{Instant, ResumePoint, Sequence}, + name::{self, Name}, }; pub trait Provider { @@ -19,130 +22,162 @@ impl<'c> Provider for Transaction<'c, Sqlite> { pub struct Channels<'t>(&'t mut SqliteConnection); impl<'c> Channels<'c> { - pub async fn create(&mut self, name: &str, created: &Instant) -> Result<History, sqlx::Error> { + pub async fn create(&mut self, name: &Name, created: &Instant) -> Result<History, sqlx::Error> { let id = Id::generate(); - let channel = sqlx::query!( + let name = name.clone(); + let display_name = name.display(); + let canonical_name = name.canonical(); + let created = *created; + + sqlx::query!( r#" insert - into channel (id, name, created_at, created_sequence) - values ($1, $2, $3, $4) - returning - id as "id: Id", - name, - created_at as "created_at: DateTime", - created_sequence as "created_sequence: Sequence" + into channel (id, created_at, created_sequence) + values ($1, $2, $3) "#, id, - name, created.at, created.sequence, ) - .map(|row| History { + .execute(&mut *self.0) + .await?; + + sqlx::query!( + r#" + insert into channel_name (id, display_name, canonical_name) + values ($1, $2, $3) + "#, + id, + display_name, + canonical_name, + ) + .execute(&mut *self.0) + .await?; + + let channel = History { channel: Channel { - id: row.id, - name: row.name, - }, - created: Instant { - at: row.created_at, - sequence: row.created_sequence, + id, + name: name.clone(), + deleted_at: None, }, + created, deleted: None, - }) - .fetch_one(&mut *self.0) - .await?; + }; Ok(channel) } - pub async fn by_id(&mut self, channel: &Id) -> Result<History, sqlx::Error> { + pub async fn by_id(&mut self, channel: &Id) -> Result<History, LoadError> { let channel = sqlx::query!( r#" select id as "id: Id", - name, - created_at as "created_at: DateTime", - created_sequence as "created_sequence: Sequence" + name.display_name as "display_name?: String", + name.canonical_name as "canonical_name?: String", + 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_name as name + using (id) + left join channel_deleted as deleted + using (id) where id = $1 "#, channel, ) - .map(|row| History { - channel: Channel { - id: row.id, - name: row.name, - }, - created: Instant { - at: row.created_at, - sequence: row.created_sequence, - }, - deleted: None, + .map(|row| { + Ok::<_, name::Error>(History { + channel: Channel { + id: row.id, + name: Name::optional(row.display_name, row.canonical_name)?.unwrap_or_default(), + deleted_at: row.deleted_at, + }, + created: Instant::new(row.created_at, row.created_sequence), + deleted: Instant::optional(row.deleted_at, row.deleted_sequence), + }) }) .fetch_one(&mut *self.0) - .await?; + .await??; Ok(channel) } - pub async fn all(&mut self, resume_at: ResumePoint) -> Result<Vec<History>, sqlx::Error> { + pub async fn all(&mut self, resume_at: Sequence) -> Result<Vec<History>, LoadError> { let channels = sqlx::query!( r#" select id as "id: Id", - name, - created_at as "created_at: DateTime", - created_sequence as "created_sequence: Sequence" + name.display_name as "display_name?: String", + name.canonical_name as "canonical_name?: String", + 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) - order by channel.name + left join channel_name as name + using (id) + left join channel_deleted as deleted + using (id) + where channel.created_sequence <= $1 + order by name.canonical_name "#, resume_at, ) - .map(|row| History { - channel: Channel { - id: row.id, - name: row.name, - }, - created: Instant { - at: row.created_at, - sequence: row.created_sequence, - }, - deleted: None, + .map(|row| { + Ok::<_, name::Error>(History { + channel: Channel { + id: row.id, + name: Name::optional(row.display_name, row.canonical_name)?.unwrap_or_default(), + 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) + .fetch(&mut *self.0) + .map(|res| Ok::<_, LoadError>(res??)) + .try_collect() .await?; Ok(channels) } - pub async fn replay( - &mut self, - resume_at: Option<Sequence>, - ) -> Result<Vec<History>, sqlx::Error> { + pub async fn replay(&mut self, resume_at: ResumePoint) -> Result<Vec<History>, LoadError> { let channels = sqlx::query!( r#" select id as "id: Id", - name, - created_at as "created_at: DateTime", - created_sequence as "created_sequence: Sequence" + name.display_name as "display_name: String", + name.canonical_name as "canonical_name: String", + 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_name as name + using (id) + left join channel_deleted as deleted + using (id) + where coalesce(channel.created_sequence > $1, true) "#, resume_at, ) - .map(|row| History { - channel: Channel { - id: row.id, - name: row.name, - }, - created: Instant { - at: row.created_at, - sequence: row.created_sequence, - }, - deleted: None, + .map(|row| { + Ok::<_, name::Error>(History { + channel: Channel { + id: row.id, + name: Name::optional(row.display_name, row.canonical_name)?.unwrap_or_default(), + 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) + .fetch(&mut *self.0) + .map(|res| Ok::<_, LoadError>(res??)) + .try_collect() .await?; Ok(channels) @@ -150,53 +185,171 @@ impl<'c> Channels<'c> { pub async fn delete( &mut self, - channel: &Id, + channel: &History, deleted: &Instant, - ) -> Result<History, sqlx::Error> { - let channel = sqlx::query!( + ) -> Result<History, LoadError> { + let id = channel.id(); + sqlx::query!( r#" - delete from channel + insert into channel_deleted (id, deleted_at, deleted_sequence) + values ($1, $2, $3) + "#, + id, + deleted.at, + deleted.sequence, + ) + .execute(&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. + // + // This also avoids the need for a separate name reservation table to ensure + // that live channels have unique names, since the `channel` table's name field + // is unique over non-null values. + sqlx::query!( + r#" + delete from channel_name where id = $1 - returning - id as "id: Id", - name, - created_at as "created_at: DateTime", - created_sequence as "created_sequence: Sequence" "#, - channel, + 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) + .execute(&mut *self.0) .await?; + let channel = self.by_id(id).await?; + Ok(channel) } - pub async fn expired(&mut self, expired_at: &DateTime) -> Result<Vec<Id>, 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<Vec<History>, LoadError> { + let channels = sqlx::query!( + r#" select - channel.id as "id: Id" + channel.id as "id: Id", + name.display_name as "display_name?: String", + name.canonical_name as "canonical_name?: String", + 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_name as name + using (id) + left join channel_deleted as deleted + using (id) + left join message + on channel.id = message.channel + where channel.created_at < $1 and message.id is null + and deleted.id is null "#, expired_at, ) - .fetch_all(&mut *self.0) + .map(|row| { + Ok::<_, name::Error>(History { + channel: Channel { + id: row.id, + name: Name::optional(row.display_name, row.canonical_name)?.unwrap_or_default(), + deleted_at: row.deleted_at, + }, + created: Instant::new(row.created_at, row.created_sequence), + deleted: Instant::optional(row.deleted_at, row.deleted_sequence), + }) + }) + .fetch(&mut *self.0) + .map(|res| Ok::<_, LoadError>(res??)) + .try_collect() .await?; Ok(channels) } + + pub async fn recanonicalize(&mut self) -> Result<(), sqlx::Error> { + let channels = sqlx::query!( + r#" + select + id as "id: Id", + display_name as "display_name: String" + from channel_name + "#, + ) + .fetch_all(&mut *self.0) + .await?; + + for channel in channels { + let name = Name::from(channel.display_name); + let canonical_name = name.canonical(); + + sqlx::query!( + r#" + update channel_name + set canonical_name = $1 + where id = $2 + "#, + canonical_name, + channel.id, + ) + .execute(&mut *self.0) + .await?; + } + + Ok(()) + } +} + +#[derive(Debug, thiserror::Error)] +#[error(transparent)] +pub enum LoadError { + Database(#[from] sqlx::Error), + Name(#[from] name::Error), +} + +impl<T> NotFound for Result<T, LoadError> { + type Ok = T; + type Error = LoadError; + + fn optional(self) -> Result<Option<T>, LoadError> { + match self { + Ok(value) => Ok(Some(value)), + Err(LoadError::Database(sqlx::Error::RowNotFound)) => Ok(None), + Err(other) => Err(other), + } + } } diff --git a/src/channel/routes.rs b/src/channel/routes.rs deleted file mode 100644 index eaf7962..0000000 --- a/src/channel/routes.rs +++ /dev/null @@ -1,121 +0,0 @@ -use axum::{ - extract::{Json, Path, State}, - http::StatusCode, - response::{IntoResponse, Response}, - routing::{delete, post}, - Router, -}; - -use super::{app, Channel, Id}; -use crate::{ - app::App, - clock::RequestedAt, - error::{Internal, NotFound}, - login::Login, - message::app::SendError, -}; - -#[cfg(test)] -mod test; - -pub fn router() -> Router<App> { - Router::new() - .route("/api/channels", post(on_create)) - .route("/api/channels/:channel", post(on_send)) - .route("/api/channels/:channel", delete(on_delete)) -} - -#[derive(Clone, serde::Deserialize)] -struct CreateRequest { - name: String, -} - -async fn on_create( - State(app): State<App>, - _: Login, // requires auth, but doesn't actually care who you are - RequestedAt(created_at): RequestedAt, - Json(form): Json<CreateRequest>, -) -> Result<Json<Channel>, CreateError> { - let channel = app - .channels() - .create(&form.name, &created_at) - .await - .map_err(CreateError)?; - - Ok(Json(channel)) -} - -#[derive(Debug)] -struct CreateError(app::CreateError); - -impl IntoResponse for CreateError { - fn into_response(self) -> Response { - let Self(error) = self; - match error { - duplicate @ app::CreateError::DuplicateName(_) => { - (StatusCode::CONFLICT, duplicate.to_string()).into_response() - } - other => Internal::from(other).into_response(), - } - } -} - -#[derive(Clone, serde::Deserialize)] -struct SendRequest { - body: String, -} - -async fn on_send( - State(app): State<App>, - Path(channel): Path<Id>, - RequestedAt(sent_at): RequestedAt, - login: Login, - Json(request): Json<SendRequest>, -) -> Result<StatusCode, SendErrorResponse> { - app.messages() - .send(&channel, &login, &sent_at, &request.body) - .await?; - - Ok(StatusCode::ACCEPTED) -} - -#[derive(Debug, thiserror::Error)] -#[error(transparent)] -struct SendErrorResponse(#[from] SendError); - -impl IntoResponse for SendErrorResponse { - fn into_response(self) -> Response { - let Self(error) = self; - match error { - not_found @ SendError::ChannelNotFound(_) => NotFound(not_found).into_response(), - other => Internal::from(other).into_response(), - } - } -} - -async fn on_delete( - State(app): State<App>, - Path(channel): Path<Id>, - RequestedAt(deleted_at): RequestedAt, - _: Login, -) -> Result<StatusCode, ErrorResponse> { - app.channels().delete(&channel, &deleted_at).await?; - - Ok(StatusCode::ACCEPTED) -} - -#[derive(Debug, thiserror::Error)] -#[error(transparent)] -struct ErrorResponse(#[from] app::Error); - -impl IntoResponse for ErrorResponse { - fn into_response(self) -> Response { - let Self(error) = self; - match error { - not_found @ app::Error::NotFound(_) => { - (StatusCode::NOT_FOUND, not_found.to_string()).into_response() - } - other => Internal::from(other).into_response(), - } - } -} diff --git a/src/channel/routes/channel/delete.rs b/src/channel/routes/channel/delete.rs new file mode 100644 index 0000000..91eb506 --- /dev/null +++ b/src/channel/routes/channel/delete.rs @@ -0,0 +1,39 @@ +use axum::{ + extract::{Path, State}, + http::StatusCode, + response::{IntoResponse, Response}, +}; + +use crate::{ + app::App, + channel::app, + clock::RequestedAt, + error::{Internal, NotFound}, + token::extract::Identity, +}; + +pub async fn handler( + State(app): State<App>, + Path(channel): Path<super::PathInfo>, + RequestedAt(deleted_at): RequestedAt, + _: Identity, +) -> Result<StatusCode, Error> { + app.channels().delete(&channel, &deleted_at).await?; + + Ok(StatusCode::ACCEPTED) +} + +#[derive(Debug, thiserror::Error)] +#[error(transparent)] +pub struct Error(#[from] pub app::Error); + +impl IntoResponse for Error { + fn into_response(self) -> Response { + let Self(error) = self; + #[allow(clippy::match_wildcard_for_single_variants)] + match error { + app::Error::NotFound(_) | app::Error::Deleted(_) => NotFound(error).into_response(), + other => Internal::from(other).into_response(), + } + } +} diff --git a/src/channel/routes/channel/mod.rs b/src/channel/routes/channel/mod.rs new file mode 100644 index 0000000..31a9142 --- /dev/null +++ b/src/channel/routes/channel/mod.rs @@ -0,0 +1,9 @@ +use crate::channel::Id; + +pub mod delete; +pub mod post; + +#[cfg(test)] +mod test; + +type PathInfo = Id; diff --git a/src/channel/routes/channel/post.rs b/src/channel/routes/channel/post.rs new file mode 100644 index 0000000..b51e691 --- /dev/null +++ b/src/channel/routes/channel/post.rs @@ -0,0 +1,58 @@ +use axum::{ + extract::{Json, Path, State}, + http::StatusCode, + response::{self, IntoResponse}, +}; + +use crate::{ + app::App, + clock::RequestedAt, + error::{Internal, NotFound}, + message::{app::SendError, Body, Message}, + token::extract::Identity, +}; + +pub async fn handler( + State(app): State<App>, + Path(channel): Path<super::PathInfo>, + RequestedAt(sent_at): RequestedAt, + identity: Identity, + Json(request): Json<Request>, +) -> Result<Response, Error> { + let message = app + .messages() + .send(&channel, &identity.login, &sent_at, &request.body) + .await?; + + Ok(Response(message)) +} + +#[derive(serde::Deserialize)] +pub struct Request { + pub body: Body, +} + +#[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::Response { + let Self(error) = self; + #[allow(clippy::match_wildcard_for_single_variants)] + match error { + SendError::ChannelNotFound(_) => NotFound(error).into_response(), + other => Internal::from(other).into_response(), + } + } +} diff --git a/src/channel/routes/channel/test/delete.rs b/src/channel/routes/channel/test/delete.rs new file mode 100644 index 0000000..e9af12f --- /dev/null +++ b/src/channel/routes/channel/test/delete.rs @@ -0,0 +1,154 @@ +use axum::{ + extract::{Path, State}, + http::StatusCode, +}; + +use crate::{ + channel::{app, routes::channel::delete}, + test::fixtures, +}; + +#[tokio::test] +pub async fn delete_channel() { + // Set up the environment + + let app = fixtures::scratch_app().await; + let channel = fixtures::channel::create(&app, &fixtures::now()).await; + + // Send the request + + let deleter = fixtures::identity::create(&app, &fixtures::now()).await; + let response = delete::handler( + State(app.clone()), + Path(channel.id.clone()), + fixtures::now(), + deleter, + ) + .await + .expect("deleting a valid channel succeeds"); + + // Verify the response + + assert_eq!(response, StatusCode::ACCEPTED); + + // Verify the semantics + + let snapshot = app.boot().snapshot().await.expect("boot always succeeds"); + assert!(!snapshot.channels.contains(&channel)); +} + +#[tokio::test] +pub async fn delete_invalid_channel_id() { + // Set up the environment + + let app = fixtures::scratch_app().await; + + // Send the request + + let deleter = fixtures::identity::create(&app, &fixtures::now()).await; + let channel = fixtures::channel::fictitious(); + let delete::Error(error) = delete::handler( + State(app.clone()), + Path(channel.clone()), + fixtures::now(), + deleter, + ) + .await + .expect_err("deleting a nonexistent channel fails"); + + // Verify the response + + assert!(matches!(error, app::Error::NotFound(id) if id == channel)); +} + +#[tokio::test] +pub async fn delete_deleted() { + // Set up the environment + + let app = fixtures::scratch_app().await; + let channel = fixtures::channel::create(&app, &fixtures::now()).await; + + app.channels() + .delete(&channel.id, &fixtures::now()) + .await + .expect("deleting a recently-sent channel succeeds"); + + // Send the request + + let deleter = fixtures::identity::create(&app, &fixtures::now()).await; + let delete::Error(error) = delete::handler( + State(app.clone()), + Path(channel.id.clone()), + fixtures::now(), + deleter, + ) + .await + .expect_err("deleting a deleted channel fails"); + + // Verify the response + + assert!(matches!(error, app::Error::Deleted(id) if id == channel.id)); +} + +#[tokio::test] +pub async fn delete_expired() { + // Set up the environment + + let app = fixtures::scratch_app().await; + let channel = fixtures::channel::create(&app, &fixtures::ancient()).await; + + app.channels() + .expire(&fixtures::now()) + .await + .expect("expiring channels always succeeds"); + + // Send the request + + let deleter = fixtures::identity::create(&app, &fixtures::now()).await; + let delete::Error(error) = delete::handler( + State(app.clone()), + Path(channel.id.clone()), + fixtures::now(), + deleter, + ) + .await + .expect_err("deleting an expired channel fails"); + + // Verify the response + + assert!(matches!(error, app::Error::Deleted(id) if id == channel.id)); +} + +#[tokio::test] +pub async fn delete_purged() { + // Set up the environment + + let app = fixtures::scratch_app().await; + let channel = fixtures::channel::create(&app, &fixtures::ancient()).await; + + app.channels() + .expire(&fixtures::old()) + .await + .expect("expiring channels always succeeds"); + + app.channels() + .purge(&fixtures::now()) + .await + .expect("purging channels always succeeds"); + + // Send the request + + let deleter = fixtures::identity::create(&app, &fixtures::now()).await; + let delete::Error(error) = delete::handler( + State(app.clone()), + Path(channel.id.clone()), + fixtures::now(), + deleter, + ) + .await + .expect_err("deleting a purged channel fails"); + + // Verify the response + + assert!(matches!(error, app::Error::NotFound(id) if id == channel.id)); +} diff --git a/src/channel/routes/channel/test/mod.rs b/src/channel/routes/channel/test/mod.rs new file mode 100644 index 0000000..78bf86e --- /dev/null +++ b/src/channel/routes/channel/test/mod.rs @@ -0,0 +1,2 @@ +mod delete; +mod post; diff --git a/src/channel/routes/test/on_send.rs b/src/channel/routes/channel/test/post.rs index 293cc56..67e7d36 100644 --- a/src/channel/routes/test/on_send.rs +++ b/src/channel/routes/channel/test/post.rs @@ -2,9 +2,8 @@ use axum::extract::{Json, Path, State}; use futures::stream::StreamExt; use crate::{ - channel, - channel::routes, - event::{self, Sequenced}, + channel::{self, routes::channel::post}, + event::Sequenced, message::{self, app::SendError}, test::fixtures::{self, future::Immediately as _}, }; @@ -14,7 +13,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) @@ -25,17 +24,17 @@ async fn messages_in_order() { ]; for (sent_at, body) in &requests { - let request = routes::SendRequest { body: body.clone() }; + let request = post::Request { body: body.clone() }; - routes::on_send( + let _ = post::handler( State(app.clone()), Path(channel.id.clone()), sent_at.clone(), sender.clone(), - Json(request.clone()), + Json(request), ) .await - .expect("sending to a valid channel"); + .expect("sending to a valid channel succeeds"); } // Verify the semantics @@ -44,8 +43,8 @@ async fn messages_in_order() { .events() .subscribe(None) .await - .expect("subscribing to a valid channel") - .filter(fixtures::filter::messages()) + .expect("subscribing to a valid channel succeeds") + .filter_map(fixtures::message::events) .take(requests.len()); let events = events.collect::<Vec<_>>().immediately().await; @@ -54,8 +53,8 @@ async fn messages_in_order() { assert_eq!(*sent_at, event.at()); assert!(matches!( event, - event::Event::Message(message::Event::Sent(event)) - if event.message.sender == sender.id + message::Event::Sent(event) + if event.message.sender == sender.login.id && event.message.body == message )); } @@ -66,24 +65,62 @@ 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 let sent_at = fixtures::now(); let channel = channel::Id::generate(); - let request = routes::SendRequest { + let request = post::Request { body: fixtures::message::propose(), }; - let routes::SendErrorResponse(error) = routes::on_send( + let post::Error(error) = post::handler( 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/mod.rs b/src/channel/routes/mod.rs new file mode 100644 index 0000000..696bd72 --- /dev/null +++ b/src/channel/routes/mod.rs @@ -0,0 +1,19 @@ +use axum::{ + routing::{delete, post}, + Router, +}; + +use crate::app::App; + +mod channel; +mod post; + +#[cfg(test)] +mod test; + +pub fn router() -> Router<App> { + Router::new() + .route("/api/channels", post(post::handler)) + .route("/api/channels/:channel", post(channel::post::handler)) + .route("/api/channels/:channel", delete(channel::delete::handler)) +} diff --git a/src/channel/routes/post.rs b/src/channel/routes/post.rs new file mode 100644 index 0000000..810445c --- /dev/null +++ b/src/channel/routes/post.rs @@ -0,0 +1,60 @@ +use axum::{ + extract::{Json, State}, + http::StatusCode, + response::{self, IntoResponse}, +}; + +use crate::{ + app::App, + channel::{app, Channel}, + clock::RequestedAt, + error::Internal, + name::Name, + token::extract::Identity, +}; + +pub async fn handler( + State(app): State<App>, + _: Identity, // requires auth, but doesn't actually care who you are + RequestedAt(created_at): RequestedAt, + Json(request): Json<Request>, +) -> Result<Response, Error> { + let channel = app + .channels() + .create(&request.name, &created_at) + .await + .map_err(Error)?; + + Ok(Response(channel)) +} + +#[derive(serde::Deserialize)] +pub struct Request { + pub name: Name, +} + +#[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); + +impl IntoResponse for Error { + fn into_response(self) -> response::Response { + let Self(error) = self; + #[allow(clippy::match_wildcard_for_single_variants)] + match error { + app::CreateError::DuplicateName(_) => { + (StatusCode::CONFLICT, error.to_string()).into_response() + } + other => Internal::from(other).into_response(), + } + } +} diff --git a/src/channel/routes/test.rs b/src/channel/routes/test.rs new file mode 100644 index 0000000..216eba1 --- /dev/null +++ b/src/channel/routes/test.rs @@ -0,0 +1,221 @@ +use std::future; + +use axum::extract::{Json, State}; +use futures::stream::StreamExt as _; + +use super::post; +use crate::{ + channel::app, + name::Name, + 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::identity::create(&app, &fixtures::now()).await; + + // Call the endpoint + + let name = fixtures::channel::propose(); + let request = post::Request { name: name.clone() }; + 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 + + 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); +} + +#[tokio::test] +async fn duplicate_name() { + // Set up the environment + + let app = fixtures::scratch_app().await; + let creator = fixtures::identity::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 + )); +} + +#[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 + + let app = fixtures::scratch_app().await; + let creator = fixtures::identity::create(&app, &fixtures::now()).await; + let name = fixtures::channel::propose(); + + // Call the endpoint (first time) + + let request = post::Request { name: name.clone() }; + let post::Response(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 post::Response(response) = + post::handler(State(app.clone()), creator, fixtures::now(), Json(request)) + .await + .expect("creation succeeds after original channel deleted"); + + // 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); +} + +#[tokio::test] +async fn name_reusable_after_expiry() { + // Set up the environment + + 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("expiry always succeeds"); + + // 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); +} diff --git a/src/channel/routes/test/mod.rs b/src/channel/routes/test/mod.rs deleted file mode 100644 index 3e5aa17..0000000 --- a/src/channel/routes/test/mod.rs +++ /dev/null @@ -1,2 +0,0 @@ -mod on_create; -mod on_send; diff --git a/src/channel/routes/test/on_create.rs b/src/channel/routes/test/on_create.rs deleted file mode 100644 index eeecc7f..0000000 --- a/src/channel/routes/test/on_create.rs +++ /dev/null @@ -1,88 +0,0 @@ -use axum::extract::{Json, State}; -use futures::stream::StreamExt as _; - -use crate::{ - channel::{self, app, routes}, - 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 = routes::CreateRequest { name }; - let Json(response_channel) = routes::on_create( - State(app.clone()), - creator, - fixtures::now(), - Json(request.clone()), - ) - .await - .expect("new channel in an empty app"); - - // Verify the structure of the response - - assert_eq!(request.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 = routes::CreateRequest { name: channel.name }; - let routes::CreateError(error) = routes::on_create( - State(app.clone()), - creator, - fixtures::now(), - Json(request.clone()), - ) - .await - .expect_err("duplicate channel name"); - - // Verify the structure of the response - - assert!(matches!( - error, - app::CreateError::DuplicateName(name) if request.name == name - )); -} diff --git a/src/channel/snapshot.rs b/src/channel/snapshot.rs index d4d1d27..129c0d6 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, name::Name}; #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize)] pub struct Channel { pub id: Id, - pub name: String, + pub name: Name, + #[serde(skip_serializing_if = "Option::is_none")] + pub deleted_at: Option<DateTime>, } impl Channel { diff --git a/src/cli.rs b/src/cli/mod.rs index ade61ae..c75ce2b 100644 --- a/src/cli.rs +++ b/src/cli/mod.rs @@ -22,6 +22,8 @@ use crate::{ ui, }; +pub mod recanonicalize; + /// Command-line entry point for running the `hi` server. /// /// This is intended to be used as a Clap [Parser], to capture command-line @@ -164,7 +166,7 @@ fn started_msg(listener: &net::TcpListener) -> io::Result<String> { #[error(transparent)] pub enum Error { /// Failure due to `io::Error`. See [`io::Error`]. - IoError(#[from] io::Error), + Io(#[from] io::Error), /// Failure due to a database initialization error. See [`db::Error`]. Database(#[from] db::Error), } diff --git a/src/cli/recanonicalize.rs b/src/cli/recanonicalize.rs new file mode 100644 index 0000000..9db5b77 --- /dev/null +++ b/src/cli/recanonicalize.rs @@ -0,0 +1,86 @@ +use sqlx::sqlite::SqlitePool; + +use crate::{app::App, db}; + +/// Command-line entry point for repairing canonical names in the `hi` database. +/// This command may be necessary after an upgrade, if the canonical forms of +/// names has changed. It will re-calculate the canonical form of each name in +/// the database, based on its display form, and store the results back to the +/// database. +/// +/// This is intended to be used as a Clap [Parser], to capture command-line +/// arguments for the `hi-recanonicalize` command: +/// +/// ```no_run +/// # use hi::cli::recanonicalize::Error; +/// # +/// # #[tokio::main] +/// # async fn main() -> Result<(), Error> { +/// use clap::Parser; +/// use hi::cli::recanonicalize::Args; +/// +/// let args = Args::parse(); +/// args.run().await?; +/// # Ok(()) +/// # } +/// ``` +#[derive(clap::Parser)] +#[command( + version, + about = "Recanonicalize names in the `hi` database.", + long_about = r#"Recanonicalize names in the `hi` database. + +The `hi` server must not be running while this command is run. + +The database at `--database-url` will also be created, or upgraded, automatically."# +)] +pub struct Args { + /// Sqlite URL or path for the `hi` database + #[arg(short, long, env, default_value = "sqlite://.hi")] + database_url: String, + + /// Sqlite URL or path for a backup of the `hi` database during upgrades + #[arg(short = 'D', long, env, default_value = "sqlite://.hi.backup")] + backup_database_url: String, +} + +impl Args { + /// Recanonicalizes the `hi` database, using the parsed configuation in + /// `self`. + /// + /// This will perform the following tasks: + /// + /// * Migrate the `hi` database (at `--database-url`). + /// * Recanonicalize names in the `login` and `channel` tables. + /// + /// # Errors + /// + /// Will return `Err` if the canonicalization or database upgrade processes + /// fail. The specific [`Error`] variant will expose the cause + /// of the failure. + pub async fn run(self) -> Result<(), Error> { + let pool = self.pool().await?; + + let app = App::from(pool); + app.logins().recanonicalize().await?; + app.channels().recanonicalize().await?; + + Ok(()) + } + + async fn pool(&self) -> Result<SqlitePool, db::Error> { + db::prepare(&self.database_url, &self.backup_database_url).await + } +} + +/// Errors that can be raised by [`Args::run`]. +#[derive(Debug, thiserror::Error)] +#[error(transparent)] +pub enum Error { + // /// Failure due to `io::Error`. See [`io::Error`]. + // Io(#[from] io::Error), + /// Failure due to a database initialization error. See [`db::Error`]. + Database(#[from] db::Error), + /// Failure due to a data manipulation error. See [`sqlx::Error`]. + Sqlx(#[from] sqlx::Error), +} diff --git a/src/db/mod.rs b/src/db/mod.rs index 6005813..e0522d4 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -130,14 +130,17 @@ pub enum Error { Rejected(String, String), } -pub trait NotFound { +pub trait NotFound: Sized { type Ok; type Error; fn not_found<E, F>(self, map: F) -> Result<Self::Ok, E> where E: From<Self::Error>, - F: FnOnce() -> E; + F: FnOnce() -> E, + { + self.optional()?.ok_or_else(map) + } fn optional(self) -> Result<Option<Self::Ok>, Self::Error>; } @@ -153,14 +156,6 @@ impl<T> NotFound for Result<T, sqlx::Error> { Err(other) => Err(other), } } - - fn not_found<E, F>(self, map: F) -> Result<T, E> - where - E: From<sqlx::Error>, - F: FnOnce() -> E, - { - self.optional()?.ok_or_else(map) - } } pub trait Duplicate { diff --git a/src/error.rs b/src/error.rs index 85573d4..f3399c6 100644 --- a/src/error.rs +++ b/src/error.rs @@ -28,15 +28,20 @@ where } } +impl fmt::Display for Internal { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let Self(id, _) = self; + writeln!(f, "internal server error")?; + writeln!(f, "error id: {id}")?; + Ok(()) + } +} + impl IntoResponse for Internal { fn into_response(self) -> Response { - let Self(id, error) = self; + let Self(id, error) = &self; eprintln!("hi: [{id}] {error}"); - ( - StatusCode::INTERNAL_SERVER_ERROR, - format!("internal server error\nerror id: {id}"), - ) - .into_response() + (StatusCode::INTERNAL_SERVER_ERROR, self.to_string()).into_response() } } diff --git a/src/event/app.rs b/src/event/app.rs index 951ce25..c754388 100644 --- a/src/event/app.rs +++ b/src/event/app.rs @@ -11,6 +11,7 @@ use crate::{ channel::{self, repo::Provider as _}, login::{self, repo::Provider as _}, message::{self, repo::Provider as _}, + name, }; pub struct Events<'a> { @@ -26,7 +27,7 @@ impl<'a> Events<'a> { pub async fn subscribe( &self, resume_at: impl Into<ResumePoint>, - ) -> Result<impl Stream<Item = Event> + std::fmt::Debug, sqlx::Error> { + ) -> Result<impl Stream<Item = Event> + std::fmt::Debug, Error> { let resume_at = resume_at.into(); // Subscribe before retrieving, to catch messages broadcast while we're // querying the DB. We'll prune out duplicates later. @@ -81,3 +82,30 @@ impl<'a> Events<'a> { move |event| future::ready(filter(event)) } } + +#[derive(Debug, thiserror::Error)] +#[error(transparent)] +pub enum Error { + Database(#[from] sqlx::Error), + Name(#[from] name::Error), +} + +impl From<login::repo::LoadError> for Error { + fn from(error: login::repo::LoadError) -> Self { + use login::repo::LoadError; + match error { + LoadError::Database(error) => error.into(), + LoadError::Name(error) => error.into(), + } + } +} + +impl From<channel::repo::LoadError> for Error { + fn from(error: channel::repo::LoadError) -> Self { + use channel::repo::LoadError; + match error { + LoadError::Database(error) => error.into(), + LoadError::Name(error) => error.into(), + } + } +} 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<Sequence, sqlx::Error> { diff --git a/src/event/routes.rs b/src/event/routes/get.rs index de6d248..22e8762 100644 --- a/src/event/routes.rs +++ b/src/event/routes/get.rs @@ -1,41 +1,27 @@ use axum::{ extract::State, response::{ + self, sse::{self, Sse}, - IntoResponse, Response, + IntoResponse, }, - routing::get, - Router, }; use axum_extra::extract::Query; use futures::stream::{Stream, StreamExt as _}; -use super::{extract::LastEventId, Event}; use crate::{ app::App, error::{Internal, Unauthorized}, - event::{ResumePoint, Sequence, Sequenced as _}, + event::{app, extract::LastEventId, Event, ResumePoint, Sequence, Sequenced as _}, token::{app::ValidateError, extract::Identity}, }; -#[cfg(test)] -mod test; - -pub fn router() -> Router<App> { - Router::new().route("/api/events", get(events)) -} - -#[derive(Default, serde::Deserialize)] -struct EventsQuery { - resume_point: ResumePoint, -} - -async fn events( +pub async fn handler( State(app): State<App>, identity: Identity, last_event_id: Option<LastEventId<Sequence>>, - Query(query): Query<EventsQuery>, -) -> Result<Events<impl Stream<Item = Event> + std::fmt::Debug>, EventsError> { + Query(query): Query<QueryParams>, +) -> Result<Response<impl Stream<Item = Event> + std::fmt::Debug>, Error> { let resume_at = last_event_id .map(LastEventId::into_inner) .or(query.resume_point); @@ -43,17 +29,22 @@ async fn events( let stream = app.events().subscribe(resume_at).await?; let stream = app.tokens().limit_stream(identity.token, stream).await?; - Ok(Events(stream)) + Ok(Response(stream)) +} + +#[derive(Default, serde::Deserialize)] +pub struct QueryParams { + pub resume_point: ResumePoint, } #[derive(Debug)] -struct Events<S>(S); +pub struct Response<S>(pub S); -impl<S> IntoResponse for Events<S> +impl<S> IntoResponse for Response<S> where S: Stream<Item = Event> + Send + 'static, { - fn into_response(self) -> Response { + fn into_response(self) -> response::Response { let Self(stream) = self; let stream = stream.map(sse::Event::try_from); Sse::new(stream) @@ -77,15 +68,15 @@ impl TryFrom<Event> for sse::Event { #[derive(Debug, thiserror::Error)] #[error(transparent)] -pub enum EventsError { - DatabaseError(#[from] sqlx::Error), - ValidateError(#[from] ValidateError), +pub enum Error { + Subscribe(#[from] app::Error), + Validate(#[from] ValidateError), } -impl IntoResponse for EventsError { - fn into_response(self) -> Response { +impl IntoResponse for Error { + fn into_response(self) -> response::Response { match self { - Self::ValidateError(ValidateError::InvalidToken) => Unauthorized.into_response(), + Self::Validate(ValidateError::InvalidToken) => Unauthorized.into_response(), other => Internal::from(other).into_response(), } } diff --git a/src/event/routes/mod.rs b/src/event/routes/mod.rs new file mode 100644 index 0000000..57ab9db --- /dev/null +++ b/src/event/routes/mod.rs @@ -0,0 +1,11 @@ +use axum::{routing::get, Router}; + +use crate::app::App; + +mod get; +#[cfg(test)] +mod test; + +pub fn router() -> Router<App> { + Router::new().route("/api/events", get(get::handler)) +} diff --git a/src/event/routes/test.rs b/src/event/routes/test.rs index 209a016..49f8094 100644 --- a/src/event/routes/test.rs +++ b/src/event/routes/test.rs @@ -5,8 +5,9 @@ use futures::{ stream::{self, StreamExt as _}, }; +use super::get; use crate::{ - event::{routes, Sequenced as _}, + event::Sequenced as _, test::fixtures::{self, future::Immediately as _}, }; @@ -21,16 +22,15 @@ 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 routes::Events(events) = routes::events(State(app), subscriber, None, Query::default()) + 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"); // Verify the structure of the response. let event = events - .filter(fixtures::filter::messages()) + .filter_map(fixtures::message::events) .next() .immediately() .await @@ -48,10 +48,9 @@ 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 routes::Events(events) = - routes::events(State(app.clone()), subscriber, None, Query::default()) + let subscriber = fixtures::identity::create(&app, &fixtures::now()).await; + let get::Response(events) = + get::handler(State(app.clone()), subscriber, None, Query::default()) .await .expect("subscribe never fails"); @@ -61,7 +60,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 @@ -94,16 +93,15 @@ 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 routes::Events(events) = routes::events(State(app), subscriber, None, Query::default()) + 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"); // Verify the structure of the response. let events = events - .filter(fixtures::filter::messages()) + .filter_map(fixtures::message::events) .take(messages.len()) .collect::<Vec<_>>() .immediately() @@ -132,21 +130,22 @@ 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 routes::Events(events) = routes::events(State(app), subscriber, None, Query::default()) + 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"); // 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 { @@ -177,12 +176,11 @@ 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 - let routes::Events(events) = routes::events( + let get::Response(events) = get::handler( State(app.clone()), subscriber.clone(), None, @@ -192,7 +190,7 @@ async fn resumes_from() { .expect("subscribe never fails"); let event = events - .filter(fixtures::filter::messages()) + .filter_map(fixtures::message::events) .next() .immediately() .await @@ -204,7 +202,7 @@ async fn resumes_from() { }; // Resume after disconnect - let routes::Events(resumed) = routes::events( + let get::Response(resumed) = get::handler( State(app), subscriber, Some(resume_at.into()), @@ -216,6 +214,7 @@ async fn resumes_from() { // Verify the structure of the response. let events = resumed + .filter_map(fixtures::message::events) .take(later_messages.len()) .collect::<Vec<_>>() .immediately() @@ -254,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 = [ @@ -264,7 +262,7 @@ async fn serial_resume() { ]; // First subscription - let routes::Events(events) = routes::events( + let get::Response(events) = get::handler( State(app.clone()), subscriber.clone(), None, @@ -274,7 +272,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::<Vec<_>>() .immediately() @@ -302,7 +300,7 @@ async fn serial_resume() { ]; // Second subscription - let routes::Events(events) = routes::events( + let get::Response(events) = get::handler( State(app.clone()), subscriber.clone(), Some(resume_at.into()), @@ -312,7 +310,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::<Vec<_>>() .immediately() @@ -340,7 +338,7 @@ async fn serial_resume() { ]; // Third subscription - let routes::Events(events) = routes::events( + let get::Response(events) = get::handler( State(app.clone()), subscriber.clone(), Some(resume_at.into()), @@ -350,7 +348,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::<Vec<_>>() .immediately() @@ -378,10 +376,10 @@ 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 routes::Events(events) = - routes::events(State(app.clone()), subscriber, None, Query::default()) + let get::Response(events) = + get::handler(State(app.clone()), subscriber, None, Query::default()) .await .expect("subscribe never fails"); @@ -400,6 +398,7 @@ async fn terminates_on_token_expiry() { ]; assert!(events + .filter_map(fixtures::message::events) .filter(|event| future::ready( messages .iter() @@ -421,13 +420,9 @@ 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 routes::Events(events) = routes::events( + let get::Response(events) = get::handler( State(app.clone()), subscriber.clone(), None, @@ -451,6 +446,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<DateTime>, sequence: Option<Sequence>) -> Option<Self> { + at.zip(sequence) + .map(|(at, sequence)| Self::new(at, sequence)) + } +} + impl From<Instant> 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/invite/app.rs b/src/invite/app.rs index 6800d72..64ba753 100644 --- a/src/invite/app.rs +++ b/src/invite/app.rs @@ -7,6 +7,7 @@ use crate::{ db::{Duplicate as _, NotFound as _}, event::repo::Provider as _, login::{repo::Provider as _, Login, Password}, + name::Name, token::{repo::Provider as _, Secret}, }; @@ -31,13 +32,9 @@ impl<'a> Invites<'a> { Ok(invite) } - pub async fn get(&self, invite: &Id) -> Result<Summary, Error> { + pub async fn get(&self, invite: &Id) -> Result<Option<Summary>, sqlx::Error> { let mut tx = self.db.begin().await?; - let invite = tx - .invites() - .summary(invite) - .await - .not_found(|| Error::NotFound(invite.clone()))?; + let invite = tx.invites().summary(invite).await.optional()?; tx.commit().await?; Ok(invite) @@ -46,10 +43,10 @@ impl<'a> Invites<'a> { pub async fn accept( &self, invite: &Id, - name: &str, + name: &Name, password: &Password, accepted_at: &DateTime, - ) -> Result<Secret, AcceptError> { + ) -> Result<(Login, Secret), AcceptError> { let mut tx = self.db.begin().await?; let invite = tx .invites() @@ -72,11 +69,11 @@ impl<'a> Invites<'a> { .logins() .create(name, &password_hash, &created) .await - .duplicate(|| AcceptError::DuplicateLogin(name.into()))?; + .duplicate(|| AcceptError::DuplicateLogin(name.clone()))?; 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> { @@ -92,19 +89,11 @@ impl<'a> Invites<'a> { } #[derive(Debug, thiserror::Error)] -pub enum Error { - #[error("invite not found: {0}")] - NotFound(Id), - #[error(transparent)] - Database(#[from] sqlx::Error), -} - -#[derive(Debug, thiserror::Error)] pub enum AcceptError { #[error("invite not found: {0}")] NotFound(Id), #[error("name in use: {0}")] - DuplicateLogin(String), + DuplicateLogin(Name), #[error(transparent)] Database(#[from] sqlx::Error), #[error(transparent)] diff --git a/src/invite/mod.rs b/src/invite/mod.rs index 5f9d490..d59fb9c 100644 --- a/src/invite/mod.rs +++ b/src/invite/mod.rs @@ -3,10 +3,7 @@ mod id; mod repo; mod routes; -use crate::{ - clock::DateTime, - login::{self, Login}, -}; +use crate::{clock::DateTime, login, normalize::nfc}; pub use self::{id::Id, routes::router}; @@ -19,6 +16,7 @@ pub struct Invite { #[derive(serde::Serialize)] pub struct Summary { - pub issuer: Login, + pub id: Id, + pub issuer: nfc::String, pub issued_at: DateTime, } diff --git a/src/invite/repo.rs b/src/invite/repo.rs index 2ab993f..5f86e49 100644 --- a/src/invite/repo.rs +++ b/src/invite/repo.rs @@ -4,6 +4,7 @@ use super::{Id, Invite, Summary}; use crate::{ clock::DateTime, login::{self, Login}, + normalize::nfc, }; pub trait Provider { @@ -28,13 +29,13 @@ impl<'c> Invites<'c> { let invite = sqlx::query_as!( Invite, r#" - insert into invite (id, issuer, issued_at) - values ($1, $2, $3) - returning - id as "id: Id", - issuer as "issuer: login::Id", - issued_at as "issued_at: DateTime" - "#, + insert into invite (id, issuer, issued_at) + values ($1, $2, $3) + returning + id as "id: Id", + issuer as "issuer: login::Id", + issued_at as "issued_at: DateTime" + "#, id, issuer.id, issued_at @@ -49,13 +50,13 @@ impl<'c> Invites<'c> { let invite = sqlx::query_as!( Invite, r#" - select - id as "id: Id", - issuer as "issuer: login::Id", - issued_at as "issued_at: DateTime" - from invite - where id = $1 - "#, + select + id as "id: Id", + issuer as "issuer: login::Id", + issued_at as "issued_at: DateTime" + from invite + where id = $1 + "#, invite, ) .fetch_one(&mut *self.0) @@ -67,21 +68,20 @@ impl<'c> Invites<'c> { pub async fn summary(&mut self, invite: &Id) -> Result<Summary, sqlx::Error> { let invite = sqlx::query!( r#" - select - issuer.id as "issuer_id: login::Id", - issuer.name as "issuer_name", - invite.issued_at as "invite_issued_at: DateTime" - from invite - join login as issuer on (invite.issuer = issuer.id) - where invite.id = $1 - "#, + select + invite.id as "invite_id: Id", + issuer.id as "issuer_id: login::Id", + issuer.display_name as "issuer_name: nfc::String", + invite.issued_at as "invite_issued_at: DateTime" + from invite + join login as issuer on (invite.issuer = issuer.id) + where invite.id = $1 + "#, invite, ) .map(|row| Summary { - issuer: Login { - id: row.issuer_id, - name: row.issuer_name, - }, + id: row.invite_id, + issuer: row.issuer_name, issued_at: row.invite_issued_at, }) .fetch_one(&mut *self.0) @@ -93,10 +93,10 @@ impl<'c> Invites<'c> { pub async fn accept(&mut self, invite: &Invite) -> Result<(), sqlx::Error> { sqlx::query_scalar!( r#" - delete from invite - where id = $1 - returning 1 as "deleted: bool" - "#, + delete from invite + where id = $1 + returning 1 as "deleted: bool" + "#, invite.id, ) .fetch_one(&mut *self.0) @@ -108,9 +108,9 @@ impl<'c> Invites<'c> { pub async fn expire(&mut self, expire_at: &DateTime) -> Result<(), sqlx::Error> { sqlx::query!( r#" - delete from invite - where issued_at < $1 - "#, + delete from invite + where issued_at < $1 + "#, expire_at, ) .execute(&mut *self.0) diff --git a/src/invite/routes.rs b/src/invite/routes.rs deleted file mode 100644 index 977fe9b..0000000 --- a/src/invite/routes.rs +++ /dev/null @@ -1,97 +0,0 @@ -use axum::{ - extract::{Json, Path, State}, - http::StatusCode, - response::{IntoResponse, Response}, - routing::{get, post}, - Router, -}; - -use super::{app, Id, Invite, Summary}; -use crate::{ - app::App, - clock::RequestedAt, - error::{Internal, NotFound}, - login::{Login, Password}, - token::extract::IdentityToken, -}; - -pub fn router() -> Router<App> { - Router::new() - .route("/api/invite", post(on_invite)) - .route("/api/invite/:invite", get(invite)) - .route("/api/invite/:invite", post(on_accept)) -} - -#[derive(serde::Deserialize)] -struct InviteRequest {} - -async fn on_invite( - State(app): State<App>, - RequestedAt(issued_at): RequestedAt, - login: Login, - // Require `{}` as the only valid request for this endpoint. - _: Json<InviteRequest>, -) -> Result<Json<Invite>, Internal> { - let invite = app.invites().create(&login, &issued_at).await?; - Ok(Json(invite)) -} - -async fn invite( - State(app): State<App>, - Path(invite): Path<Id>, -) -> Result<Json<Summary>, InviteError> { - app.invites() - .get(&invite) - .await - .map(Json) - .map_err(InviteError) -} - -struct InviteError(app::Error); - -impl IntoResponse for InviteError { - fn into_response(self) -> Response { - let Self(error) = self; - match error { - error @ app::Error::NotFound(_) => NotFound(error).into_response(), - other => Internal::from(other).into_response(), - } - } -} - -#[derive(serde::Deserialize)] -struct AcceptRequest { - name: String, - password: Password, -} - -async fn on_accept( - State(app): State<App>, - RequestedAt(accepted_at): RequestedAt, - identity: IdentityToken, - Path(invite): Path<Id>, - Json(request): Json<AcceptRequest>, -) -> Result<(IdentityToken, StatusCode), AcceptError> { - let secret = app - .invites() - .accept(&invite, &request.name, &request.password, &accepted_at) - .await - .map_err(AcceptError)?; - let identity = identity.set(secret); - Ok((identity, StatusCode::NO_CONTENT)) -} - -struct AcceptError(app::AcceptError); - -impl IntoResponse for AcceptError { - fn into_response(self) -> Response { - let Self(error) = self; - match error { - error @ app::AcceptError::NotFound(_) => NotFound(error).into_response(), - error @ app::AcceptError::DuplicateLogin(_) => { - (StatusCode::CONFLICT, error.to_string()).into_response() - } - other => Internal::from(other).into_response(), - } - } -} diff --git a/src/invite/routes/invite/get.rs b/src/invite/routes/invite/get.rs new file mode 100644 index 0000000..c8b52f1 --- /dev/null +++ b/src/invite/routes/invite/get.rs @@ -0,0 +1,39 @@ +use axum::{ + extract::{Json, Path, State}, + response::{IntoResponse, Response}, +}; + +use crate::{ + app::App, + error::{Internal, NotFound}, + invite::{Id, Summary}, +}; + +pub async fn handler( + State(app): State<App>, + Path(invite): Path<super::PathInfo>, +) -> Result<Json<Summary>, Error> { + app.invites() + .get(&invite) + .await? + .map(Json) + .ok_or_else(move || Error::NotFound(invite)) +} + +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("invite not found: {0}")] + NotFound(Id), + #[error(transparent)] + Database(#[from] sqlx::Error), +} + +impl IntoResponse for Error { + fn into_response(self) -> Response { + #[allow(clippy::match_wildcard_for_single_variants)] + match self { + Self::NotFound(_) => NotFound(self).into_response(), + other => Internal::from(other).into_response(), + } + } +} diff --git a/src/invite/routes/invite/mod.rs b/src/invite/routes/invite/mod.rs new file mode 100644 index 0000000..04593fd --- /dev/null +++ b/src/invite/routes/invite/mod.rs @@ -0,0 +1,4 @@ +pub mod get; +pub mod post; + +type PathInfo = crate::invite::Id; diff --git a/src/invite/routes/invite/post.rs b/src/invite/routes/invite/post.rs new file mode 100644 index 0000000..3ca4e6b --- /dev/null +++ b/src/invite/routes/invite/post.rs @@ -0,0 +1,52 @@ +use axum::{ + extract::{Json, Path, State}, + http::StatusCode, + response::{IntoResponse, Response}, +}; + +use crate::{ + app::App, + clock::RequestedAt, + error::{Internal, NotFound}, + invite::app, + login::{Login, Password}, + name::Name, + token::extract::IdentityCookie, +}; + +pub async fn handler( + State(app): State<App>, + RequestedAt(accepted_at): RequestedAt, + identity: IdentityCookie, + Path(invite): Path<super::PathInfo>, + Json(request): Json<Request>, +) -> Result<(IdentityCookie, Json<Login>), 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, Json(login))) +} + +#[derive(serde::Deserialize)] +pub struct Request { + pub name: Name, + pub password: Password, +} + +pub struct Error(app::AcceptError); + +impl IntoResponse for Error { + fn into_response(self) -> Response { + let Self(error) = self; + match error { + app::AcceptError::NotFound(_) => NotFound(error).into_response(), + app::AcceptError::DuplicateLogin(_) => { + (StatusCode::CONFLICT, error.to_string()).into_response() + } + other => Internal::from(other).into_response(), + } + } +} diff --git a/src/invite/routes/mod.rs b/src/invite/routes/mod.rs new file mode 100644 index 0000000..dae20ba --- /dev/null +++ b/src/invite/routes/mod.rs @@ -0,0 +1,16 @@ +use axum::{ + routing::{get, post}, + Router, +}; + +use crate::app::App; + +mod invite; +mod post; + +pub fn router() -> Router<App> { + Router::new() + .route("/api/invite", post(post::handler)) + .route("/api/invite/:invite", get(invite::get::handler)) + .route("/api/invite/:invite", post(invite::post::handler)) +} diff --git a/src/invite/routes/post.rs b/src/invite/routes/post.rs new file mode 100644 index 0000000..eb7d706 --- /dev/null +++ b/src/invite/routes/post.rs @@ -0,0 +1,19 @@ +use axum::extract::{Json, State}; + +use crate::{ + app::App, clock::RequestedAt, error::Internal, invite::Invite, token::extract::Identity, +}; + +pub async fn handler( + State(app): State<App>, + RequestedAt(issued_at): RequestedAt, + identity: Identity, + _: Json<Request>, +) -> Result<Json<Invite>, Internal> { + 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 {} @@ -16,6 +16,8 @@ mod id; mod invite; mod login; mod message; +mod name; +mod normalize; mod setup; #[cfg(test)] mod test; diff --git a/src/login/app.rs b/src/login/app.rs index bb1419b..2f5896f 100644 --- a/src/login/app.rs +++ b/src/login/app.rs @@ -1,24 +1,37 @@ use sqlx::sqlite::SqlitePool; -use super::{repo::Provider as _, Login, Password}; +use super::repo::Provider as _; + +#[cfg(test)] +use super::{Login, Password}; +#[cfg(test)] use crate::{ clock::DateTime, event::{repo::Provider as _, Broadcaster, Event}, + name::Name, }; pub struct Logins<'a> { db: &'a SqlitePool, + #[cfg(test)] events: &'a Broadcaster, } impl<'a> Logins<'a> { + #[cfg(not(test))] + pub const fn new(db: &'a SqlitePool) -> Self { + Self { db } + } + + #[cfg(test)] pub const fn new(db: &'a SqlitePool, events: &'a Broadcaster) -> Self { Self { db, events } } + #[cfg(test)] pub async fn create( &self, - name: &str, + name: &Name, password: &Password, created_at: &DateTime, ) -> Result<Login, CreateError> { @@ -34,11 +47,19 @@ impl<'a> Logins<'a> { Ok(login.as_created()) } + + pub async fn recanonicalize(&self) -> Result<(), sqlx::Error> { + let mut tx = self.db.begin().await?; + tx.logins().recanonicalize().await?; + tx.commit().await?; + + Ok(()) + } } #[derive(Debug, thiserror::Error)] #[error(transparent)] pub enum CreateError { - DatabaseError(#[from] sqlx::Error), - PasswordHashError(#[from] password_hash::Error), + Database(#[from] sqlx::Error), + PasswordHash(#[from] password_hash::Error), } 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<App> for Login { - type Rejection = <Identity as FromRequestParts<App>>::Rejection; - - async fn from_request_parts(parts: &mut Parts, state: &App) -> Result<Self, Self::Rejection> { - let identity = Identity::from_request_parts(parts, state).await?; - - Ok(identity.login) - } -} 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<Login> { + self.events().collect() + } } // Events interface diff --git a/src/login/mod.rs b/src/login/mod.rs index 98cc3d7..279e9a6 100644 --- a/src/login/mod.rs +++ b/src/login/mod.rs @@ -1,7 +1,5 @@ -#[cfg(test)] pub mod app; pub mod event; -pub mod extract; mod history; mod id; pub mod password; diff --git a/src/login/password.rs b/src/login/password.rs index 14fd981..c27c950 100644 --- a/src/login/password.rs +++ b/src/login/password.rs @@ -4,6 +4,8 @@ use argon2::Argon2; use password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString}; use rand_core::OsRng; +use crate::normalize::nfc; + #[derive(sqlx::Type)] #[sqlx(transparent)] pub struct StoredHash(String); @@ -31,7 +33,7 @@ impl fmt::Debug for StoredHash { #[derive(serde::Deserialize)] #[serde(transparent)] -pub struct Password(String); +pub struct Password(nfc::String); impl Password { pub fn hash(&self) -> Result<StoredHash, password_hash::Error> { @@ -56,9 +58,8 @@ impl fmt::Debug for Password { } } -#[cfg(test)] impl From<String> for Password { fn from(password: String) -> Self { - Self(password) + Password(password.into()) } } diff --git a/src/login/repo.rs b/src/login/repo.rs index 6d6510c..611edd6 100644 --- a/src/login/repo.rs +++ b/src/login/repo.rs @@ -1,9 +1,11 @@ +use futures::stream::{StreamExt as _, TryStreamExt as _}; use sqlx::{sqlite::Sqlite, SqliteConnection, Transaction}; use crate::{ clock::DateTime, event::{Instant, ResumePoint, Sequence}, login::{password::StoredHash, History, Id, Login}, + name::{self, Name}, }; pub trait Provider { @@ -21,80 +23,80 @@ pub struct Logins<'t>(&'t mut SqliteConnection); impl<'c> Logins<'c> { pub async fn create( &mut self, - name: &str, + name: &Name, password_hash: &StoredHash, created: &Instant, ) -> Result<History, sqlx::Error> { let id = Id::generate(); + let display_name = name.display(); + let canonical_name = name.canonical(); - let login = sqlx::query!( + sqlx::query!( r#" insert - into login (id, name, password_hash, created_sequence, created_at) - values ($1, $2, $3, $4, $5) - returning - id as "id: Id", - name, - created_sequence as "created_sequence: Sequence", - created_at as "created_at: DateTime" + into login (id, display_name, canonical_name, password_hash, created_sequence, created_at) + values ($1, $2, $3, $4, $5, $6) "#, id, - name, + display_name, + canonical_name, password_hash, created.sequence, created.at, ) - .map(|row| History { + .execute(&mut *self.0) + .await?; + + let login = History { + created: *created, login: Login { - id: row.id, - name: row.name, - }, - created: Instant { - at: row.created_at, - sequence: row.created_sequence, + id, + name: name.clone(), }, - }) - .fetch_one(&mut *self.0) - .await?; + }; Ok(login) } - pub async fn all(&mut self, resume_at: ResumePoint) -> Result<Vec<History>, sqlx::Error> { - let channels = sqlx::query!( + pub async fn all(&mut self, resume_at: ResumePoint) -> Result<Vec<History>, LoadError> { + let logins = sqlx::query!( r#" select id as "id: Id", - name, + display_name as "display_name: String", + canonical_name as "canonical_name: String", created_sequence as "created_sequence: Sequence", created_at as "created_at: DateTime" from login where coalesce(created_sequence <= $1, true) - order by created_sequence + order by canonical_name "#, resume_at, ) - .map(|row| History { - login: Login { - id: row.id, - name: row.name, - }, - created: Instant { - at: row.created_at, - sequence: row.created_sequence, - }, + .map(|row| { + Ok::<_, LoadError>(History { + login: Login { + id: row.id, + name: Name::new(row.display_name, row.canonical_name)?, + }, + created: Instant::new(row.created_at, row.created_sequence), + }) }) - .fetch_all(&mut *self.0) + .fetch(&mut *self.0) + .map(|res| res?) + .try_collect() .await?; - Ok(channels) + Ok(logins) } - pub async fn replay(&mut self, resume_at: ResumePoint) -> Result<Vec<History>, sqlx::Error> { - let messages = sqlx::query!( + + pub async fn replay(&mut self, resume_at: ResumePoint) -> Result<Vec<History>, LoadError> { + let logins = sqlx::query!( r#" select id as "id: Id", - name, + display_name as "display_name: String", + canonical_name as "canonical_name: String", created_sequence as "created_sequence: Sequence", created_at as "created_at: DateTime" from login @@ -102,25 +104,59 @@ impl<'c> Logins<'c> { "#, resume_at, ) - .map(|row| History { - login: Login { - id: row.id, - name: row.name, - }, - created: Instant { - at: row.created_at, - sequence: row.created_sequence, - }, + .map(|row| { + Ok::<_, name::Error>(History { + login: Login { + id: row.id, + name: Name::new(row.display_name, row.canonical_name)?, + }, + created: Instant::new(row.created_at, row.created_sequence), + }) }) + .fetch(&mut *self.0) + .map(|res| Ok::<_, LoadError>(res??)) + .try_collect() + .await?; + + Ok(logins) + } + + pub async fn recanonicalize(&mut self) -> Result<(), sqlx::Error> { + let logins = sqlx::query!( + r#" + select + id as "id: Id", + display_name as "display_name: String" + from login + "#, + ) .fetch_all(&mut *self.0) .await?; - Ok(messages) + for login in logins { + let name = Name::from(login.display_name); + let canonical_name = name.canonical(); + + sqlx::query!( + r#" + update login + set canonical_name = $1 + where id = $2 + "#, + canonical_name, + login.id, + ) + .execute(&mut *self.0) + .await?; + } + + Ok(()) } } -impl<'t> From<&'t mut SqliteConnection> for Logins<'t> { - fn from(tx: &'t mut SqliteConnection) -> Self { - Self(tx) - } +#[derive(Debug, thiserror::Error)] +#[error(transparent)] +pub enum LoadError { + Database(#[from] sqlx::Error), + Name(#[from] name::Error), } diff --git a/src/login/routes.rs b/src/login/routes.rs deleted file mode 100644 index 6579ae6..0000000 --- a/src/login/routes.rs +++ /dev/null @@ -1,97 +0,0 @@ -use axum::{ - extract::{Json, State}, - http::StatusCode, - response::{IntoResponse, Response}, - routing::post, - Router, -}; - -use crate::{ - app::App, - clock::RequestedAt, - error::{Internal, Unauthorized}, - login::Password, - token::{app, extract::IdentityToken}, -}; - -#[cfg(test)] -mod test; - -pub fn router() -> Router<App> { - Router::new() - .route("/api/auth/login", post(on_login)) - .route("/api/auth/logout", post(on_logout)) -} - -#[derive(serde::Deserialize)] -struct LoginRequest { - name: String, - password: Password, -} - -async fn on_login( - State(app): State<App>, - RequestedAt(now): RequestedAt, - identity: IdentityToken, - Json(request): Json<LoginRequest>, -) -> Result<(IdentityToken, StatusCode), LoginError> { - let token = app - .tokens() - .login(&request.name, &request.password, &now) - .await - .map_err(LoginError)?; - let identity = identity.set(token); - Ok((identity, StatusCode::NO_CONTENT)) -} - -#[derive(Debug)] -struct LoginError(app::LoginError); - -impl IntoResponse for LoginError { - fn into_response(self) -> Response { - let Self(error) = self; - match error { - app::LoginError::Rejected => { - // not error::Unauthorized due to differing messaging - (StatusCode::UNAUTHORIZED, "invalid name or password").into_response() - } - other => Internal::from(other).into_response(), - } - } -} - -#[derive(serde::Deserialize)] -struct LogoutRequest {} - -async fn on_logout( - State(app): State<App>, - RequestedAt(now): RequestedAt, - identity: IdentityToken, - // This forces the only valid request to be `{}`, and not the infinite - // variation allowed when there's no body extractor. - Json(LogoutRequest {}): Json<LogoutRequest>, -) -> Result<(IdentityToken, StatusCode), LogoutError> { - if let Some(secret) = identity.secret() { - let (token, _) = app.tokens().validate(&secret, &now).await?; - app.tokens().logout(&token).await?; - } - - let identity = identity.clear(); - Ok((identity, StatusCode::NO_CONTENT)) -} - -#[derive(Debug, thiserror::Error)] -#[error(transparent)] -enum LogoutError { - ValidateError(#[from] app::ValidateError), - DatabaseError(#[from] sqlx::Error), -} - -impl IntoResponse for LogoutError { - fn into_response(self) -> Response { - match self { - Self::ValidateError(app::ValidateError::InvalidToken) => Unauthorized.into_response(), - other => Internal::from(other).into_response(), - } - } -} diff --git a/src/login/routes/login/mod.rs b/src/login/routes/login/mod.rs new file mode 100644 index 0000000..36b384e --- /dev/null +++ b/src/login/routes/login/mod.rs @@ -0,0 +1,4 @@ +pub mod post; + +#[cfg(test)] +mod test; diff --git a/src/login/routes/login/post.rs b/src/login/routes/login/post.rs new file mode 100644 index 0000000..96da5c5 --- /dev/null +++ b/src/login/routes/login/post.rs @@ -0,0 +1,52 @@ +use axum::{ + extract::{Json, State}, + http::StatusCode, + response::{IntoResponse, Response}, +}; + +use crate::{ + app::App, + clock::RequestedAt, + error::Internal, + login::{Login, Password}, + name::Name, + token::{app, extract::IdentityCookie}, +}; + +pub async fn handler( + State(app): State<App>, + RequestedAt(now): RequestedAt, + identity: IdentityCookie, + Json(request): Json<Request>, +) -> Result<(IdentityCookie, Json<Login>), Error> { + let (login, secret) = app + .tokens() + .login(&request.name, &request.password, &now) + .await + .map_err(Error)?; + let identity = identity.set(secret); + Ok((identity, Json(login))) +} + +#[derive(serde::Deserialize)] +pub struct Request { + pub name: Name, + pub password: Password, +} + +#[derive(Debug, thiserror::Error)] +#[error(transparent)] +pub struct Error(#[from] pub app::LoginError); + +impl IntoResponse for Error { + fn into_response(self) -> Response { + let Self(error) = self; + match error { + app::LoginError::Rejected => { + // not error::Unauthorized due to differing messaging + (StatusCode::UNAUTHORIZED, "invalid name or password").into_response() + } + other => Internal::from(other).into_response(), + } + } +} diff --git a/src/login/routes/test/login.rs b/src/login/routes/login/test.rs index 68c92de..7399796 100644 --- a/src/login/routes/test/login.rs +++ b/src/login/routes/login/test.rs @@ -1,9 +1,7 @@ -use axum::{ - extract::{Json, State}, - http::StatusCode, -}; +use axum::extract::{Json, State}; -use crate::{login::routes, test::fixtures, token::app}; +use super::post; +use crate::{test::fixtures, token::app}; #[tokio::test] async fn correct_credentials() { @@ -14,21 +12,23 @@ async fn correct_credentials() { // 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 = routes::LoginRequest { + let request = post::Request { name: name.clone(), password, }; - let (identity, status) = - routes::on_login(State(app.clone()), logged_in_at, identity, Json(request)) + 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); - 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 @@ -39,7 +39,7 @@ async fn correct_credentials() { .await .expect("identity secret is valid"); - assert_eq!(name, validated_login.name); + assert_eq!(response, validated_login); } #[tokio::test] @@ -50,17 +50,17 @@ 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 = routes::LoginRequest { + let request = post::Request { name: name.clone(), password, }; - let routes::LoginError(error) = - routes::on_login(State(app.clone()), logged_in_at, identity, Json(request)) + 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 @@ -77,13 +77,13 @@ async fn incorrect_password() { // Call the endpoint let logged_in_at = fixtures::now(); - let identity = fixtures::identity::not_logged_in(); - let request = routes::LoginRequest { + let identity = fixtures::cookie::not_logged_in(); + let request = post::Request { name: login.name, password: fixtures::login::propose_password(), }; - let routes::LoginError(error) = - routes::on_login(State(app.clone()), logged_in_at, identity, Json(request)) + let post::Error(error) = + post::handler(State(app.clone()), logged_in_at, identity, Json(request)) .await .expect_err("logged in with an incorrect password"); @@ -102,9 +102,9 @@ async fn token_expires() { // Call the endpoint let logged_in_at = fixtures::ancient(); - let identity = fixtures::identity::not_logged_in(); - let request = routes::LoginRequest { name, password }; - let (identity, _) = routes::on_login(State(app.clone()), logged_in_at, identity, Json(request)) + 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"); let secret = identity.secret().expect("logged in with valid credentials"); diff --git a/src/login/routes/logout/mod.rs b/src/login/routes/logout/mod.rs new file mode 100644 index 0000000..36b384e --- /dev/null +++ b/src/login/routes/logout/mod.rs @@ -0,0 +1,4 @@ +pub mod post; + +#[cfg(test)] +mod test; diff --git a/src/login/routes/logout/post.rs b/src/login/routes/logout/post.rs new file mode 100644 index 0000000..bb09b9f --- /dev/null +++ b/src/login/routes/logout/post.rs @@ -0,0 +1,47 @@ +use axum::{ + extract::{Json, State}, + http::StatusCode, + response::{IntoResponse, Response}, +}; + +use crate::{ + app::App, + clock::RequestedAt, + error::{Internal, Unauthorized}, + token::{app, extract::IdentityCookie}, +}; + +pub async fn handler( + State(app): State<App>, + RequestedAt(now): RequestedAt, + identity: IdentityCookie, + Json(_): Json<Request>, +) -> Result<(IdentityCookie, StatusCode), Error> { + if let Some(secret) = identity.secret() { + let (token, _) = app.tokens().validate(&secret, &now).await?; + app.tokens().logout(&token).await?; + } + + let identity = identity.clear(); + Ok((identity, StatusCode::NO_CONTENT)) +} + +// This forces the only valid request to be `{}`, and not the infinite +// variation allowed when there's no body extractor. +#[derive(Default, serde::Deserialize)] +pub struct Request {} + +#[derive(Debug, thiserror::Error)] +#[error(transparent)] +pub struct Error(#[from] pub app::ValidateError); + +impl IntoResponse for Error { + fn into_response(self) -> Response { + let Self(error) = self; + #[allow(clippy::match_wildcard_for_single_variants)] + match error { + app::ValidateError::InvalidToken => Unauthorized.into_response(), + other => Internal::from(other).into_response(), + } + } +} diff --git a/src/login/routes/logout/test.rs b/src/login/routes/logout/test.rs new file mode 100644 index 0000000..775fa9f --- /dev/null +++ b/src/login/routes/logout/test.rs @@ -0,0 +1,79 @@ +use axum::{ + extract::{Json, State}, + http::StatusCode, +}; + +use super::post; +use crate::{test::fixtures, token::app}; + +#[tokio::test] +async fn successful() { + // Set up the environment + + let app = fixtures::scratch_app().await; + let now = fixtures::now(); + 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 + + let (response_identity, response_status) = post::handler( + State(app.clone()), + fixtures::now(), + identity.clone(), + Json::default(), + ) + .await + .expect("logged out with a valid token"); + + // Verify the return value's basic structure + + assert!(response_identity.secret().is_none()); + assert_eq!(StatusCode::NO_CONTENT, response_status); + + // Verify the semantics + let error = app + .tokens() + .validate(&secret, &now) + .await + .expect_err("secret is invalid"); + assert!(matches!(error, app::ValidateError::InvalidToken)); +} + +#[tokio::test] +async fn no_identity() { + // Set up the environment + + let app = fixtures::scratch_app().await; + + // Call the endpoint + + 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 succeeds"); + + // Verify the return value's basic structure + + assert!(identity.secret().is_none()); + assert_eq!(StatusCode::NO_CONTENT, status); +} + +#[tokio::test] +async fn invalid_token() { + // Set up the environment + + let app = fixtures::scratch_app().await; + + // Call the endpoint + + 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 fails"); + + // Verify the return value's basic structure + + assert!(matches!(error, app::ValidateError::InvalidToken)); +} diff --git a/src/login/routes/mod.rs b/src/login/routes/mod.rs new file mode 100644 index 0000000..8cb8852 --- /dev/null +++ b/src/login/routes/mod.rs @@ -0,0 +1,12 @@ +use axum::{routing::post, Router}; + +use crate::app::App; + +mod login; +mod logout; + +pub fn router() -> Router<App> { + Router::new() + .route("/api/auth/login", post(login::post::handler)) + .route("/api/auth/logout", post(logout::post::handler)) +} diff --git a/src/login/routes/test/logout.rs b/src/login/routes/test/logout.rs deleted file mode 100644 index 611829e..0000000 --- a/src/login/routes/test/logout.rs +++ /dev/null @@ -1,97 +0,0 @@ -use axum::{ - extract::{Json, State}, - http::StatusCode, -}; - -use crate::{login::routes, test::fixtures, token::app}; - -#[tokio::test] -async fn successful() { - // Set up the environment - - 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); - - // Call the endpoint - - let (response_identity, response_status) = routes::on_logout( - State(app.clone()), - fixtures::now(), - identity.clone(), - Json(routes::LogoutRequest {}), - ) - .await - .expect("logged out with a valid token"); - - // Verify the return value's basic structure - - assert!(response_identity.secret().is_none()); - assert_eq!(StatusCode::NO_CONTENT, response_status); - - // Verify the semantics - - let error = app - .tokens() - .validate(&secret, &now) - .await - .expect_err("secret is invalid"); - match error { - app::ValidateError::InvalidToken => (), // should be invalid - other @ app::ValidateError::DatabaseError(_) => { - panic!("expected ValidateError::InvalidToken, got {other:#}") - } - } -} - -#[tokio::test] -async fn no_identity() { - // Set up the environment - - let app = fixtures::scratch_app().await; - - // Call the endpoint - - let identity = fixtures::identity::not_logged_in(); - let (identity, status) = routes::on_logout( - State(app), - fixtures::now(), - identity, - Json(routes::LogoutRequest {}), - ) - .await - .expect("logged out with no token"); - - // Verify the return value's basic structure - - assert!(identity.secret().is_none()); - assert_eq!(StatusCode::NO_CONTENT, status); -} - -#[tokio::test] -async fn invalid_token() { - // Set up the environment - - let app = fixtures::scratch_app().await; - - // Call the endpoint - - let identity = fixtures::identity::fictitious(); - let error = routes::on_logout( - State(app), - fixtures::now(), - identity, - Json(routes::LogoutRequest {}), - ) - .await - .expect_err("logged out with an invalid token"); - - // Verify the return value's basic structure - - assert!(matches!( - error, - routes::LogoutError::ValidateError(app::ValidateError::InvalidToken) - )); -} diff --git a/src/login/routes/test/mod.rs b/src/login/routes/test/mod.rs deleted file mode 100644 index 90522c4..0000000 --- a/src/login/routes/test/mod.rs +++ /dev/null @@ -1,2 +0,0 @@ -mod login; -mod logout; diff --git a/src/login/snapshot.rs b/src/login/snapshot.rs index 1a92f5c..e1eb96c 100644 --- a/src/login/snapshot.rs +++ b/src/login/snapshot.rs @@ -2,6 +2,7 @@ use super::{ event::{Created, Event}, Id, }; +use crate::name::Name; // This also implements FromRequestParts (see `./extract.rs`). As a result, it // can be used as an extractor for endpoints that want to require login, or for @@ -10,7 +11,7 @@ use super::{ #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize)] pub struct Login { pub id: Id, - pub name: String, + pub name: Name, // The omission of the hashed password is deliberate, to minimize the // chance that it ends up tangled up in debug output or in some other chunk // of logic elsewhere. diff --git a/src/message/app.rs b/src/message/app.rs index 3385af2..eed6ba4 100644 --- a/src/message/app.rs +++ b/src/message/app.rs @@ -2,13 +2,14 @@ use chrono::TimeDelta; use itertools::Itertools; use sqlx::sqlite::SqlitePool; -use super::{repo::Provider as _, Id, Message}; +use super::{repo::Provider as _, Body, Id, Message}; use crate::{ channel::{self, repo::Provider as _}, clock::DateTime, db::NotFound as _, event::{repo::Provider as _, Broadcaster, Event, Sequence}, login::Login, + name, }; pub struct Messages<'a> { @@ -26,7 +27,7 @@ impl<'a> Messages<'a> { channel: &channel::Id, sender: &Login, sent_at: &DateTime, - body: &str, + body: &Body, ) -> Result<Message, SendError> { let mut tx = self.db.begin().await?; let channel = tx @@ -46,8 +47,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 +101,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)] @@ -98,15 +119,27 @@ pub enum SendError { #[error("channel {0} not found")] ChannelNotFound(channel::Id), #[error(transparent)] - DatabaseError(#[from] sqlx::Error), + Database(#[from] sqlx::Error), + #[error(transparent)] + Name(#[from] name::Error), +} + +impl From<channel::repo::LoadError> for SendError { + fn from(error: channel::repo::LoadError) -> Self { + use channel::repo::LoadError; + match error { + LoadError::Database(error) => error.into(), + LoadError::Name(error) => error.into(), + } + } } #[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")] + Deleted(Id), #[error(transparent)] - DatabaseError(#[from] sqlx::Error), + Database(#[from] sqlx::Error), } diff --git a/src/message/body.rs b/src/message/body.rs new file mode 100644 index 0000000..6dd224c --- /dev/null +++ b/src/message/body.rs @@ -0,0 +1,30 @@ +use std::fmt; + +use crate::normalize::nfc; + +#[derive( + Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, sqlx::Type, +)] +#[serde(transparent)] +#[sqlx(transparent)] +pub struct Body(nfc::String); + +impl fmt::Display for Body { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let Self(body) = self; + body.fmt(f) + } +} + +impl From<String> for Body { + fn from(body: String) -> Self { + Self(body.into()) + } +} + +impl From<Body> for String { + fn from(body: Body) -> Self { + let Body(body) = body; + body.into() + } +} 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<Message> { + self.events().collect() + } } // Events interface diff --git a/src/message/mod.rs b/src/message/mod.rs index a8f51ab..c2687bc 100644 --- a/src/message/mod.rs +++ b/src/message/mod.rs @@ -1,4 +1,5 @@ pub mod app; +mod body; pub mod event; mod history; mod id; @@ -6,4 +7,6 @@ pub mod repo; mod routes; mod snapshot; -pub use self::{event::Event, history::History, id::Id, routes::router, snapshot::Message}; +pub use self::{ + body::Body, event::Event, history::History, id::Id, routes::router, snapshot::Message, +}; diff --git a/src/message/repo.rs b/src/message/repo.rs index 71c6d10..c8ceceb 100644 --- a/src/message/repo.rs +++ b/src/message/repo.rs @@ -1,6 +1,6 @@ use sqlx::{sqlite::Sqlite, SqliteConnection, Transaction}; -use super::{snapshot::Message, History, Id}; +use super::{snapshot::Message, Body, History, Id}; use crate::{ channel, clock::DateTime, @@ -26,24 +26,24 @@ impl<'c> Messages<'c> { channel: &channel::History, sender: &Login, sent: &Instant, - body: &str, + body: &Body, ) -> Result<History, sqlx::Error> { let id = Id::generate(); let channel_id = channel.id(); let message = sqlx::query!( r#" - insert into message - (id, channel, sender, sent_at, sent_sequence, body) - values ($1, $2, $3, $4, $5, $6) - returning - id as "id: Id", + insert into message + (id, channel, sender, sent_at, sent_sequence, body) + values ($1, $2, $3, $4, $5, $6) + returning + id as "id: Id", channel as "channel: channel::Id", sender as "sender: login::Id", sent_at as "sent_at: DateTime", sent_sequence as "sent_sequence: Sequence", - body - "#, + body as "body: Body" + "#, id, channel_id, sender.id, @@ -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, + body: row.body.unwrap_or_default(), + 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<Vec<History>, sqlx::Error> { + pub async fn live(&mut self, channel: &channel::History) -> Result<Vec<History>, 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 as "body: 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, + body: row.body.unwrap_or_default(), + 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 as "body: 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, + body: row.body.unwrap_or_default(), + 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<History, sqlx::Error> { + pub async fn by_id(&mut self, message: &Id) -> Result<History, sqlx::Error> { 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 as "body: 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, + body: row.body.unwrap_or_default(), + 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,101 @@ impl<'c> Messages<'c> { pub async fn delete( &mut self, - message: &Id, + message: &History, deleted: &Instant, ) -> Result<History, sqlx::Error> { - let history = self.by_id(message).await?; + let id = message.id(); - sqlx::query_scalar!( + sqlx::query!( 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) "#, - history.message.id, + id, + deleted.at, + deleted.sequence, ) - .fetch_one(&mut *self.0) + .execute(&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!( + r#" + update message + set body = '' + where id = $1 + "#, + id, + ) + .execute(&mut *self.0) + .await?; + + let message = self.by_id(id).await?; + + Ok(message) } - pub async fn expired(&mut self, expire_at: &DateTime) -> Result<Vec<Id>, 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<Vec<History>, 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 as "body: 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.unwrap_or_default(), + deleted_at: row.deleted_at, + }, + deleted: Instant::optional(row.deleted_at, row.deleted_sequence), + }) .fetch_all(&mut *self.0) .await?; @@ -226,29 +286,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 as "body: 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, + body: row.body.unwrap_or_default(), + 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.rs b/src/message/routes.rs deleted file mode 100644 index e21c674..0000000 --- a/src/message/routes.rs +++ /dev/null @@ -1,46 +0,0 @@ -use axum::{ - extract::{Path, State}, - http::StatusCode, - response::{IntoResponse, Response}, - routing::delete, - Router, -}; - -use crate::{ - app::App, - clock::RequestedAt, - error::{Internal, NotFound}, - login::Login, - message::{self, app::DeleteError}, -}; - -pub fn router() -> Router<App> { - Router::new().route("/api/messages/:message", delete(on_delete)) -} - -async fn on_delete( - State(app): State<App>, - Path(message): Path<message::Id>, - RequestedAt(deleted_at): RequestedAt, - _: Login, -) -> Result<StatusCode, ErrorResponse> { - app.messages().delete(&message, &deleted_at).await?; - - Ok(StatusCode::ACCEPTED) -} - -#[derive(Debug, thiserror::Error)] -#[error(transparent)] -struct ErrorResponse(#[from] DeleteError); - -impl IntoResponse for ErrorResponse { - fn into_response(self) -> Response { - let Self(error) = self; - match error { - not_found @ (DeleteError::ChannelNotFound(_) | DeleteError::NotFound(_)) => { - NotFound(not_found).into_response() - } - other => Internal::from(other).into_response(), - } - } -} diff --git a/src/message/routes/message/mod.rs b/src/message/routes/message/mod.rs new file mode 100644 index 0000000..545ad26 --- /dev/null +++ b/src/message/routes/message/mod.rs @@ -0,0 +1,46 @@ +#[cfg(test)] +mod test; + +pub mod delete { + use axum::{ + extract::{Path, State}, + http::StatusCode, + response::{IntoResponse, Response}, + }; + + use crate::{ + app::App, + clock::RequestedAt, + error::{Internal, NotFound}, + message::{self, app::DeleteError}, + token::extract::Identity, + }; + + pub async fn handler( + State(app): State<App>, + Path(message): Path<message::Id>, + RequestedAt(deleted_at): RequestedAt, + _: Identity, + ) -> Result<StatusCode, Error> { + app.messages().delete(&message, &deleted_at).await?; + + Ok(StatusCode::ACCEPTED) + } + + #[derive(Debug, thiserror::Error)] + #[error(transparent)] + pub struct Error(#[from] pub DeleteError); + + impl IntoResponse for Error { + fn into_response(self) -> Response { + let Self(error) = self; + #[allow(clippy::match_wildcard_for_single_variants)] + match error { + DeleteError::NotFound(_) | DeleteError::Deleted(_) => { + NotFound(error).into_response() + } + other => Internal::from(other).into_response(), + } + } + } +} diff --git a/src/message/routes/message/test.rs b/src/message/routes/message/test.rs new file mode 100644 index 0000000..2016fb8 --- /dev/null +++ b/src/message/routes/message/test.rs @@ -0,0 +1,160 @@ +use axum::{ + extract::{Path, State}, + http::StatusCode, +}; + +use super::delete; +use crate::{message::app, test::fixtures}; + +#[tokio::test] +pub async fn delete_message() { + // Set up the environment + + let app = fixtures::scratch_app().await; + let sender = fixtures::login::create(&app, &fixtures::now()).await; + let channel = fixtures::channel::create(&app, &fixtures::now()).await; + let message = fixtures::message::send(&app, &channel, &sender, &fixtures::now()).await; + + // Send the request + + let deleter = fixtures::identity::create(&app, &fixtures::now()).await; + let response = delete::handler( + State(app.clone()), + Path(message.id.clone()), + fixtures::now(), + deleter, + ) + .await + .expect("deleting a valid message succeeds"); + + // Verify the response + + assert_eq!(response, StatusCode::ACCEPTED); + + // Verify the semantics + + let snapshot = app.boot().snapshot().await.expect("boot always succeeds"); + assert!(!snapshot.messages.contains(&message)); +} + +#[tokio::test] +pub async fn delete_invalid_message_id() { + // Set up the environment + + let app = fixtures::scratch_app().await; + + // Send the request + + let deleter = fixtures::identity::create(&app, &fixtures::now()).await; + let message = fixtures::message::fictitious(); + let delete::Error(error) = delete::handler( + State(app.clone()), + Path(message.clone()), + fixtures::now(), + deleter, + ) + .await + .expect_err("deleting a nonexistent message fails"); + + // Verify the response + + assert!(matches!(error, app::DeleteError::NotFound(id) if id == message)); +} + +#[tokio::test] +pub async fn delete_deleted() { + // Set up the environment + + let app = fixtures::scratch_app().await; + let sender = fixtures::login::create(&app, &fixtures::now()).await; + let channel = fixtures::channel::create(&app, &fixtures::now()).await; + let message = fixtures::message::send(&app, &channel, &sender, &fixtures::now()).await; + + app.messages() + .delete(&message.id, &fixtures::now()) + .await + .expect("deleting a recently-sent message succeeds"); + + // Send the request + + let deleter = fixtures::identity::create(&app, &fixtures::now()).await; + let delete::Error(error) = delete::handler( + State(app.clone()), + Path(message.id.clone()), + fixtures::now(), + deleter, + ) + .await + .expect_err("deleting a deleted message fails"); + + // Verify the response + + assert!(matches!(error, app::DeleteError::Deleted(id) if id == message.id)); +} + +#[tokio::test] +pub async fn delete_expired() { + // Set up the environment + + let app = fixtures::scratch_app().await; + let sender = fixtures::login::create(&app, &fixtures::ancient()).await; + let channel = fixtures::channel::create(&app, &fixtures::ancient()).await; + let message = fixtures::message::send(&app, &channel, &sender, &fixtures::ancient()).await; + + app.messages() + .expire(&fixtures::now()) + .await + .expect("expiring messages always succeeds"); + + // Send the request + + let deleter = fixtures::identity::create(&app, &fixtures::now()).await; + let delete::Error(error) = delete::handler( + State(app.clone()), + Path(message.id.clone()), + fixtures::now(), + deleter, + ) + .await + .expect_err("deleting an expired message fails"); + + // Verify the response + + assert!(matches!(error, app::DeleteError::Deleted(id) if id == message.id)); +} + +#[tokio::test] +pub async fn delete_purged() { + // Set up the environment + + let app = fixtures::scratch_app().await; + let sender = fixtures::login::create(&app, &fixtures::ancient()).await; + let channel = fixtures::channel::create(&app, &fixtures::ancient()).await; + let message = fixtures::message::send(&app, &channel, &sender, &fixtures::ancient()).await; + + app.messages() + .expire(&fixtures::old()) + .await + .expect("expiring messages always succeeds"); + + app.messages() + .purge(&fixtures::now()) + .await + .expect("purging messages always succeeds"); + + // Send the request + + let deleter = fixtures::identity::create(&app, &fixtures::now()).await; + let delete::Error(error) = delete::handler( + State(app.clone()), + Path(message.id.clone()), + fixtures::now(), + deleter, + ) + .await + .expect_err("deleting a purged message fails"); + + // Verify the response + + assert!(matches!(error, app::DeleteError::NotFound(id) if id == message.id)); +} diff --git a/src/message/routes/mod.rs b/src/message/routes/mod.rs new file mode 100644 index 0000000..dfe8628 --- /dev/null +++ b/src/message/routes/mod.rs @@ -0,0 +1,9 @@ +use axum::{routing::delete, Router}; + +use crate::app::App; + +mod message; + +pub fn router() -> Router<App> { + Router::new().route("/api/messages/:message", delete(message::delete::handler)) +} diff --git a/src/message/snapshot.rs b/src/message/snapshot.rs index 0eb37bb..53b7176 100644 --- a/src/message/snapshot.rs +++ b/src/message/snapshot.rs @@ -1,8 +1,8 @@ use super::{ event::{Event, Sent}, - Id, + Body, 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 { @@ -11,7 +11,9 @@ pub struct Message { pub channel: channel::Id, pub sender: login::Id, pub id: Id, - pub body: String, + pub body: Body, + #[serde(skip_serializing_if = "Option::is_none")] + pub deleted_at: Option<DateTime>, } impl Message { diff --git a/src/name.rs b/src/name.rs new file mode 100644 index 0000000..9187d33 --- /dev/null +++ b/src/name.rs @@ -0,0 +1,85 @@ +use std::fmt; + +use crate::normalize::{ident, nfc}; + +#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, sqlx::Type)] +#[serde(from = "String", into = "String")] +pub struct Name { + display: nfc::String, + canonical: ident::String, +} + +impl Name { + pub fn new<D, C>(display: D, canonical: C) -> Result<Self, Error> + where + D: AsRef<str>, + C: AsRef<str>, + { + let name = Self::from(display); + + if name.canonical.as_str() == canonical.as_ref() { + Ok(name) + } else { + Err(Error::CanonicalMismatch( + canonical.as_ref().into(), + name.canonical, + name.display, + )) + } + } + + pub fn optional<D, C>(display: Option<D>, canonical: Option<C>) -> Result<Option<Self>, Error> + where + D: AsRef<str>, + C: AsRef<str>, + { + display + .zip(canonical) + .map(|(display, canonical)| Self::new(display, canonical)) + .transpose() + } + + pub fn display(&self) -> &nfc::String { + &self.display + } + + pub fn canonical(&self) -> &ident::String { + &self.canonical + } +} + +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("stored canonical form {0:#?} does not match computed canonical form {:#?} for name {:#?}", .1.as_str(), .2.as_str())] + CanonicalMismatch(String, ident::String, nfc::String), +} + +impl Default for Name { + fn default() -> Self { + Self::from(String::default()) + } +} + +impl fmt::Display for Name { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.display.fmt(f) + } +} + +impl<S> From<S> for Name +where + S: AsRef<str>, +{ + fn from(name: S) -> Self { + let display = nfc::String::from(&name); + let canonical = ident::String::from(&name); + + Self { display, canonical } + } +} + +impl From<Name> for String { + fn from(name: Name) -> Self { + name.display.into() + } +} diff --git a/src/normalize/mod.rs b/src/normalize/mod.rs new file mode 100644 index 0000000..6294201 --- /dev/null +++ b/src/normalize/mod.rs @@ -0,0 +1,36 @@ +mod string; + +pub mod nfc { + use std::string::String as StdString; + + use unicode_normalization::UnicodeNormalization as _; + + pub type String = super::string::String<Nfc>; + + #[derive(Clone, Debug, Default, Eq, PartialEq)] + pub struct Nfc; + + impl super::string::Normalize for Nfc { + fn normalize(&self, value: &str) -> StdString { + value.nfc().collect() + } + } +} + +pub mod ident { + use std::string::String as StdString; + + use unicode_casefold::UnicodeCaseFold as _; + use unicode_normalization::UnicodeNormalization as _; + + pub type String = super::string::String<Ident>; + + #[derive(Clone, Debug, Default, Eq, PartialEq)] + pub struct Ident; + + impl super::string::Normalize for Ident { + fn normalize(&self, value: &str) -> StdString { + value.case_fold().nfkc().collect() + } + } +} diff --git a/src/normalize/string.rs b/src/normalize/string.rs new file mode 100644 index 0000000..a0d178c --- /dev/null +++ b/src/normalize/string.rs @@ -0,0 +1,112 @@ +use std::{fmt, string::String as StdString}; + +use sqlx::{ + encode::{Encode, IsNull}, + Database, Decode, Type, +}; + +pub trait Normalize: Clone + Default { + fn normalize(&self, value: &str) -> StdString; +} + +#[derive(Clone, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize)] +#[serde(into = "StdString", from = "StdString")] +#[serde(bound = "N: Normalize")] +pub struct String<N>(StdString, N); + +impl<N> fmt::Display for String<N> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let Self(value, _) = self; + value.fmt(f) + } +} + +impl<S, N> From<S> for String<N> +where + S: AsRef<str>, + N: Normalize, +{ + fn from(value: S) -> Self { + let normalizer = N::default(); + let value = normalizer.normalize(value.as_ref()); + + Self(value, normalizer) + } +} + +impl<N> From<String<N>> for StdString { + fn from(value: String<N>) -> Self { + let String(value, _) = value; + value + } +} + +impl<N> std::ops::Deref for String<N> { + type Target = StdString; + + fn deref(&self) -> &Self::Target { + let Self(value, _) = self; + value + } +} + +// Type is manually implemented so that we can implement Decode to do +// normalization on read. Implementation is otherwise based on +// `#[derive(sqlx::Type)]` with the `#[sqlx(transparent)]` attribute. +impl<DB, N> Type<DB> for String<N> +where + DB: Database, + StdString: Type<DB>, +{ + fn type_info() -> <DB as Database>::TypeInfo { + <StdString as Type<DB>>::type_info() + } + + fn compatible(ty: &<DB as Database>::TypeInfo) -> bool { + <StdString as Type<DB>>::compatible(ty) + } +} + +impl<'r, DB, N> Decode<'r, DB> for String<N> +where + DB: Database, + StdString: Decode<'r, DB>, + N: Normalize, +{ + fn decode(value: <DB as Database>::ValueRef<'r>) -> Result<Self, sqlx::error::BoxDynError> { + let value = StdString::decode(value)?; + Ok(Self::from(value)) + } +} + +impl<'q, DB, N> Encode<'q, DB> for String<N> +where + DB: Database, + StdString: Encode<'q, DB>, +{ + fn encode_by_ref( + &self, + buf: &mut <DB as Database>::ArgumentBuffer<'q>, + ) -> Result<IsNull, sqlx::error::BoxDynError> { + let Self(value, _) = self; + value.encode_by_ref(buf) + } + + fn encode( + self, + buf: &mut <DB as Database>::ArgumentBuffer<'q>, + ) -> Result<IsNull, sqlx::error::BoxDynError> { + let Self(value, _) = self; + value.encode(buf) + } + + fn produces(&self) -> Option<<DB as Database>::TypeInfo> { + let Self(value, _) = self; + value.produces() + } + + fn size_hint(&self) -> usize { + let Self(value, _) = self; + value.size_hint() + } +} diff --git a/src/setup/app.rs b/src/setup/app.rs index 24e0010..030b5f6 100644 --- a/src/setup/app.rs +++ b/src/setup/app.rs @@ -4,7 +4,8 @@ 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}, + name::Name, token::{repo::Provider as _, Secret}, }; @@ -20,10 +21,10 @@ impl<'a> Setup<'a> { pub async fn initial( &self, - name: &str, + name: &Name, password: &Password, created_at: &DateTime, - ) -> Result<Secret, Error> { + ) -> Result<(Login, Secret), Error> { let password_hash = password.hash()?; let mut tx = self.db.begin().await?; @@ -39,7 +40,7 @@ impl<'a> Setup<'a> { self.events .broadcast(login.events().map(Event::from).collect::<Vec<_>>()); - Ok(secret) + Ok((login.as_created(), secret)) } pub async fn completed(&self) -> Result<bool, sqlx::Error> { diff --git a/src/setup/routes/mod.rs b/src/setup/routes/mod.rs new file mode 100644 index 0000000..e1e1711 --- /dev/null +++ b/src/setup/routes/mod.rs @@ -0,0 +1,9 @@ +use axum::{routing::post, Router}; + +use crate::app::App; + +mod post; + +pub fn router() -> Router<App> { + Router::new().route("/api/setup", post(post::handler)) +} diff --git a/src/setup/routes.rs b/src/setup/routes/post.rs index ff41734..f7b256e 100644 --- a/src/setup/routes.rs +++ b/src/setup/routes/post.rs @@ -2,44 +2,43 @@ use axum::{ extract::{Json, State}, http::StatusCode, response::{IntoResponse, Response}, - routing::post, - Router, }; -use super::app; use crate::{ - app::App, clock::RequestedAt, error::Internal, login::Password, token::extract::IdentityToken, + app::App, + clock::RequestedAt, + error::Internal, + login::{Login, Password}, + name::Name, + setup::app, + token::extract::IdentityCookie, }; -pub fn router() -> Router<App> { - Router::new().route("/api/setup", post(on_setup)) -} - -#[derive(serde::Deserialize)] -struct SetupRequest { - name: String, - password: Password, -} - -async fn on_setup( +pub async fn handler( State(app): State<App>, RequestedAt(setup_at): RequestedAt, - identity: IdentityToken, - Json(request): Json<SetupRequest>, -) -> Result<(IdentityToken, StatusCode), SetupError> { - let secret = app + identity: IdentityCookie, + Json(request): Json<Request>, +) -> Result<(IdentityCookie, Json<Login>), Error> { + let (login, secret) = app .setup() .initial(&request.name, &request.password, &setup_at) .await - .map_err(SetupError)?; + .map_err(Error)?; let identity = identity.set(secret); - Ok((identity, StatusCode::NO_CONTENT)) + Ok((identity, Json(login))) +} + +#[derive(serde::Deserialize)] +pub struct Request { + pub name: Name, + pub password: Password, } #[derive(Debug)] -struct SetupError(app::Error); +pub struct Error(pub app::Error); -impl IntoResponse for SetupError { +impl IntoResponse for Error { fn into_response(self) -> Response { let Self(error) = self; match error { diff --git a/src/test/fixtures/channel.rs b/src/test/fixtures/channel.rs index b678717..8cb38ae 100644 --- a/src/test/fixtures/channel.rs +++ b/src/test/fixtures/channel.rs @@ -1,10 +1,18 @@ +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, + name::Name, +}; pub async fn create(app: &App, created_at: &RequestedAt) -> Channel { let name = propose(); @@ -14,11 +22,29 @@ pub async fn create(app: &App, created_at: &RequestedAt) -> Channel { .expect("should always succeed if the channel is actually new") } -pub fn propose() -> String { - rand::random::<Name>().to_string() +pub fn propose() -> Name { + rand::random::<NameTemplate>().to_string().into() } -struct Name(String); +struct NameTemplate(String); faker_impl_from_templates! { - Name; "{} {}", CityName, FullName; + NameTemplate; "{} {}", CityName, FullName; +} + +pub fn events(event: Event) -> future::Ready<Option<channel::Event>> { + future::ready(match event { + Event::Channel(channel) => Some(channel), + _ => None, + }) +} + +pub fn created(event: channel::Event) -> future::Ready<Option<channel::event::Created>> { + future::ready(match event { + channel::Event::Created(event) => Some(event), + channel::Event::Deleted(_) => None, + }) +} + +pub fn fictitious() -> channel::Id { + channel::Id::generate() } 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/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<bool> { - |event| future::ready(matches!(event, Event::Message(Sent(_)))) -} - -pub fn created() -> impl FnMut(&Event) -> future::Ready<bool> { - |event| future::ready(matches!(event, Event::Channel(Created(_)))) -} diff --git a/src/test/fixtures/identity.rs b/src/test/fixtures/identity.rs index 56b4ffa..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::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: &(String, Password), now: &RequestedAt) -> IdentityToken { - let (name, password) = login; - let token = app - .tokens() - .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: &(String, 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 e5ac716..e308289 100644 --- a/src/test/fixtures/login.rs +++ b/src/test/fixtures/login.rs @@ -5,16 +5,18 @@ use crate::{ app::App, clock::RequestedAt, login::{self, Login, Password}, + name::Name, }; -pub async fn create_with_password(app: &App, created_at: &RequestedAt) -> (String, Password) { +pub async fn create_with_password(app: &App, created_at: &RequestedAt) -> (Name, 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.name, password) } pub async fn create(app: &App, created_at: &RequestedAt) -> Login { @@ -28,16 +30,16 @@ pub async fn create(app: &App, created_at: &RequestedAt) -> Login { pub fn fictitious() -> Login { Login { id: login::Id::generate(), - name: name(), + name: propose_name(), } } -pub fn propose() -> (String, Password) { - (name(), propose_password()) +pub fn propose() -> (Name, Password) { + (propose_name(), propose_password()) } -fn name() -> String { - rand::random::<internet::Username>().to_string() +fn propose_name() -> Name { + rand::random::<internet::Username>().to_string().into() } pub fn propose_password() -> Password { diff --git a/src/test/fixtures/message.rs b/src/test/fixtures/message.rs index 381b10b..3aebdd9 100644 --- a/src/test/fixtures/message.rs +++ b/src/test/fixtures/message.rs @@ -1,16 +1,36 @@ +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, Body, Message}, +}; -pub async fn send(app: &App, channel: &Channel, login: &Login, sent_at: &RequestedAt) -> Message { +pub async fn send(app: &App, channel: &Channel, sender: &Login, sent_at: &RequestedAt) -> Message { let body = propose(); app.messages() - .send(&channel.id, login, sent_at, &body) + .send(&channel.id, sender, sent_at, &body) .await .expect("should succeed if the channel exists") } -pub fn propose() -> String { - rand::random::<Paragraphs>().to_string() +pub fn propose() -> Body { + rand::random::<Paragraphs>().to_string().into() +} + +pub fn events(event: Event) -> future::Ready<Option<message::Event>> { + future::ready(match event { + Event::Message(event) => Some(event), + _ => None, + }) +} + +pub fn fictitious() -> message::Id { + message::Id::generate() } diff --git a/src/test/fixtures/mod.rs b/src/test/fixtures/mod.rs index 41f7e13..9111811 100644 --- a/src/test/fixtures/mod.rs +++ b/src/test/fixtures/mod.rs @@ -3,8 +3,8 @@ use chrono::{TimeDelta, Utc}; use crate::{app::App, clock::RequestedAt, db}; pub mod channel; +pub mod cookie; pub mod event; -pub mod filter; pub mod future; pub mod identity; pub mod login; @@ -21,6 +21,11 @@ pub fn now() -> RequestedAt { Utc::now().into() } +pub fn old() -> RequestedAt { + let timestamp = Utc::now() - TimeDelta::days(95); + timestamp.into() +} + pub fn ancient() -> RequestedAt { let timestamp = Utc::now() - TimeDelta::days(365); timestamp.into() diff --git a/src/token/app.rs b/src/token/app.rs index 15fd858..c19d6a0 100644 --- a/src/token/app.rs +++ b/src/token/app.rs @@ -7,12 +7,14 @@ use futures::{ use sqlx::sqlite::SqlitePool; use super::{ - repo::auth::Provider as _, repo::Provider as _, Broadcaster, Event as TokenEvent, Id, Secret, + repo::{self, auth::Provider as _, Provider as _}, + Broadcaster, Event as TokenEvent, Id, Secret, }; use crate::{ clock::DateTime, db::NotFound as _, login::{Login, Password}, + name::{self, Name}, }; pub struct Tokens<'a> { @@ -27,10 +29,10 @@ impl<'a> Tokens<'a> { pub async fn login( &self, - name: &str, + name: &Name, password: &Password, login_at: &DateTime, - ) -> Result<Secret, LoginError> { + ) -> Result<(Login, Secret), LoginError> { let mut tx = self.db.begin().await?; let (login, stored_hash) = tx .auth() @@ -45,6 +47,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 +58,7 @@ impl<'a> Tokens<'a> { Err(LoginError::Rejected)? }; - Ok(token) + Ok((snapshot, token)) } pub async fn validate( @@ -63,14 +67,16 @@ impl<'a> Tokens<'a> { used_at: &DateTime, ) -> Result<(Id, Login), ValidateError> { let mut tx = self.db.begin().await?; - let login = tx + let (token, login) = tx .tokens() .validate(secret, used_at) .await .not_found(|| ValidateError::InvalidToken)?; tx.commit().await?; - Ok(login) + let login = login.as_snapshot().ok_or(ValidateError::LoginDeleted)?; + + Ok((token, login)) } pub async fn limit_stream<E>( @@ -158,17 +164,42 @@ pub enum LoginError { #[error("invalid login")] Rejected, #[error(transparent)] - DatabaseError(#[from] sqlx::Error), + Database(#[from] sqlx::Error), + #[error(transparent)] + Name(#[from] name::Error), #[error(transparent)] - PasswordHashError(#[from] password_hash::Error), + PasswordHash(#[from] password_hash::Error), +} + +impl From<repo::auth::LoadError> for LoginError { + fn from(error: repo::auth::LoadError) -> Self { + use repo::auth::LoadError; + match error { + LoadError::Database(error) => error.into(), + LoadError::Name(error) => error.into(), + } + } } #[derive(Debug, thiserror::Error)] pub enum ValidateError { #[error("invalid token")] InvalidToken, + #[error("login deleted")] + LoginDeleted, + #[error(transparent)] + Database(#[from] sqlx::Error), #[error(transparent)] - DatabaseError(#[from] sqlx::Error), + Name(#[from] name::Error), +} + +impl From<repo::LoadError> for ValidateError { + fn from(error: repo::LoadError) -> Self { + match error { + repo::LoadError::Database(error) => error.into(), + repo::LoadError::Name(error) => error.into(), + } + } } #[derive(Debug)] diff --git a/src/token/extract/identity_token.rs b/src/token/extract/cookie.rs index a1e900e..af5787d 100644 --- a/src/token/extract/identity_token.rs +++ b/src/token/extract/cookie.rs @@ -12,19 +12,21 @@ 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 { +pub struct Identity { cookies: CookieJar, } -impl fmt::Debug for IdentityToken { +impl fmt::Debug for Identity { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("IdentityToken") + f.debug_struct("IdentityCookie") .field("identity", &self.secret()) .finish() } } -impl IdentityToken { +impl Identity { + const COOKIE_NAME: &str = "identity"; + // Creates a new, unpopulated identity token store. #[cfg(test)] pub fn new() -> Self { @@ -40,7 +42,7 @@ impl IdentityToken { // included. pub fn secret(&self) -> Option<Secret> { self.cookies - .get(IDENTITY_COOKIE) + .get(Self::COOKIE_NAME) .map(Cookie::value) .map(Secret::from) } @@ -49,7 +51,7 @@ impl IdentityToken { // back to the client when this extractor is included in a response. pub fn set(self, secret: impl Into<Secret>) -> Self { let secret = secret.into().reveal(); - let identity_cookie = Cookie::build((IDENTITY_COOKIE, secret)) + let identity_cookie = Cookie::build((Self::COOKIE_NAME, secret)) .http_only(true) .path("/") .permanent() @@ -64,15 +66,13 @@ impl IdentityToken { // extractor is included in a response. pub fn clear(self) -> Self { Self { - cookies: self.cookies.remove(IDENTITY_COOKIE), + cookies: self.cookies.remove(Self::COOKIE_NAME), } } } -const IDENTITY_COOKIE: &str = "identity"; - #[async_trait::async_trait] -impl<S> FromRequestParts<S> for IdentityToken +impl<S> FromRequestParts<S> for Identity where S: Send + Sync, { @@ -84,7 +84,7 @@ where } } -impl IntoResponseParts for IdentityToken { +impl IntoResponseParts for Identity { type Error = <CookieJar as IntoResponseParts>::Error; fn into_response_parts(self, res: ResponseParts) -> Result<ResponseParts, Self::Error> { diff --git a/src/token/extract/identity.rs b/src/token/extract/identity.rs index 60ad220..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,19 +25,10 @@ impl FromRequestParts<App> for Identity { type Rejection = LoginError<Internal>; async fn from_request_parts(parts: &mut Parts, state: &App) -> Result<Self, Self::Rejection> { - // After Rust 1.82 (and #[feature(min_exhaustive_patterns)] lands on - // stable), the following can be replaced: - // - // ``` - // let Ok(identity_token) = IdentityToken::from_request_parts( - // parts, - // state, - // ).await; - // ``` - let 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::<App>::from_request_parts(parts, state).await?; match app.tokens().validate(&secret, &used_at).await { 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/token/repo/auth.rs b/src/token/repo/auth.rs index 9aee81f..bdc4c33 100644 --- a/src/token/repo/auth.rs +++ b/src/token/repo/auth.rs @@ -2,8 +2,10 @@ use sqlx::{sqlite::Sqlite, SqliteConnection, Transaction}; use crate::{ clock::DateTime, + db::NotFound, event::{Instant, Sequence}, login::{self, password::StoredHash, History, Login}, + name::{self, Name}, }; pub trait Provider { @@ -19,38 +21,53 @@ impl<'c> Provider for Transaction<'c, Sqlite> { pub struct Auth<'t>(&'t mut SqliteConnection); impl<'t> Auth<'t> { - pub async fn for_name(&mut self, name: &str) -> Result<(History, StoredHash), sqlx::Error> { - let found = sqlx::query!( + pub async fn for_name(&mut self, name: &Name) -> Result<(History, StoredHash), LoadError> { + let name = name.canonical(); + let row = sqlx::query!( r#" - select - id as "id: login::Id", - name, - password_hash as "password_hash: StoredHash", + select + id as "id: login::Id", + display_name as "display_name: String", + canonical_name as "canonical_name: String", created_sequence as "created_sequence: Sequence", - created_at as "created_at: DateTime" - from login - where name = $1 - "#, + created_at as "created_at: DateTime", + password_hash as "password_hash: StoredHash" + from login + where canonical_name = $1 + "#, name, ) - .map(|row| { - ( - History { - login: Login { - id: row.id, - name: row.name, - }, - created: Instant { - at: row.created_at, - sequence: row.created_sequence, - }, - }, - row.password_hash, - ) - }) .fetch_one(&mut *self.0) .await?; - Ok(found) + let login = History { + login: Login { + id: row.id, + name: Name::new(row.display_name, row.canonical_name)?, + }, + created: Instant::new(row.created_at, row.created_sequence), + }; + + Ok((login, row.password_hash)) + } +} + +#[derive(Debug, thiserror::Error)] +#[error(transparent)] +pub enum LoadError { + Database(#[from] sqlx::Error), + Name(#[from] name::Error), +} + +impl<T> NotFound for Result<T, LoadError> { + type Ok = T; + type Error = LoadError; + + fn optional(self) -> Result<Option<T>, LoadError> { + match self { + Ok(value) => Ok(Some(value)), + Err(LoadError::Database(sqlx::Error::RowNotFound)) => Ok(None), + Err(other) => Err(other), + } } } diff --git a/src/token/repo/mod.rs b/src/token/repo/mod.rs index 9169743..d8463eb 100644 --- a/src/token/repo/mod.rs +++ b/src/token/repo/mod.rs @@ -1,4 +1,4 @@ pub mod auth; mod token; -pub use self::token::Provider; +pub use self::token::{LoadError, Provider}; diff --git a/src/token/repo/token.rs b/src/token/repo/token.rs index c592dcd..35ea385 100644 --- a/src/token/repo/token.rs +++ b/src/token/repo/token.rs @@ -3,7 +3,10 @@ use uuid::Uuid; use crate::{ clock::DateTime, + db::NotFound, + event::{Instant, Sequence}, login::{self, History, Login}, + name::{self, Name}, token::{Id, Secret}, }; @@ -100,53 +103,78 @@ impl<'c> Tokens<'c> { } // Validate a token by its secret, retrieving the associated Login record. - // Will return [None] if the token is not valid. The token's last-used - // timestamp will be set to `used_at`. + // Will return an error if the token is not valid. If successful, the + // retrieved token's last-used timestamp will be set to `used_at`. pub async fn validate( &mut self, secret: &Secret, used_at: &DateTime, - ) -> Result<(Id, Login), sqlx::Error> { + ) -> Result<(Id, History), LoadError> { // I would use `update … returning` to do this in one query, but // sqlite3, as of this writing, does not allow an update's `returning` // clause to reference columns from tables joined into the update. Two // queries is fine, but it feels untidy. - sqlx::query!( + let (token, login) = sqlx::query!( r#" update token set last_used_at = $1 where secret = $2 + returning + id as "token: Id", + login as "login: login::Id" "#, used_at, secret, ) - .execute(&mut *self.0) + .map(|row| (row.token, row.login)) + .fetch_one(&mut *self.0) .await?; let login = sqlx::query!( r#" select - token.id as "token_id: Id", - login.id as "login_id: login::Id", - login.name as "login_name" + id as "id: login::Id", + display_name as "display_name: String", + canonical_name as "canonical_name: String", + created_sequence as "created_sequence: Sequence", + created_at as "created_at: DateTime" from login - join token on login.id = token.login - where token.secret = $1 + where id = $1 "#, - secret, + login, ) .map(|row| { - ( - row.token_id, - Login { - id: row.login_id, - name: row.login_name, + Ok::<_, name::Error>(History { + login: Login { + id: row.id, + name: Name::new(row.display_name, row.canonical_name)?, }, - ) + created: Instant::new(row.created_at, row.created_sequence), + }) }) .fetch_one(&mut *self.0) - .await?; + .await??; + + Ok((token, login)) + } +} + +#[derive(Debug, thiserror::Error)] +#[error(transparent)] +pub enum LoadError { + Database(#[from] sqlx::Error), + Name(#[from] name::Error), +} + +impl<T> NotFound for Result<T, LoadError> { + type Ok = T; + type Error = LoadError; - Ok(login) + fn optional(self) -> Result<Option<T>, LoadError> { + match self { + Ok(value) => Ok(Some(value)), + Err(LoadError::Database(sqlx::Error::RowNotFound)) => Ok(None), + Err(other) => Err(other), + } } } diff --git a/src/ui.rs b/src/ui.rs deleted file mode 100644 index 91d0eb8..0000000 --- a/src/ui.rs +++ /dev/null @@ -1,134 +0,0 @@ -use axum::{ - extract::{Path, Request, State}, - http::{header, StatusCode}, - middleware::{self, Next}, - response::{IntoResponse, Redirect, Response}, - routing::get, - Router, -}; -use mime_guess::Mime; -use rust_embed::EmbeddedFile; - -use crate::{app::App, channel, error::Internal, invite, login::Login}; - -#[derive(rust_embed::Embed)] -#[folder = "target/ui"] -struct Assets; - -impl Assets { - fn load(path: impl AsRef<str>) -> Result<Asset, NotFound<String>> { - let path = path.as_ref(); - let mime = mime_guess::from_path(path).first_or_octet_stream(); - - Self::get(path) - .map(|file| Asset(mime, file)) - .ok_or(NotFound(format!("not found: {path}"))) - } - - fn index() -> Result<Asset, Internal> { - // "not found" in this case really is an internal error, as it should - // never happen. `index.html` is a known-valid path. - Ok(Self::load("index.html")?) - } -} - -pub fn router(app: &App) -> Router<App> { - [ - Router::new() - .route("/*path", get(asset)) - .route("/setup", get(setup)), - Router::new() - .route("/", get(root)) - .route("/login", get(login)) - .route("/ch/:channel", get(channel)) - .route("/invite/:invite", get(invite)) - .route_layer(middleware::from_fn_with_state(app.clone(), setup_required)), - ] - .into_iter() - .fold(Router::default(), Router::merge) -} - -async fn asset(Path(path): Path<String>) -> Result<Asset, NotFound<String>> { - Assets::load(path) -} - -async fn root(login: Option<Login>) -> Result<impl IntoResponse, Internal> { - if login.is_none() { - Ok(Redirect::temporary("/login").into_response()) - } else { - Ok(Assets::index()?.into_response()) - } -} - -async fn login() -> Result<impl IntoResponse, Internal> { - Assets::index() -} - -async fn setup(State(app): State<App>) -> Result<impl IntoResponse, Internal> { - if app.setup().completed().await? { - Ok(Redirect::to("/login").into_response()) - } else { - Ok(Assets::index().into_response()) - } -} - -async fn channel( - State(app): State<App>, - login: Option<Login>, - Path(channel): Path<channel::Id>, -) -> Result<impl IntoResponse, Internal> { - if login.is_none() { - Ok(Redirect::temporary("/").into_response()) - } else if app.channels().get(&channel).await?.is_none() { - Ok(NotFound(Assets::index()?).into_response()) - } else { - Ok(Assets::index()?.into_response()) - } -} - -async fn invite( - State(app): State<App>, - Path(invite): Path<invite::Id>, -) -> Result<impl IntoResponse, Internal> { - match app.invites().get(&invite).await { - Ok(_) => Ok(Assets::index()?.into_response()), - Err(invite::app::Error::NotFound(_)) => Ok(NotFound(Assets::index()?).into_response()), - Err(other) => Err(Internal::from(other)), - } -} - -struct Asset(Mime, EmbeddedFile); - -impl IntoResponse for Asset { - fn into_response(self) -> Response { - let Self(mime, file) = self; - ( - StatusCode::OK, - [(header::CONTENT_TYPE, mime.as_ref())], - file.data, - ) - .into_response() - } -} - -#[derive(Debug, thiserror::Error)] -#[error("{0}")] -struct NotFound<E>(pub E); - -impl<E> IntoResponse for NotFound<E> -where - E: IntoResponse, -{ - fn into_response(self) -> Response { - let Self(response) = self; - (StatusCode::NOT_FOUND, response).into_response() - } -} - -pub async fn setup_required(State(app): State<App>, request: Request, next: Next) -> Response { - match app.setup().completed().await { - Ok(true) => next.run(request).await, - Ok(false) => Redirect::to("/setup").into_response(), - Err(error) => Internal::from(error).into_response(), - } -} diff --git a/src/ui/assets.rs b/src/ui/assets.rs new file mode 100644 index 0000000..6a7563a --- /dev/null +++ b/src/ui/assets.rs @@ -0,0 +1,63 @@ +use ::mime::{FromStrError, Mime}; +use axum::{ + http::{header, StatusCode}, + response::{IntoResponse, Response}, +}; +use rust_embed::EmbeddedFile; + +use super::{error::NotFound, mime}; +use crate::error::Internal; + +#[derive(rust_embed::Embed)] +#[folder = "target/ui"] +pub struct Assets; + +impl Assets { + pub fn load(path: impl AsRef<str>) -> Result<Asset, Error> { + let path = path.as_ref(); + let mime = mime::from_path(path)?; + + Self::get(path) + .map(|file| Asset(mime, file)) + .ok_or(Error::NotFound(path.into())) + } + + pub fn index() -> Result<Asset, Internal> { + // "not found" in this case really is an internal error, as it should + // never happen. `index.html` is a known-valid path with a known-valid + // file extension. + Ok(Self::load("index.html")?) + } +} + +pub struct Asset(Mime, EmbeddedFile); + +impl IntoResponse for Asset { + fn into_response(self) -> Response { + let Self(mime, file) = self; + ( + StatusCode::OK, + [(header::CONTENT_TYPE, mime.as_ref())], + file.data, + ) + .into_response() + } +} + +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("not found: {0}")] + NotFound(String), + #[error(transparent)] + Mime(#[from] FromStrError), +} + +impl IntoResponse for Error { + fn into_response(self) -> Response { + #[allow(clippy::match_wildcard_for_single_variants)] + match self { + Self::NotFound(_) => NotFound(self.to_string()).into_response(), + other => Internal::from(other).into_response(), + } + } +} diff --git a/src/ui/error.rs b/src/ui/error.rs new file mode 100644 index 0000000..2dc627f --- /dev/null +++ b/src/ui/error.rs @@ -0,0 +1,18 @@ +use axum::{ + http::StatusCode, + response::{IntoResponse, Response}, +}; + +#[derive(Debug, thiserror::Error)] +#[error("{0}")] +pub struct NotFound<E>(pub E); + +impl<E> IntoResponse for NotFound<E> +where + E: IntoResponse, +{ + fn into_response(self) -> Response { + let Self(response) = self; + (StatusCode::NOT_FOUND, response).into_response() + } +} diff --git a/src/ui/middleware.rs b/src/ui/middleware.rs new file mode 100644 index 0000000..f60ee1c --- /dev/null +++ b/src/ui/middleware.rs @@ -0,0 +1,15 @@ +use axum::{ + extract::{Request, State}, + middleware::Next, + response::{IntoResponse, Redirect, Response}, +}; + +use crate::{app::App, error::Internal}; + +pub async fn setup_required(State(app): State<App>, request: Request, next: Next) -> Response { + match app.setup().completed().await { + Ok(true) => next.run(request).await, + Ok(false) => Redirect::to("/setup").into_response(), + Err(error) => Internal::from(error).into_response(), + } +} diff --git a/src/ui/mime.rs b/src/ui/mime.rs new file mode 100644 index 0000000..9c724f0 --- /dev/null +++ b/src/ui/mime.rs @@ -0,0 +1,22 @@ +use mime::Mime; +use unix_path::Path; + +// Extremely manual; using `std::path` here would result in platform-dependent behaviour when it's not appropriate (the URLs passed here always use `/` and are parsed like URLs). Using `unix_path` might be an option, but it's not clearly +pub fn from_path<P>(path: P) -> Result<Mime, mime::FromStrError> +where + P: AsRef<Path>, +{ + let path = path.as_ref(); + let extension = path.extension().and_then(|ext| ext.to_str()); + let mime = match extension { + Some("css") => "text/css; charset=utf-8", + Some("js") => "text/javascript; charset=utf-8", + Some("json") => "application/json", + Some("html") => "text/html; charset=utf-8", + Some("png") => "image/png", + _ => "application/octet-stream", + }; + let mime = mime.parse()?; + + Ok(mime) +} diff --git a/src/ui/mod.rs b/src/ui/mod.rs new file mode 100644 index 0000000..f8caa48 --- /dev/null +++ b/src/ui/mod.rs @@ -0,0 +1,7 @@ +mod assets; +mod error; +mod middleware; +mod mime; +mod routes; + +pub use self::routes::router; diff --git a/src/ui/routes/ch/channel.rs b/src/ui/routes/ch/channel.rs new file mode 100644 index 0000000..a338f1f --- /dev/null +++ b/src/ui/routes/ch/channel.rs @@ -0,0 +1,61 @@ +pub mod get { + use axum::{ + extract::{Path, State}, + response::{self, IntoResponse, Redirect}, + }; + + use crate::{ + app::App, + channel, + error::Internal, + token::extract::Identity, + ui::{ + assets::{Asset, Assets}, + error::NotFound, + }, + }; + + pub async fn handler( + State(app): State<App>, + identity: Option<Identity>, + Path(channel): Path<channel::Id>, + ) -> Result<Asset, Error> { + let _ = identity.ok_or(Error::NotLoggedIn)?; + app.channels() + .get(&channel) + .await + .map_err(Error::internal)? + .ok_or(Error::NotFound)?; + + Assets::index().map_err(Error::Internal) + } + + #[derive(Debug, thiserror::Error)] + pub enum Error { + #[error("requested channel not found")] + NotFound, + #[error("not logged in")] + NotLoggedIn, + #[error("{0}")] + Internal(Internal), + } + + impl Error { + fn internal(err: impl Into<Internal>) -> Self { + Self::Internal(err.into()) + } + } + + impl IntoResponse for Error { + fn into_response(self) -> response::Response { + match self { + Self::NotFound => match Assets::index() { + Ok(asset) => NotFound(asset).into_response(), + Err(internal) => internal.into_response(), + }, + Self::NotLoggedIn => Redirect::temporary("/login").into_response(), + Self::Internal(error) => error.into_response(), + } + } + } +} diff --git a/src/ui/routes/ch/mod.rs b/src/ui/routes/ch/mod.rs new file mode 100644 index 0000000..ff02972 --- /dev/null +++ b/src/ui/routes/ch/mod.rs @@ -0,0 +1 @@ +pub mod channel; diff --git a/src/ui/routes/get.rs b/src/ui/routes/get.rs new file mode 100644 index 0000000..2fcb51c --- /dev/null +++ b/src/ui/routes/get.rs @@ -0,0 +1,30 @@ +use axum::response::{self, IntoResponse, Redirect}; + +use crate::{ + error::Internal, + token::extract::Identity, + ui::assets::{Asset, Assets}, +}; + +pub async fn handler(identity: Option<Identity>) -> Result<Asset, Error> { + let _ = identity.ok_or(Error::NotLoggedIn)?; + + Assets::index().map_err(Error::Internal) +} + +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("not logged in")] + NotLoggedIn, + #[error("{0}")] + Internal(Internal), +} + +impl IntoResponse for Error { + fn into_response(self) -> response::Response { + match self { + Self::NotLoggedIn => Redirect::temporary("/login").into_response(), + Self::Internal(error) => error.into_response(), + } + } +} diff --git a/src/ui/routes/invite/invite.rs b/src/ui/routes/invite/invite.rs new file mode 100644 index 0000000..06e5792 --- /dev/null +++ b/src/ui/routes/invite/invite.rs @@ -0,0 +1,55 @@ +pub mod get { + use axum::{ + extract::{Path, State}, + response::{self, IntoResponse}, + }; + + use crate::{ + app::App, + error::Internal, + invite, + ui::{ + assets::{Asset, Assets}, + error::NotFound, + }, + }; + + pub async fn handler( + State(app): State<App>, + Path(invite): Path<invite::Id>, + ) -> Result<Asset, Error> { + app.invites() + .get(&invite) + .await + .map_err(Error::internal)? + .ok_or(Error::NotFound)?; + + Assets::index().map_err(Error::Internal) + } + + #[derive(Debug, thiserror::Error)] + pub enum Error { + #[error("invite not found")] + NotFound, + #[error("{0}")] + Internal(Internal), + } + + impl Error { + fn internal(err: impl Into<Internal>) -> Self { + Self::Internal(err.into()) + } + } + + impl IntoResponse for Error { + fn into_response(self) -> response::Response { + match self { + Self::NotFound => match Assets::index() { + Ok(asset) => NotFound(asset).into_response(), + Err(internal) => internal.into_response(), + }, + Self::Internal(error) => error.into_response(), + } + } + } +} diff --git a/src/ui/routes/invite/mod.rs b/src/ui/routes/invite/mod.rs new file mode 100644 index 0000000..50af8be --- /dev/null +++ b/src/ui/routes/invite/mod.rs @@ -0,0 +1,4 @@ +// In this case, the first redundant `invite` is a literal path segment, and the +// second `invite` reflects a placeholder. +#[allow(clippy::module_inception)] +pub mod invite; diff --git a/src/ui/routes/login.rs b/src/ui/routes/login.rs new file mode 100644 index 0000000..81a874c --- /dev/null +++ b/src/ui/routes/login.rs @@ -0,0 +1,11 @@ +pub mod get { + use crate::{ + error::Internal, + ui::assets::{Asset, Assets}, + }; + + #[allow(clippy::unused_async)] + pub async fn handler() -> Result<Asset, Internal> { + Assets::index() + } +} diff --git a/src/ui/routes/mod.rs b/src/ui/routes/mod.rs new file mode 100644 index 0000000..72d9a4a --- /dev/null +++ b/src/ui/routes/mod.rs @@ -0,0 +1,26 @@ +use axum::{middleware, routing::get, Router}; + +use crate::{app::App, ui::middleware::setup_required}; + +mod ch; +mod get; +mod invite; +mod login; +mod path; +mod setup; + +pub fn router(app: &App) -> Router<App> { + [ + Router::new() + .route("/*path", get(path::get::handler)) + .route("/setup", get(setup::get::handler)), + Router::new() + .route("/", get(get::handler)) + .route("/login", get(login::get::handler)) + .route("/ch/:channel", get(ch::channel::get::handler)) + .route("/invite/:invite", get(invite::invite::get::handler)) + .route_layer(middleware::from_fn_with_state(app.clone(), setup_required)), + ] + .into_iter() + .fold(Router::default(), Router::merge) +} diff --git a/src/ui/routes/path.rs b/src/ui/routes/path.rs new file mode 100644 index 0000000..a387552 --- /dev/null +++ b/src/ui/routes/path.rs @@ -0,0 +1,9 @@ +pub mod get { + use axum::extract::Path; + + use crate::ui::assets::{Asset, Assets, Error}; + + pub async fn handler(Path(path): Path<String>) -> Result<Asset, Error> { + Assets::load(path) + } +} diff --git a/src/ui/routes/setup.rs b/src/ui/routes/setup.rs new file mode 100644 index 0000000..649cc5f --- /dev/null +++ b/src/ui/routes/setup.rs @@ -0,0 +1,43 @@ +pub mod get { + use axum::{ + extract::State, + response::{self, IntoResponse, Redirect}, + }; + + use crate::{ + app::App, + error::Internal, + ui::assets::{Asset, Assets}, + }; + + pub async fn handler(State(app): State<App>) -> Result<Asset, Error> { + if app + .setup() + .completed() + .await + .map_err(Internal::from) + .map_err(Error::Internal)? + { + Err(Error::SetupCompleted) + } else { + Assets::index().map_err(Error::Internal) + } + } + + #[derive(Debug, thiserror::Error)] + pub enum Error { + #[error("setup already completed")] + SetupCompleted, + #[error("{0}")] + Internal(Internal), + } + + impl IntoResponse for Error { + fn into_response(self) -> response::Response { + match self { + Self::SetupCompleted => Redirect::to("/login").into_response(), + Self::Internal(error) => error.into_response(), + } + } + } +} diff --git a/ui/routes/(login)/invite/[invite]/+page.js b/ui/routes/(login)/invite/[invite]/+page.js index d90f542..e6664d2 100644 --- a/ui/routes/(login)/invite/[invite]/+page.js +++ b/ui/routes/(login)/invite/[invite]/+page.js @@ -5,7 +5,8 @@ export async function load({ params }) { let response = await getInvite(invite); switch (response.status) { case 200: - return response.data; + let invite = response.data + return { invite }; break; case 404: return null; diff --git a/ui/routes/(login)/invite/[invite]/+page.svelte b/ui/routes/(login)/invite/[invite]/+page.svelte index eea05fc..b9a4a97 100644 --- a/ui/routes/(login)/invite/[invite]/+page.svelte +++ b/ui/routes/(login)/invite/[invite]/+page.svelte @@ -1,20 +1,18 @@ <script> import { goto } from '$app/navigation'; - import { page } from '$app/stores'; import { acceptInvite } from '$lib/apiServer'; - $: inviteId = $page?.params?.invite; - $: invite = $page.data; - import LogIn from '$lib/components/LogIn.svelte'; + export let data; + let disabled; let username; let password; async function onSubmit() { disabled = true; - const response = await acceptInvite(inviteId, username, password); + const response = await acceptInvite(data.invite.id, username, password); if (200 <= response.status && response.status < 300) { username = ''; password = ''; @@ -24,5 +22,9 @@ } </script> -<p>Hi there! {invite.issuer.name} invites you to the conversation.</p> +{#await data} +<p>Loading invitation…</p> +{:then { invite }} +<p>Hi there! {invite.issuer} invites you to the conversation.</p> <LogIn bind:disabled bind:username bind:password on:submit={onSubmit} /> +{/await} |
