mirror of
https://github.com/aziascreations/BakaShrot.git
synced 2026-11-23 20:58:46 +01:00
Add attachments (protocol 4), their edge-case tests, and handoff docs
- One optional attachment per message, any size up to the server's MaxAttachmentSize (default 1G), sent and stored in 1 MB parts, checked with its SHA-256. Uploaded before its message (UploadStart, UploadChunk), then attached by the PushMessage in the same transaction; uploads never pushed expire after UploadTimeout. Read back a part at a time (GetAttachment). - Replicated separately, after the messages: the message carries the size and SHA-256, then each check-in lists what the peer is missing (MissingAttachments) and sends the parts from where it stopped. Over the receiver's limit, the attachment is marked not kept. - Deleted with its message by the retention, parts cleaned up in the background. Schema v7 (attachments, blobs, blob_chunks), replacing the unused attachements table. - DLL: PushMessageWithFile/WithData, SaveAttachment, LoadAttachment, GetMessageAttachmentSize, IsMessageAttachmentReady. Python: push(..., attachment=), get_attachment(), save_attachment(). Tools: PushMessage -a, GetAttachment. The release smoke test round-trips one. - Tests/Attachments-Test.ps1 (39 checks) and Tests/AttachmentEdges-Test.ps1 (51 checks, with a raw protocol client): wrong SHA-256, bad parts, others' uploads, expiry, replication resuming after a kill, a corrupted stored copy. Found: a corrupted copy is re-sent to peers forever, noted as open item 3 in Notes.md with a proposed fix. - CLAUDE.md: how to build, test, the traps and working rules, for the next session. Notes.md and the Design docs updated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RwFeVPXGLs3KK1MAQn3ouP
This commit is contained in:
@@ -172,12 +172,14 @@ try {
|
|||||||
# Example app using the DLL, run it from ./Build while the server runs.
|
# Example app using the DLL, run it from ./Build while the server runs.
|
||||||
Invoke-Compiler "Client\BakaShrot_Client_Prototypes.pbi" "ClientExample.exe" @("/CONSOLE")
|
Invoke-Compiler "Client\BakaShrot_Client_Prototypes.pbi" "ClientExample.exe" @("/CONSOLE")
|
||||||
# Tools using the DLL, same as the example:
|
# Tools using the DLL, same as the example:
|
||||||
# PushMessage [-t <Topic>] <Json|@JsonFile> [ClientIni]
|
# PushMessage [-t <Topic>] [-a <File>] <Json|@JsonFile> [ClientIni]
|
||||||
# GetLatestMessage <Topic> <Node> [ClientIni]
|
# GetLatestMessage <Topic> <Node> [ClientIni]
|
||||||
Invoke-Compiler "Tools\PushMessage\PushMessage.pb" "PushMessage.exe" @("/CONSOLE")
|
Invoke-Compiler "Tools\PushMessage\PushMessage.pb" "PushMessage.exe" @("/CONSOLE")
|
||||||
Invoke-Compiler "Tools\GetLatestMessage\GetLatestMessage.pb" "GetLatestMessage.exe" @("/CONSOLE")
|
Invoke-Compiler "Tools\GetLatestMessage\GetLatestMessage.pb" "GetLatestMessage.exe" @("/CONSOLE")
|
||||||
# GetMessages <Topic> <Node> [--after <Id|latest>] [--limit <N>] [--follow] [ClientIni]
|
# GetMessages <Topic> <Node> [--after <Id|latest>] [--limit <N>] [--follow] [ClientIni]
|
||||||
Invoke-Compiler "Tools\GetMessages\GetMessages.pb" "GetMessages.exe" @("/CONSOLE")
|
Invoke-Compiler "Tools\GetMessages\GetMessages.pb" "GetMessages.exe" @("/CONSOLE")
|
||||||
|
# GetAttachment <Topic> <Node> <MessageId> <OutFile> [ClientIni]
|
||||||
|
Invoke-Compiler "Tools\GetAttachment\GetAttachment.pb" "GetAttachment.exe" @("/CONSOLE")
|
||||||
# Query <Sql|@SqlFile> [ClientIni]
|
# Query <Sql|@SqlFile> [ClientIni]
|
||||||
Invoke-Compiler "Tools\Query\Query.pb" "Query.exe" @("/CONSOLE")
|
Invoke-Compiler "Tools\Query\Query.pb" "Query.exe" @("/CONSOLE")
|
||||||
# Resolve <topic|node> <NameOrId> [ClientIni]
|
# Resolve <topic|node> <NameOrId> [ClientIni]
|
||||||
|
|||||||
@@ -0,0 +1,99 @@
|
|||||||
|
# BakaShrot - start here
|
||||||
|
|
||||||
|
A message store with replication, in PureBasic: servers take JSON (or any)
|
||||||
|
messages per topic/node from authenticated clients, store them in SQLite,
|
||||||
|
and replicate them between peers by name. Clients: a DLL, CLI tools, a
|
||||||
|
Python module. An **internal tool on trusted machines**: correctness and
|
||||||
|
operations come before security hardening (`Notes.md`, "Threat model").
|
||||||
|
|
||||||
|
## Read first
|
||||||
|
|
||||||
|
1. `Notes.md`: where things stand, "Open items, by importance" (the to-do
|
||||||
|
list, item 3 is the next known bug), "Testing tips".
|
||||||
|
2. `Design/`, by topic: `Packets.md` (the protocol, where every file lives,
|
||||||
|
code conventions), `Attachments.md`, `Cryptography.md`,
|
||||||
|
`StorageConcurrency.md`, `ReplicationIssues.md`, `Release.md`,
|
||||||
|
`Suggestions.md`.
|
||||||
|
3. `git log --oneline` and `git status`: what's committed. Work happens on
|
||||||
|
branches off `master` (`timestamps-retention` at this writing).
|
||||||
|
|
||||||
|
## Build
|
||||||
|
|
||||||
|
- Dev compiler, PureBasic 5.73: `C:\Program Files\PureBasic_573\Compilers\pbcompiler.exe <src> /EXE <out> [flags]`.
|
||||||
|
Release compiler, 6.40 C backend: `C:\Program Files\PureBasic_640\Compilers\pbcompilerc.exe <src> /OUTPUT <out> /OPTIMIZER`.
|
||||||
|
Code must compile with both (`Release.ps1` checks the 6.40 side).
|
||||||
|
- `Build.ps1` builds everything into `Build\`, **regenerates keys and
|
||||||
|
configs, then runs a server waiting on its console**: don't run it from
|
||||||
|
an automated shell. To rebuild after a change, compile what changed:
|
||||||
|
|
||||||
|
| Source | Output | Flags |
|
||||||
|
|---|---|---|
|
||||||
|
| `Server\BakaShrot_Server.pb` | `Build\BakaShrot_Server.exe` | `/CONSOLE /THREAD` |
|
||||||
|
| `Client\BakaShrot_Client.pbi` | `Build\BakaShrot_Client.dll` | `/DLL /THREAD` |
|
||||||
|
| `Tools\<Name>\<Name>.pb` (PushMessage, GetLatestMessage, GetMessages, GetAttachment, Query, Resolve, ListNames, KeyGen) | `Build\<Name>.exe` | `/CONSOLE` |
|
||||||
|
| `Client\BakaShrot_Client_Prototypes.pbi` | `Build\ClientExample.exe` | `/CONSOLE` |
|
||||||
|
| `Tests\Bench\BenchServer.pb` (the server with a stop file, used by every test) | `Build\Bench\BenchServer.exe` | `/CONSOLE /THREAD` |
|
||||||
|
| `Tests\Bench\BenchClient.pb`, `BenchSeed.pb` | `Build\Bench\` | `/CONSOLE /THREAD` |
|
||||||
|
| `Tests\HandshakeTest.pb`, `Tests\CipherTest.pb` | `Build\` | `/CONSOLE` |
|
||||||
|
| `Tests\AttachmentEdgeClient.pb` | `Build\AttachmentEdgeClient.exe` | `/CONSOLE /THREAD` |
|
||||||
|
|
||||||
|
- `Release.ps1 [-Force]` builds the release with 6.40 into `Release\` and
|
||||||
|
smoke-tests it (`-Force` replaces an existing folder of the same name).
|
||||||
|
|
||||||
|
## Test
|
||||||
|
|
||||||
|
Each suite starts its own servers (`BenchServer.exe`) on fixed ports, in a
|
||||||
|
fresh folder under `Build\`, and prints PASS/FAIL lines; exit code 0 means
|
||||||
|
all passed. `powershell -ExecutionPolicy Bypass -File Tests\<Suite>.ps1`:
|
||||||
|
|
||||||
|
| Suite | Ports | Covers |
|
||||||
|
|---|---|---|
|
||||||
|
| `Names-Test.ps1` | 12401-12402 | names/ids, filters, wildcards, replication by name |
|
||||||
|
| `BigMessages-Test.ps1` | 12403-12404 | 16 MB messages, handshake frame limit, `is_json`, query errors |
|
||||||
|
| `GetMessages-Test.ps1` | 12405 | runs of messages, `--follow` |
|
||||||
|
| `Python-Test.ps1` | 12406-12407 | `bakashrot.py` (`check_bakashrot.py`), the wire is encrypted (`wire_check.py`) |
|
||||||
|
| `Retention-Test.ps1` | 12408-12409 | `pushed_at`, retention, schema upgrade (Python) |
|
||||||
|
| `Attachments-Test.ps1` | 12410-12411 | attachments through the tools, replication, limits |
|
||||||
|
| `AttachmentEdges-Test.ps1` | 12413-12414 | raw-protocol edge cases, expiry, resuming, corruption (Python) |
|
||||||
|
|
||||||
|
Plus `Build\HandshakeTest.exe` and `Build\CipherTest.exe` (no server), and
|
||||||
|
the release's smoke test. Speed: `Tests\Bench\Bench-Replication.ps1 -Ramp 10x0 -Parts Ramp`
|
||||||
|
(push ceiling, ~40,800 msg/s for 4 servers). After a change, run every
|
||||||
|
suite: they take a few minutes in all.
|
||||||
|
|
||||||
|
## Traps
|
||||||
|
|
||||||
|
- **Run exes from `Build\`**: the antivirus blocks them in temp folders.
|
||||||
|
- **`Build\` holds private keys**: git-ignored, never publish it.
|
||||||
|
- **PureBasic is single pass**: constants, structures and procedures must
|
||||||
|
be declared before use, so include order matters (e.g. `Config.pbi`
|
||||||
|
includes `Packets.pbi` for its constants).
|
||||||
|
- **`SetDatabase*()` binds the next statement run on that connection**, not
|
||||||
|
a specific one: set them right before their `DatabaseUpdate/Query`.
|
||||||
|
- **PureBasic lists aren't safe to walk from several threads** (`ForEach`
|
||||||
|
moves the shared current element): give each thread its own copy.
|
||||||
|
- **Files mix CRLF and LF**: edits must keep each file's line endings.
|
||||||
|
- **PowerShell 5**: JSON passed as an argument loses its double quotes
|
||||||
|
(tests write it to a file, `@file`), and `@()` can't be passed through
|
||||||
|
`-File`.
|
||||||
|
- **Bash tool heredocs collapse `\\`**, and PureBasic uses `\` for fields:
|
||||||
|
write edit scripts to files, or use the Edit tool.
|
||||||
|
- **The real server needs a console** (it stops at once without input):
|
||||||
|
tests use `BenchServer.exe` and its stop file instead.
|
||||||
|
|
||||||
|
## Working rules
|
||||||
|
|
||||||
|
- **Commit only when the owner asks**, on a branch, not `master`.
|
||||||
|
- **Wire changes bump `#BakaShrot_ProtocolVersion`** (`Packets.pbi`, 4 at
|
||||||
|
this writing); any difference refuses the connection.
|
||||||
|
- **Schema changes** add a `Server/Storage/db_schema_vN.dbml` (v7 at this
|
||||||
|
writing) and a migration in `SetupStorageDatabase()` (`Storage.pbi`),
|
||||||
|
existing databases must keep working.
|
||||||
|
- **Packets** follow `Design/Packets.md` "Code conventions": one file per
|
||||||
|
packet in `Commons/Networking/Packets/`, `_Encode` / `_Decode` (and
|
||||||
|
`_Free` when it holds data), every field validated on decode.
|
||||||
|
- **Every write goes through the writer** (`Server/Storage/Writer.pbi`,
|
||||||
|
under its mutex); reads use the thread's own connection.
|
||||||
|
- **Docs follow the code**: a finished piece gets a "Done: ... (date)"
|
||||||
|
section in `Notes.md`, what's left goes to its open items, and the
|
||||||
|
`Design/` doc of that area is updated with it.
|
||||||
+475
-1
@@ -18,6 +18,8 @@
|
|||||||
; BakaShrot_GetLatestMessage(TopicId, NodeId), then
|
; BakaShrot_GetLatestMessage(TopicId, NodeId), then
|
||||||
; BakaShrot_GetMessageId(), BakaShrot_GetMessageData(),
|
; BakaShrot_GetMessageId(), BakaShrot_GetMessageData(),
|
||||||
; BakaShrot_GetMessagePushedAt() (ms since 1970 UTC),
|
; BakaShrot_GetMessagePushedAt() (ms since 1970 UTC),
|
||||||
|
; BakaShrot_GetMessageAttachmentSize() (0 for none) and
|
||||||
|
; BakaShrot_IsMessageAttachmentReady(),
|
||||||
; BakaShrot_GetMessageTopic() / BakaShrot_GetMessageNode() (names)
|
; BakaShrot_GetMessageTopic() / BakaShrot_GetMessageNode() (names)
|
||||||
; and BakaShrot_GetMessageTopicId() / BakaShrot_GetMessageNodeId()
|
; and BakaShrot_GetMessageTopicId() / BakaShrot_GetMessageNodeId()
|
||||||
; BakaShrot_GetMessages(Topic, Node, AfterMessageId, Limit): the
|
; BakaShrot_GetMessages(Topic, Node, AfterMessageId, Limit): the
|
||||||
@@ -32,6 +34,13 @@
|
|||||||
; id and name, then BakaShrot_GetNamesList() as JSON
|
; id and name, then BakaShrot_GetNamesList() as JSON
|
||||||
; BakaShrot_Query(Sql), raw read-only SQL, then
|
; BakaShrot_Query(Sql), raw read-only SQL, then
|
||||||
; BakaShrot_GetQueryResult()
|
; BakaShrot_GetQueryResult()
|
||||||
|
; Attachments, one per message at most (Design/Attachments.md):
|
||||||
|
; BakaShrot_PushMessageWithFile(Topic, JsonData, FilePath) or
|
||||||
|
; BakaShrot_PushMessageWithData(Topic, JsonData, *Data, Size): the
|
||||||
|
; attachment is uploaded first, the message stored once it all is
|
||||||
|
; BakaShrot_SaveAttachment(Topic, Node, MessageId, FilePath), or
|
||||||
|
; BakaShrot_LoadAttachment(Topic, Node, MessageId) then
|
||||||
|
; BakaShrot_GetAttachmentData(*Buffer, Size): checked with its SHA-256
|
||||||
; If the server refuses a request, the connection stays open and
|
; If the server refuses a request, the connection stays open and
|
||||||
; BakaShrot_GetRefusalReason() tells why.
|
; BakaShrot_GetRefusalReason() tells why.
|
||||||
; 4. BakaShrot_IsConnected(), BakaShrot_Disconnect()
|
; 4. BakaShrot_IsConnected(), BakaShrot_Disconnect()
|
||||||
@@ -88,6 +97,8 @@ Global BakaShrot_Outbound.BakaShrot_Outbound
|
|||||||
; Filled by the requests, see BakaShrot_GetLatestMessage() and BakaShrot_GetRefusalReasonA/W().
|
; Filled by the requests, see BakaShrot_GetLatestMessage() and BakaShrot_GetRefusalReasonA/W().
|
||||||
Global BakaShrot_MessageId.q = 0
|
Global BakaShrot_MessageId.q = 0
|
||||||
Global BakaShrot_MessagePushedAt.q = 0
|
Global BakaShrot_MessagePushedAt.q = 0
|
||||||
|
Global BakaShrot_MessageAttachmentSize.q = 0
|
||||||
|
Global BakaShrot_MessageAttachmentReady.i = #False
|
||||||
Global BakaShrot_MessageData.s = ""
|
Global BakaShrot_MessageData.s = ""
|
||||||
Global BakaShrot_MessageTopicId.l = -1
|
Global BakaShrot_MessageTopicId.l = -1
|
||||||
Global BakaShrot_MessageNodeId.l = -1
|
Global BakaShrot_MessageNodeId.l = -1
|
||||||
@@ -394,10 +405,11 @@ EndProcedure
|
|||||||
; is_json column) into Topic (a name or an id, "" for the client's own
|
; is_json column) into Topic (a name or an id, "" for the client's own
|
||||||
; topic), the server stores it under that topic and this client's node, with
|
; topic), the server stores it under that topic and this client's node, with
|
||||||
; the next message id. The client's PushTopics on the server must allow it.
|
; the next message id. The client's PushTopics on the server must allow it.
|
||||||
|
; UploadId: its attachment, uploaded with BakaShrot_Upload(), 0 for none.
|
||||||
; Returns the new message's id (1 or more), or -1 on failure.
|
; Returns the new message's id (1 or more), or -1 on failure.
|
||||||
; On -1, BakaShrot_IsConnected() tells if the server refused it (still
|
; On -1, BakaShrot_IsConnected() tells if the server refused it (still
|
||||||
; connected, see BakaShrot_GetRefusalReason()) or if the connection failed.
|
; connected, see BakaShrot_GetRefusalReason()) or if the connection failed.
|
||||||
Procedure.q BakaShrot_PushMessageToString(Topic.s, JsonData.s)
|
Procedure.q BakaShrot_PushMessageToString(Topic.s, JsonData.s, UploadId.q = 0)
|
||||||
Protected Push.BakaShrot_PushMessage
|
Protected Push.BakaShrot_PushMessage
|
||||||
Protected *Pushed.BakaShrot_MessagePushed
|
Protected *Pushed.BakaShrot_MessagePushed
|
||||||
Protected *Request, RequestSize.Integer, *Answer, AnswerSize.Integer
|
Protected *Request, RequestSize.Integer, *Answer, AnswerSize.Integer
|
||||||
@@ -421,6 +433,7 @@ Procedure.q BakaShrot_PushMessageToString(Topic.s, JsonData.s)
|
|||||||
|
|
||||||
Push\Topic = Topic
|
Push\Topic = Topic
|
||||||
Push\JsonData = JsonData
|
Push\JsonData = JsonData
|
||||||
|
Push\UploadId = UploadId
|
||||||
*Request = BakaShrot_PushMessagePacket_Encode(@Push, @RequestSize)
|
*Request = BakaShrot_PushMessagePacket_Encode(@Push, @RequestSize)
|
||||||
If Not *Request
|
If Not *Request
|
||||||
ProcedureReturn -1
|
ProcedureReturn -1
|
||||||
@@ -514,6 +527,8 @@ Procedure.i BakaShrot_GetLatestMessageOfString(Topic.s, Node.s)
|
|||||||
BakaShrot_RefusalReason = ""
|
BakaShrot_RefusalReason = ""
|
||||||
BakaShrot_MessageId = 0
|
BakaShrot_MessageId = 0
|
||||||
BakaShrot_MessagePushedAt = 0
|
BakaShrot_MessagePushedAt = 0
|
||||||
|
BakaShrot_MessageAttachmentSize = 0
|
||||||
|
BakaShrot_MessageAttachmentReady = #False
|
||||||
BakaShrot_MessageData = ""
|
BakaShrot_MessageData = ""
|
||||||
BakaShrot_MessageTopicId = -1
|
BakaShrot_MessageTopicId = -1
|
||||||
BakaShrot_MessageNodeId = -1
|
BakaShrot_MessageNodeId = -1
|
||||||
@@ -568,6 +583,8 @@ Procedure.i BakaShrot_GetLatestMessageOfString(Topic.s, Node.s)
|
|||||||
If IsExpected
|
If IsExpected
|
||||||
BakaShrot_MessageId = *Latest\MessageId
|
BakaShrot_MessageId = *Latest\MessageId
|
||||||
BakaShrot_MessagePushedAt = *Latest\PushedAt
|
BakaShrot_MessagePushedAt = *Latest\PushedAt
|
||||||
|
BakaShrot_MessageAttachmentSize = *Latest\AttachmentSize
|
||||||
|
BakaShrot_MessageAttachmentReady = *Latest\AttachmentReady
|
||||||
BakaShrot_MessageData = *Latest\JsonData
|
BakaShrot_MessageData = *Latest\JsonData
|
||||||
BakaShrot_MessageTopicId = *Latest\TopicId
|
BakaShrot_MessageTopicId = *Latest\TopicId
|
||||||
BakaShrot_MessageNodeId = *Latest\NodeId
|
BakaShrot_MessageNodeId = *Latest\NodeId
|
||||||
@@ -576,6 +593,8 @@ Procedure.i BakaShrot_GetLatestMessageOfString(Topic.s, Node.s)
|
|||||||
AddElement(BakaShrot_Messages())
|
AddElement(BakaShrot_Messages())
|
||||||
BakaShrot_Messages()\MessageId = *Latest\MessageId
|
BakaShrot_Messages()\MessageId = *Latest\MessageId
|
||||||
BakaShrot_Messages()\PushedAt = *Latest\PushedAt
|
BakaShrot_Messages()\PushedAt = *Latest\PushedAt
|
||||||
|
BakaShrot_Messages()\AttachmentSize = *Latest\AttachmentSize
|
||||||
|
BakaShrot_Messages()\AttachmentReady = *Latest\AttachmentReady
|
||||||
BakaShrot_Messages()\JsonData = *Latest\JsonData
|
BakaShrot_Messages()\JsonData = *Latest\JsonData
|
||||||
EndIf
|
EndIf
|
||||||
FreeStructure(*Latest)
|
FreeStructure(*Latest)
|
||||||
@@ -633,6 +652,8 @@ Procedure.l BakaShrot_GetMessagesString(Topic.s, Node.s, AfterMessageId.q, Limit
|
|||||||
BakaShrot_RefusalReason = ""
|
BakaShrot_RefusalReason = ""
|
||||||
BakaShrot_MessageId = 0
|
BakaShrot_MessageId = 0
|
||||||
BakaShrot_MessagePushedAt = 0
|
BakaShrot_MessagePushedAt = 0
|
||||||
|
BakaShrot_MessageAttachmentSize = 0
|
||||||
|
BakaShrot_MessageAttachmentReady = #False
|
||||||
BakaShrot_MessageData = ""
|
BakaShrot_MessageData = ""
|
||||||
BakaShrot_MessageTopicId = -1
|
BakaShrot_MessageTopicId = -1
|
||||||
BakaShrot_MessageNodeId = -1
|
BakaShrot_MessageNodeId = -1
|
||||||
@@ -716,6 +737,8 @@ Procedure.l BakaShrot_GetMessagesString(Topic.s, Node.s, AfterMessageId.q, Limit
|
|||||||
If FirstElement(BakaShrot_Messages())
|
If FirstElement(BakaShrot_Messages())
|
||||||
BakaShrot_MessageId = BakaShrot_Messages()\MessageId
|
BakaShrot_MessageId = BakaShrot_Messages()\MessageId
|
||||||
BakaShrot_MessagePushedAt = BakaShrot_Messages()\PushedAt
|
BakaShrot_MessagePushedAt = BakaShrot_Messages()\PushedAt
|
||||||
|
BakaShrot_MessageAttachmentSize = BakaShrot_Messages()\AttachmentSize
|
||||||
|
BakaShrot_MessageAttachmentReady = BakaShrot_Messages()\AttachmentReady
|
||||||
BakaShrot_MessageData = BakaShrot_Messages()\JsonData
|
BakaShrot_MessageData = BakaShrot_Messages()\JsonData
|
||||||
EndIf
|
EndIf
|
||||||
ProcedureReturn Count
|
ProcedureReturn Count
|
||||||
@@ -751,6 +774,8 @@ ProcedureCDLL.i BakaShrot_SelectMessage(Index.l)
|
|||||||
SelectElement(BakaShrot_Messages(), Index)
|
SelectElement(BakaShrot_Messages(), Index)
|
||||||
BakaShrot_MessageId = BakaShrot_Messages()\MessageId
|
BakaShrot_MessageId = BakaShrot_Messages()\MessageId
|
||||||
BakaShrot_MessagePushedAt = BakaShrot_Messages()\PushedAt
|
BakaShrot_MessagePushedAt = BakaShrot_Messages()\PushedAt
|
||||||
|
BakaShrot_MessageAttachmentSize = BakaShrot_Messages()\AttachmentSize
|
||||||
|
BakaShrot_MessageAttachmentReady = BakaShrot_Messages()\AttachmentReady
|
||||||
BakaShrot_MessageData = BakaShrot_Messages()\JsonData
|
BakaShrot_MessageData = BakaShrot_Messages()\JsonData
|
||||||
ProcedureReturn #True
|
ProcedureReturn #True
|
||||||
EndProcedure
|
EndProcedure
|
||||||
@@ -1110,3 +1135,452 @@ EndProcedure
|
|||||||
ProcedureCDLL.i BakaShrot_GetQueryResultW(*Buffer, BufferSize.i)
|
ProcedureCDLL.i BakaShrot_GetQueryResultW(*Buffer, BufferSize.i)
|
||||||
ProcedureReturn BakaShrot_CopyString(BakaShrot_QueryResult, *Buffer, BufferSize, #PB_Unicode)
|
ProcedureReturn BakaShrot_CopyString(BakaShrot_QueryResult, *Buffer, BufferSize, #PB_Unicode)
|
||||||
EndProcedure
|
EndProcedure
|
||||||
|
|
||||||
|
|
||||||
|
; --- Attachments -----------------------------------------------------------------
|
||||||
|
; At most one per message, of any size the server takes (its
|
||||||
|
; MaxAttachmentSize), sent and read in parts of 1 MB, checked with their
|
||||||
|
; SHA-256 (Design/Attachments.md). The message is only stored once all of its
|
||||||
|
; attachment is: readers never see it without.
|
||||||
|
|
||||||
|
; What BakaShrot_LoadAttachment() read, for BakaShrot_GetAttachmentData().
|
||||||
|
Global *BakaShrot_AttachmentData = 0
|
||||||
|
Global BakaShrot_AttachmentDataSize.q = 0
|
||||||
|
|
||||||
|
|
||||||
|
; Sends *Request and returns the answer if it's a packet of AnswerType, its
|
||||||
|
; size in *AnswerSize\i. Returns 0 if the server refused it (the reason in
|
||||||
|
; BakaShrot_RefusalReason, still connected), or anything else went wrong
|
||||||
|
; (the connection is closed then).
|
||||||
|
Procedure.i BakaShrot_RequestExpecting(*Request, RequestSize.i, AnswerType.i, *AnswerSize.Integer)
|
||||||
|
Protected *Answer, Type.i, IsRefusal.i
|
||||||
|
|
||||||
|
*Answer = BakaShrot_SendRequest(*Request, RequestSize, *AnswerSize)
|
||||||
|
If Not *Answer
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
Type = BakaShrot_GetPacketType(*Answer, *AnswerSize\i)
|
||||||
|
If Type = #BakaShrot_PacketType_RequestRefused
|
||||||
|
IsRefusal = BakaShrot_ReadRefusal(*Answer, *AnswerSize\i)
|
||||||
|
FreeMemory(*Answer)
|
||||||
|
If Not IsRefusal
|
||||||
|
BakaShrot_AbortConnection()
|
||||||
|
EndIf
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
If Type <> AnswerType
|
||||||
|
FreeMemory(*Answer)
|
||||||
|
BakaShrot_AbortConnection()
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
ProcedureReturn *Answer
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
|
||||||
|
; Uploads Size bytes, read from FileId (from its start) or else from *Memory,
|
||||||
|
; as the attachment of a message about to be pushed to Topic ("" for the
|
||||||
|
; client's own). Its SHA-256 is computed first, so the file is read twice.
|
||||||
|
; Returns the upload id for BakaShrot_PushMessageToString(), 0 on failure.
|
||||||
|
Procedure.q BakaShrot_Upload(Topic.s, FileId.i, *Memory, Size.q)
|
||||||
|
Protected Start.BakaShrot_UploadStart, *Started.BakaShrot_UploadStarted
|
||||||
|
Protected Chunk.BakaShrot_UploadChunk, *Stored.BakaShrot_ChunkStored
|
||||||
|
Protected Hash.BakaShrot_Sha256, *Buffer, Index.q, Count.q, Bytes.i, UploadId.q, Received.q, Complete.i
|
||||||
|
Protected *Request, RequestSize.Integer, *Answer, AnswerSize.Integer, *View.MsgPackData
|
||||||
|
|
||||||
|
BakaShrot_RefusalReason = ""
|
||||||
|
If Not BakaShrot_Outbound\ConnectionId Or BakaShrot_Outbound\Metadata\Status <> #BakaShrot_ConnectionStatus_Authenticated
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
If Topic <> "" And Not BakaShrot_IsValidRef(Topic)
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
If Size < 1
|
||||||
|
BakaShrot_RefusalReason = "The attachment is empty"
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
If Size > #BakaShrot_MaxAttachmentSize
|
||||||
|
BakaShrot_RefusalReason = "The attachment is too big: " + Str(Size) + " bytes, at most " + Str(#BakaShrot_MaxAttachmentSize)
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
*Buffer = AllocateMemory(#BakaShrot_AttachmentChunkSize, #PB_Memory_NoClear)
|
||||||
|
If Not *Buffer Or Not BakaShrot_Sha256_Start(@Hash)
|
||||||
|
If *Buffer : FreeMemory(*Buffer) : EndIf
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
Count = BakaShrot_AttachmentChunkCount(Size)
|
||||||
|
|
||||||
|
; 1. Its SHA-256.
|
||||||
|
If FileId
|
||||||
|
FileSeek(FileId, 0)
|
||||||
|
For Index = 0 To Count - 1
|
||||||
|
Bytes = BakaShrot_AttachmentChunkBytes(Size, Index)
|
||||||
|
If ReadData(FileId, *Buffer, Bytes) <> Bytes
|
||||||
|
BakaShrot_RefusalReason = "The file couldn't be read"
|
||||||
|
FreeMemory(*Buffer)
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
BakaShrot_Sha256_Add(@Hash, *Buffer, Bytes)
|
||||||
|
Next
|
||||||
|
FileSeek(FileId, 0)
|
||||||
|
Else
|
||||||
|
BakaShrot_Sha256_Add(@Hash, *Memory, Size)
|
||||||
|
EndIf
|
||||||
|
BakaShrot_Sha256_Finish(@Hash, @Start\Sha256[0])
|
||||||
|
|
||||||
|
; 2. The server makes room for it.
|
||||||
|
Start\Topic = Topic
|
||||||
|
Start\Size = Size
|
||||||
|
*Request = BakaShrot_UploadStartPacket_Encode(@Start, @RequestSize)
|
||||||
|
If Not *Request
|
||||||
|
FreeMemory(*Buffer)
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
*Answer = BakaShrot_RequestExpecting(*Request, RequestSize\i, #BakaShrot_PacketType_UploadStarted, @AnswerSize)
|
||||||
|
FreeMemory(*Request)
|
||||||
|
If Not *Answer
|
||||||
|
FreeMemory(*Buffer)
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
*Started = 0
|
||||||
|
*View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i)
|
||||||
|
If *View
|
||||||
|
*Started = BakaShrot_UploadStartedPacket_Decode(*View)
|
||||||
|
MsgPackFree(*View, #False)
|
||||||
|
EndIf
|
||||||
|
FreeMemory(*Answer)
|
||||||
|
If Not *Started Or *Started\ChunkSize <> #BakaShrot_AttachmentChunkSize
|
||||||
|
If *Started : FreeStructure(*Started) : EndIf
|
||||||
|
FreeMemory(*Buffer)
|
||||||
|
BakaShrot_AbortConnection()
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
UploadId = *Started\UploadId
|
||||||
|
FreeStructure(*Started)
|
||||||
|
|
||||||
|
; 3. Its parts, in order.
|
||||||
|
Chunk\UploadId = UploadId
|
||||||
|
For Index = 0 To Count - 1
|
||||||
|
Bytes = BakaShrot_AttachmentChunkBytes(Size, Index)
|
||||||
|
If FileId
|
||||||
|
If ReadData(FileId, *Buffer, Bytes) <> Bytes
|
||||||
|
BakaShrot_RefusalReason = "The file couldn't be read"
|
||||||
|
FreeMemory(*Buffer)
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
Chunk\Data = *Buffer
|
||||||
|
Else
|
||||||
|
Chunk\Data = *Memory + Index * #BakaShrot_AttachmentChunkSize
|
||||||
|
EndIf
|
||||||
|
Chunk\ChunkIndex = Index
|
||||||
|
Chunk\DataSize = Bytes
|
||||||
|
*Request = BakaShrot_UploadChunkPacket_Encode(@Chunk, @RequestSize)
|
||||||
|
If Not *Request
|
||||||
|
FreeMemory(*Buffer)
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
*Answer = BakaShrot_RequestExpecting(*Request, RequestSize\i, #BakaShrot_PacketType_ChunkStored, @AnswerSize)
|
||||||
|
FreeMemory(*Request)
|
||||||
|
If Not *Answer
|
||||||
|
FreeMemory(*Buffer)
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
*Stored = 0
|
||||||
|
*View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i)
|
||||||
|
If *View
|
||||||
|
*Stored = BakaShrot_ChunkStoredPacket_Decode(*View)
|
||||||
|
MsgPackFree(*View, #False)
|
||||||
|
EndIf
|
||||||
|
FreeMemory(*Answer)
|
||||||
|
If Not *Stored
|
||||||
|
FreeMemory(*Buffer)
|
||||||
|
BakaShrot_AbortConnection()
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
Received = *Stored\Received
|
||||||
|
Complete = *Stored\Complete
|
||||||
|
FreeStructure(*Stored)
|
||||||
|
; Complete exactly with the last part.
|
||||||
|
If Received <> Index * #BakaShrot_AttachmentChunkSize + Bytes Or Bool(Complete) <> Bool(Index = Count - 1)
|
||||||
|
FreeMemory(*Buffer)
|
||||||
|
BakaShrot_AbortConnection()
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
Next
|
||||||
|
|
||||||
|
FreeMemory(*Buffer)
|
||||||
|
ProcedureReturn UploadId
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
|
||||||
|
; Pushes a message with the file at FilePath as its attachment, see
|
||||||
|
; BakaShrot_PushMessageToString(): the file is uploaded first, the message
|
||||||
|
; only stored once all of it is on the server.
|
||||||
|
; Returns the new message's id, or -1 on failure (refused, see
|
||||||
|
; BakaShrot_GetRefusalReason(), or the connection failed).
|
||||||
|
Procedure.q BakaShrot_PushMessageWithFileString(Topic.s, JsonData.s, FilePath.s)
|
||||||
|
Protected FileId.i, UploadId.q
|
||||||
|
|
||||||
|
BakaShrot_RefusalReason = ""
|
||||||
|
If StringByteLength(JsonData, #PB_UTF8) > #BakaShrot_MaxMessageSize
|
||||||
|
BakaShrot_RefusalReason = "The message is too big: " + Str(StringByteLength(JsonData, #PB_UTF8)) + " bytes, at most " + Str(#BakaShrot_MaxMessageSize)
|
||||||
|
ProcedureReturn -1
|
||||||
|
EndIf
|
||||||
|
FileId = ReadFile(#PB_Any, FilePath, #PB_File_SharedRead)
|
||||||
|
If Not FileId
|
||||||
|
BakaShrot_RefusalReason = "Can't open '" + FilePath + "'"
|
||||||
|
ProcedureReturn -1
|
||||||
|
EndIf
|
||||||
|
UploadId = BakaShrot_Upload(Topic, FileId, 0, Lof(FileId))
|
||||||
|
CloseFile(FileId)
|
||||||
|
If Not UploadId
|
||||||
|
ProcedureReturn -1
|
||||||
|
EndIf
|
||||||
|
ProcedureReturn BakaShrot_PushMessageToString(Topic, JsonData, UploadId)
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
; A null *Topic is the client's own topic, a null *JsonData an empty message.
|
||||||
|
ProcedureCDLL.q BakaShrot_PushMessageWithFileA(*Topic, *JsonData, *FilePath)
|
||||||
|
Protected Topic.s, JsonData.s
|
||||||
|
If Not *FilePath
|
||||||
|
ProcedureReturn -1
|
||||||
|
EndIf
|
||||||
|
If *Topic : Topic = PeekS(*Topic, -1, #PB_UTF8) : EndIf
|
||||||
|
If *JsonData : JsonData = PeekS(*JsonData, -1, #PB_UTF8) : EndIf
|
||||||
|
ProcedureReturn BakaShrot_PushMessageWithFileString(Topic, JsonData, PeekS(*FilePath, -1, #PB_UTF8))
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
ProcedureCDLL.q BakaShrot_PushMessageWithFileW(*Topic, *JsonData, *FilePath)
|
||||||
|
Protected Topic.s, JsonData.s
|
||||||
|
If Not *FilePath
|
||||||
|
ProcedureReturn -1
|
||||||
|
EndIf
|
||||||
|
If *Topic : Topic = PeekS(*Topic, -1, #PB_Unicode) : EndIf
|
||||||
|
If *JsonData : JsonData = PeekS(*JsonData, -1, #PB_Unicode) : EndIf
|
||||||
|
ProcedureReturn BakaShrot_PushMessageWithFileString(Topic, JsonData, PeekS(*FilePath, -1, #PB_Unicode))
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
|
||||||
|
; Same, the attachment being Size bytes at *Data.
|
||||||
|
Procedure.q BakaShrot_PushMessageWithDataString(Topic.s, JsonData.s, *Data, Size.q)
|
||||||
|
Protected UploadId.q
|
||||||
|
|
||||||
|
BakaShrot_RefusalReason = ""
|
||||||
|
If StringByteLength(JsonData, #PB_UTF8) > #BakaShrot_MaxMessageSize
|
||||||
|
BakaShrot_RefusalReason = "The message is too big: " + Str(StringByteLength(JsonData, #PB_UTF8)) + " bytes, at most " + Str(#BakaShrot_MaxMessageSize)
|
||||||
|
ProcedureReturn -1
|
||||||
|
EndIf
|
||||||
|
If Not *Data
|
||||||
|
BakaShrot_RefusalReason = "The attachment is empty"
|
||||||
|
ProcedureReturn -1
|
||||||
|
EndIf
|
||||||
|
UploadId = BakaShrot_Upload(Topic, 0, *Data, Size)
|
||||||
|
If Not UploadId
|
||||||
|
ProcedureReturn -1
|
||||||
|
EndIf
|
||||||
|
ProcedureReturn BakaShrot_PushMessageToString(Topic, JsonData, UploadId)
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
ProcedureCDLL.q BakaShrot_PushMessageWithDataA(*Topic, *JsonData, *Data, Size.q)
|
||||||
|
Protected Topic.s, JsonData.s
|
||||||
|
If *Topic : Topic = PeekS(*Topic, -1, #PB_UTF8) : EndIf
|
||||||
|
If *JsonData : JsonData = PeekS(*JsonData, -1, #PB_UTF8) : EndIf
|
||||||
|
ProcedureReturn BakaShrot_PushMessageWithDataString(Topic, JsonData, *Data, Size)
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
ProcedureCDLL.q BakaShrot_PushMessageWithDataW(*Topic, *JsonData, *Data, Size.q)
|
||||||
|
Protected Topic.s, JsonData.s
|
||||||
|
If *Topic : Topic = PeekS(*Topic, -1, #PB_Unicode) : EndIf
|
||||||
|
If *JsonData : JsonData = PeekS(*JsonData, -1, #PB_Unicode) : EndIf
|
||||||
|
ProcedureReturn BakaShrot_PushMessageWithDataString(Topic, JsonData, *Data, Size)
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
|
||||||
|
; Reads the attachment of Topic:Node#MessageId, a part at a time, into FileId
|
||||||
|
; (from its start) or else into memory (*BakaShrot_AttachmentData), and
|
||||||
|
; checks its SHA-256.
|
||||||
|
; Returns its size, -1 on failure: refused (no attachment, not on this server
|
||||||
|
; yet...), a SHA-256 mismatch (refusal reason set), or the connection failed.
|
||||||
|
Procedure.q BakaShrot_Download(Topic.s, Node.s, MessageId.q, FileId.i)
|
||||||
|
Protected Request.BakaShrot_GetAttachment, *Chunk.BakaShrot_AttachmentChunk
|
||||||
|
Protected Hash.BakaShrot_Sha256, Index.q, Count.q, Size.q, *Memory, IsValid.i
|
||||||
|
Protected Dim Expected.a(#BakaShrot_Sha256Size - 1), Dim Result.a(#BakaShrot_Sha256Size - 1)
|
||||||
|
Protected *Request, RequestSize.Integer, *Answer, AnswerSize.Integer, *View.MsgPackData
|
||||||
|
|
||||||
|
BakaShrot_RefusalReason = ""
|
||||||
|
If Not BakaShrot_Outbound\ConnectionId Or BakaShrot_Outbound\Metadata\Status <> #BakaShrot_ConnectionStatus_Authenticated
|
||||||
|
ProcedureReturn -1
|
||||||
|
EndIf
|
||||||
|
If Not BakaShrot_IsValidRef(Topic) Or Not BakaShrot_IsValidRef(Node) Or MessageId < 1 Or Not BakaShrot_Sha256_Start(@Hash)
|
||||||
|
ProcedureReturn -1
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
Request\Topic = Topic
|
||||||
|
Request\Node = Node
|
||||||
|
Request\MessageId = MessageId
|
||||||
|
Index = 0
|
||||||
|
Count = 1
|
||||||
|
While Index < Count
|
||||||
|
Request\ChunkIndex = Index
|
||||||
|
*Request = BakaShrot_GetAttachmentPacket_Encode(@Request, @RequestSize)
|
||||||
|
If Not *Request
|
||||||
|
Goto DownloadFailed
|
||||||
|
EndIf
|
||||||
|
*Answer = BakaShrot_RequestExpecting(*Request, RequestSize\i, #BakaShrot_PacketType_AttachmentChunk, @AnswerSize)
|
||||||
|
FreeMemory(*Request)
|
||||||
|
If Not *Answer
|
||||||
|
Goto DownloadFailed
|
||||||
|
EndIf
|
||||||
|
*Chunk = 0
|
||||||
|
*View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i)
|
||||||
|
If *View
|
||||||
|
*Chunk = BakaShrot_AttachmentChunkPacket_Decode(*View)
|
||||||
|
MsgPackFree(*View, #False)
|
||||||
|
EndIf
|
||||||
|
FreeMemory(*Answer)
|
||||||
|
If Not *Chunk
|
||||||
|
BakaShrot_AbortConnection()
|
||||||
|
Goto DownloadFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; The first part tells the size and SHA-256, every other must agree.
|
||||||
|
If Index = 0
|
||||||
|
Size = *Chunk\Size
|
||||||
|
Count = BakaShrot_AttachmentChunkCount(Size)
|
||||||
|
CopyMemory(@*Chunk\Sha256[0], @Expected(0), #BakaShrot_Sha256Size)
|
||||||
|
If Not FileId
|
||||||
|
*Memory = AllocateMemory(Size, #PB_Memory_NoClear)
|
||||||
|
If Not *Memory
|
||||||
|
BakaShrot_AttachmentChunkPacket_Free(*Chunk)
|
||||||
|
BakaShrot_RefusalReason = "Out of memory for " + Str(Size) + " bytes"
|
||||||
|
Goto DownloadFailed
|
||||||
|
EndIf
|
||||||
|
EndIf
|
||||||
|
EndIf
|
||||||
|
If *Chunk\MessageId <> MessageId Or *Chunk\ChunkIndex <> Index Or *Chunk\Size <> Size Or Not CompareMemory(@*Chunk\Sha256[0], @Expected(0), #BakaShrot_Sha256Size) Or *Chunk\DataSize <> BakaShrot_AttachmentChunkBytes(Size, Index)
|
||||||
|
BakaShrot_AttachmentChunkPacket_Free(*Chunk)
|
||||||
|
BakaShrot_AbortConnection()
|
||||||
|
Goto DownloadFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
BakaShrot_Sha256_Add(@Hash, *Chunk\Data, *Chunk\DataSize)
|
||||||
|
If FileId
|
||||||
|
If WriteData(FileId, *Chunk\Data, *Chunk\DataSize) <> *Chunk\DataSize
|
||||||
|
BakaShrot_AttachmentChunkPacket_Free(*Chunk)
|
||||||
|
BakaShrot_RefusalReason = "The file couldn't be written"
|
||||||
|
Goto DownloadFailed
|
||||||
|
EndIf
|
||||||
|
Else
|
||||||
|
CopyMemory(*Chunk\Data, *Memory + Index * #BakaShrot_AttachmentChunkSize, *Chunk\DataSize)
|
||||||
|
EndIf
|
||||||
|
BakaShrot_AttachmentChunkPacket_Free(*Chunk)
|
||||||
|
Index + 1
|
||||||
|
Wend
|
||||||
|
|
||||||
|
BakaShrot_Sha256_Finish(@Hash, @Result(0))
|
||||||
|
If Not CompareMemory(@Result(0), @Expected(0), #BakaShrot_Sha256Size)
|
||||||
|
BakaShrot_RefusalReason = "The attachment doesn't match its SHA-256"
|
||||||
|
Goto DownloadFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If Not FileId
|
||||||
|
If *BakaShrot_AttachmentData
|
||||||
|
FreeMemory(*BakaShrot_AttachmentData)
|
||||||
|
EndIf
|
||||||
|
*BakaShrot_AttachmentData = *Memory
|
||||||
|
BakaShrot_AttachmentDataSize = Size
|
||||||
|
EndIf
|
||||||
|
ProcedureReturn Size
|
||||||
|
|
||||||
|
DownloadFailed:
|
||||||
|
If *Memory
|
||||||
|
FreeMemory(*Memory)
|
||||||
|
EndIf
|
||||||
|
ProcedureReturn -1
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
|
||||||
|
; Saves the attachment of Topic:Node#MessageId to FilePath (replaced),
|
||||||
|
; checked with its SHA-256. A failed one leaves no file.
|
||||||
|
; Returns its size, -1 on failure, see BakaShrot_Download().
|
||||||
|
Procedure.q BakaShrot_SaveAttachmentString(Topic.s, Node.s, MessageId.q, FilePath.s)
|
||||||
|
Protected FileId.i, Size.q
|
||||||
|
|
||||||
|
FileId = CreateFile(#PB_Any, FilePath)
|
||||||
|
If Not FileId
|
||||||
|
BakaShrot_RefusalReason = "Can't create '" + FilePath + "'"
|
||||||
|
ProcedureReturn -1
|
||||||
|
EndIf
|
||||||
|
Size = BakaShrot_Download(Topic, Node, MessageId, FileId)
|
||||||
|
CloseFile(FileId)
|
||||||
|
If Size < 0
|
||||||
|
DeleteFile(FilePath)
|
||||||
|
EndIf
|
||||||
|
ProcedureReturn Size
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
ProcedureCDLL.q BakaShrot_SaveAttachmentA(*Topic, *Node, MessageId.q, *FilePath)
|
||||||
|
If Not *Topic Or Not *Node Or Not *FilePath
|
||||||
|
ProcedureReturn -1
|
||||||
|
EndIf
|
||||||
|
ProcedureReturn BakaShrot_SaveAttachmentString(PeekS(*Topic, -1, #PB_UTF8), PeekS(*Node, -1, #PB_UTF8), MessageId, PeekS(*FilePath, -1, #PB_UTF8))
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
ProcedureCDLL.q BakaShrot_SaveAttachmentW(*Topic, *Node, MessageId.q, *FilePath)
|
||||||
|
If Not *Topic Or Not *Node Or Not *FilePath
|
||||||
|
ProcedureReturn -1
|
||||||
|
EndIf
|
||||||
|
ProcedureReturn BakaShrot_SaveAttachmentString(PeekS(*Topic, -1, #PB_Unicode), PeekS(*Node, -1, #PB_Unicode), MessageId, PeekS(*FilePath, -1, #PB_Unicode))
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
|
||||||
|
; Reads the attachment of Topic:Node#MessageId into memory, checked with its
|
||||||
|
; SHA-256, for BakaShrot_GetAttachmentData(). All of it is held at once:
|
||||||
|
; BakaShrot_SaveAttachment() for big ones.
|
||||||
|
; Returns its size, -1 on failure, see BakaShrot_Download().
|
||||||
|
ProcedureCDLL.q BakaShrot_LoadAttachmentA(*Topic, *Node, MessageId.q)
|
||||||
|
If Not *Topic Or Not *Node
|
||||||
|
ProcedureReturn -1
|
||||||
|
EndIf
|
||||||
|
ProcedureReturn BakaShrot_Download(PeekS(*Topic, -1, #PB_UTF8), PeekS(*Node, -1, #PB_UTF8), MessageId, 0)
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
ProcedureCDLL.q BakaShrot_LoadAttachmentW(*Topic, *Node, MessageId.q)
|
||||||
|
If Not *Topic Or Not *Node
|
||||||
|
ProcedureReturn -1
|
||||||
|
EndIf
|
||||||
|
ProcedureReturn BakaShrot_Download(PeekS(*Topic, -1, #PB_Unicode), PeekS(*Node, -1, #PB_Unicode), MessageId, 0)
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
; Copies what the last successful BakaShrot_LoadAttachment() read into
|
||||||
|
; *Buffer, if BufferSize is enough. Returns its size (0 if none): call it
|
||||||
|
; with a null *Buffer first.
|
||||||
|
ProcedureCDLL.q BakaShrot_GetAttachmentData(*Buffer, BufferSize.q)
|
||||||
|
If *Buffer And *BakaShrot_AttachmentData And BufferSize >= BakaShrot_AttachmentDataSize
|
||||||
|
CopyMemory(*BakaShrot_AttachmentData, *Buffer, BakaShrot_AttachmentDataSize)
|
||||||
|
EndIf
|
||||||
|
ProcedureReturn BakaShrot_AttachmentDataSize
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
; Frees what BakaShrot_LoadAttachment() read.
|
||||||
|
ProcedureCDLL.i BakaShrot_FreeAttachmentData()
|
||||||
|
If *BakaShrot_AttachmentData
|
||||||
|
FreeMemory(*BakaShrot_AttachmentData)
|
||||||
|
EndIf
|
||||||
|
*BakaShrot_AttachmentData = 0
|
||||||
|
BakaShrot_AttachmentDataSize = 0
|
||||||
|
ProcedureReturn #True
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
|
||||||
|
; Size in bytes of the selected message's attachment, 0 if it has none.
|
||||||
|
ProcedureCDLL.q BakaShrot_GetMessageAttachmentSize()
|
||||||
|
ProcedureReturn BakaShrot_MessageAttachmentSize
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
; #True if all of the selected message's attachment is on this server: a
|
||||||
|
; replicated one comes after its message.
|
||||||
|
ProcedureCDLL.i BakaShrot_IsMessageAttachmentReady()
|
||||||
|
ProcedureReturn BakaShrot_MessageAttachmentReady
|
||||||
|
EndProcedure
|
||||||
|
|||||||
@@ -50,6 +50,14 @@ PrototypeC.l BakaShrot_GetMessages_Prototype(Topic.p-unicode, Node.p-unicode, Af
|
|||||||
PrototypeC.l BakaShrot_GetMessageCount_Prototype()
|
PrototypeC.l BakaShrot_GetMessageCount_Prototype()
|
||||||
PrototypeC.i BakaShrot_SelectMessage_Prototype(Index.l)
|
PrototypeC.i BakaShrot_SelectMessage_Prototype(Index.l)
|
||||||
PrototypeC.i BakaShrot_HasMoreMessages_Prototype()
|
PrototypeC.i BakaShrot_HasMoreMessages_Prototype()
|
||||||
|
PrototypeC.q BakaShrot_PushMessageWithFile_Prototype(Topic.p-unicode, JsonData.p-unicode, FilePath.p-unicode)
|
||||||
|
PrototypeC.q BakaShrot_PushMessageWithData_Prototype(Topic.p-unicode, JsonData.p-unicode, *Data, Size.q)
|
||||||
|
PrototypeC.q BakaShrot_SaveAttachment_Prototype(Topic.p-unicode, Node.p-unicode, MessageId.q, FilePath.p-unicode)
|
||||||
|
PrototypeC.q BakaShrot_LoadAttachment_Prototype(Topic.p-unicode, Node.p-unicode, MessageId.q)
|
||||||
|
PrototypeC.q BakaShrot_GetAttachmentData_Prototype(*Buffer, BufferSize.q)
|
||||||
|
PrototypeC.i BakaShrot_FreeAttachmentData_Prototype()
|
||||||
|
PrototypeC.q BakaShrot_GetMessageAttachmentSize_Prototype()
|
||||||
|
PrototypeC.i BakaShrot_IsMessageAttachmentReady_Prototype()
|
||||||
|
|
||||||
|
|
||||||
Global BakaShrot_SetPrivateKey.BakaShrot_SetPrivateKey_Prototype
|
Global BakaShrot_SetPrivateKey.BakaShrot_SetPrivateKey_Prototype
|
||||||
@@ -86,6 +94,14 @@ Global BakaShrot_GetMessages.BakaShrot_GetMessages_Prototype
|
|||||||
Global BakaShrot_GetMessageCount.BakaShrot_GetMessageCount_Prototype
|
Global BakaShrot_GetMessageCount.BakaShrot_GetMessageCount_Prototype
|
||||||
Global BakaShrot_SelectMessage.BakaShrot_SelectMessage_Prototype
|
Global BakaShrot_SelectMessage.BakaShrot_SelectMessage_Prototype
|
||||||
Global BakaShrot_HasMoreMessages.BakaShrot_HasMoreMessages_Prototype
|
Global BakaShrot_HasMoreMessages.BakaShrot_HasMoreMessages_Prototype
|
||||||
|
Global BakaShrot_PushMessageWithFile.BakaShrot_PushMessageWithFile_Prototype
|
||||||
|
Global BakaShrot_PushMessageWithData.BakaShrot_PushMessageWithData_Prototype
|
||||||
|
Global BakaShrot_SaveAttachment.BakaShrot_SaveAttachment_Prototype
|
||||||
|
Global BakaShrot_LoadAttachment.BakaShrot_LoadAttachment_Prototype
|
||||||
|
Global BakaShrot_GetAttachmentData.BakaShrot_GetAttachmentData_Prototype
|
||||||
|
Global BakaShrot_FreeAttachmentData.BakaShrot_FreeAttachmentData_Prototype
|
||||||
|
Global BakaShrot_GetMessageAttachmentSize.BakaShrot_GetMessageAttachmentSize_Prototype
|
||||||
|
Global BakaShrot_IsMessageAttachmentReady.BakaShrot_IsMessageAttachmentReady_Prototype
|
||||||
|
|
||||||
Global BakaShrot_ClientLibrary.i = 0
|
Global BakaShrot_ClientLibrary.i = 0
|
||||||
|
|
||||||
@@ -146,6 +162,14 @@ Procedure.i BakaShrot_LoadClient(DllPath.s)
|
|||||||
BakaShrot_GetMessageCount = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetMessageCount")
|
BakaShrot_GetMessageCount = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetMessageCount")
|
||||||
BakaShrot_SelectMessage = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_SelectMessage")
|
BakaShrot_SelectMessage = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_SelectMessage")
|
||||||
BakaShrot_HasMoreMessages = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_HasMoreMessages")
|
BakaShrot_HasMoreMessages = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_HasMoreMessages")
|
||||||
|
BakaShrot_PushMessageWithFile = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_PushMessageWithFileW")
|
||||||
|
BakaShrot_PushMessageWithData = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_PushMessageWithDataW")
|
||||||
|
BakaShrot_SaveAttachment = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_SaveAttachmentW")
|
||||||
|
BakaShrot_LoadAttachment = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_LoadAttachmentW")
|
||||||
|
BakaShrot_GetAttachmentData = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetAttachmentData")
|
||||||
|
BakaShrot_FreeAttachmentData = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_FreeAttachmentData")
|
||||||
|
BakaShrot_GetMessageAttachmentSize = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetMessageAttachmentSize")
|
||||||
|
BakaShrot_IsMessageAttachmentReady = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_IsMessageAttachmentReady")
|
||||||
|
|
||||||
If Not BakaShrot_SetPrivateKey Or Not BakaShrot_SetPublicKey Or Not BakaShrot_SetServerPublicKey Or Not BakaShrot_SetTopicId Or Not BakaShrot_SetNodeId Or Not BakaShrot_Connect Or Not BakaShrot_IsConnected Or Not BakaShrot_Disconnect
|
If Not BakaShrot_SetPrivateKey Or Not BakaShrot_SetPublicKey Or Not BakaShrot_SetServerPublicKey Or Not BakaShrot_SetTopicId Or Not BakaShrot_SetNodeId Or Not BakaShrot_Connect Or Not BakaShrot_IsConnected Or Not BakaShrot_Disconnect
|
||||||
BakaShrot_UnloadClient()
|
BakaShrot_UnloadClient()
|
||||||
@@ -175,6 +199,11 @@ Procedure.i BakaShrot_LoadClient(DllPath.s)
|
|||||||
ProcedureReturn #False
|
ProcedureReturn #False
|
||||||
EndIf
|
EndIf
|
||||||
|
|
||||||
|
If Not BakaShrot_PushMessageWithFile Or Not BakaShrot_PushMessageWithData Or Not BakaShrot_SaveAttachment Or Not BakaShrot_LoadAttachment Or Not BakaShrot_GetAttachmentData Or Not BakaShrot_FreeAttachmentData Or Not BakaShrot_GetMessageAttachmentSize Or Not BakaShrot_IsMessageAttachmentReady
|
||||||
|
BakaShrot_UnloadClient()
|
||||||
|
ProcedureReturn #False
|
||||||
|
EndIf
|
||||||
|
|
||||||
ProcedureReturn #True
|
ProcedureReturn #True
|
||||||
EndProcedure
|
EndProcedure
|
||||||
|
|
||||||
|
|||||||
@@ -135,6 +135,14 @@ CompilerEndIf
|
|||||||
crypto_kx_client_session_keys.l(*Rx, *Tx, *ClientPublicKey, *ClientSecretKey, *ServerPublicKey)
|
crypto_kx_client_session_keys.l(*Rx, *Tx, *ClientPublicKey, *ClientSecretKey, *ServerPublicKey)
|
||||||
crypto_kx_server_session_keys.l(*Rx, *Tx, *ServerPublicKey, *ServerSecretKey, *ClientPublicKey)
|
crypto_kx_server_session_keys.l(*Rx, *Tx, *ServerPublicKey, *ServerSecretKey, *ClientPublicKey)
|
||||||
|
|
||||||
|
; SHA-256, a piece at a time: _init() a state (crypto_hash_sha256_statebytes()
|
||||||
|
; bytes), _update() it with each piece, _final() writes the 32-byte hash.
|
||||||
|
; For the attachments' checksums, see BakaShrot_Sha256_* below.
|
||||||
|
crypto_hash_sha256_statebytes.i()
|
||||||
|
crypto_hash_sha256_init.l(*State)
|
||||||
|
crypto_hash_sha256_update.l(*State, *Data, DataLength.q)
|
||||||
|
crypto_hash_sha256_final.l(*State, *Hash)
|
||||||
|
|
||||||
EndImport
|
EndImport
|
||||||
|
|
||||||
|
|
||||||
@@ -183,6 +191,34 @@ Procedure.i DecodeData(*Data, DataLength.i, *PublicKey, *Signature)
|
|||||||
EndProcedure
|
EndProcedure
|
||||||
|
|
||||||
|
|
||||||
|
; SHA-256 of data given a piece at a time (an attachment's parts): Start, Add
|
||||||
|
; each piece, then Finish writes the 32-byte hash.
|
||||||
|
#BakaShrot_Sha256_HashSize = 32
|
||||||
|
|
||||||
|
Structure BakaShrot_Sha256
|
||||||
|
; crypto_hash_sha256_state is 104 bytes, checked by Start.
|
||||||
|
State.a[128]
|
||||||
|
EndStructure
|
||||||
|
|
||||||
|
; Returns #False if libsodium's state doesn't fit (a libsodium change).
|
||||||
|
Procedure.i BakaShrot_Sha256_Start(*Hash.BakaShrot_Sha256)
|
||||||
|
If crypto_hash_sha256_statebytes() > SizeOf(BakaShrot_Sha256)
|
||||||
|
ProcedureReturn #False
|
||||||
|
EndIf
|
||||||
|
ProcedureReturn Bool(crypto_hash_sha256_init(*Hash) = 0)
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
Procedure BakaShrot_Sha256_Add(*Hash.BakaShrot_Sha256, *Data, Size.i)
|
||||||
|
If Size > 0
|
||||||
|
crypto_hash_sha256_update(*Hash, *Data, Size)
|
||||||
|
EndIf
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
Procedure BakaShrot_Sha256_Finish(*Hash.BakaShrot_Sha256, *Out)
|
||||||
|
crypto_hash_sha256_final(*Hash, *Out)
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
|
||||||
; Encodes KeySize raw bytes at *Key as a Base64 string, for storing a key in
|
; Encodes KeySize raw bytes at *Key as a Base64 string, for storing a key in
|
||||||
; the ini file (PrivateKey / PublicKey fields in Config.pbi).
|
; the ini file (PrivateKey / PublicKey fields in Config.pbi).
|
||||||
Procedure.s EncodeKeyToString(*Key, KeySize.i)
|
Procedure.s EncodeKeyToString(*Key, KeySize.i)
|
||||||
|
|||||||
@@ -31,6 +31,10 @@
|
|||||||
; C->S QueryRequest -> S->C QueryResult or RequestRefused
|
; C->S QueryRequest -> S->C QueryResult or RequestRefused
|
||||||
; C->S ResolveName -> S->C NameResolved or RequestRefused
|
; C->S ResolveName -> S->C NameResolved or RequestRefused
|
||||||
; C->S ListNames -> S->C NamesList
|
; C->S ListNames -> S->C NamesList
|
||||||
|
; C->S UploadStart -> S->C UploadStarted or RequestRefused
|
||||||
|
; C->S UploadChunk -> S->C ChunkStored or RequestRefused
|
||||||
|
; then a PushMessage with the UploadId attaches it to the message
|
||||||
|
; C->S GetAttachment -> S->C AttachmentChunk or RequestRefused
|
||||||
; Topics and nodes are given by name or id, see Names.pbi.
|
; Topics and nodes are given by name or id, see Names.pbi.
|
||||||
; A refusal keeps the connection open, a malformed or unexpected packet
|
; A refusal keeps the connection open, a malformed or unexpected packet
|
||||||
; still aborts it.
|
; still aborts it.
|
||||||
@@ -39,6 +43,9 @@
|
|||||||
; link it opened to the server:
|
; link it opened to the server:
|
||||||
; P->S SyncStateRequest -> S->P SyncState or RequestRefused
|
; P->S SyncStateRequest -> S->P SyncState or RequestRefused
|
||||||
; P->S ReplicateMessages -> S->P MessagePushed (last id) or RequestRefused
|
; P->S ReplicateMessages -> S->P MessagePushed (last id) or RequestRefused
|
||||||
|
; once the messages are caught up:
|
||||||
|
; P->S MissingAttachmentsRequest -> S->P MissingAttachments or RequestRefused
|
||||||
|
; P->S ReplicateAttachmentChunk -> S->P ChunkStored or RequestRefused
|
||||||
;
|
;
|
||||||
;
|
;
|
||||||
; Framing: every packet is sent as its size (4 bytes, little-endian),
|
; Framing: every packet is sent as its size (4 bytes, little-endian),
|
||||||
@@ -73,6 +80,15 @@ XIncludeFile "Packets/ListNamesPacket.pbi"
|
|||||||
XIncludeFile "Packets/NamesListPacket.pbi"
|
XIncludeFile "Packets/NamesListPacket.pbi"
|
||||||
XIncludeFile "Packets/GetMessagesPacket.pbi"
|
XIncludeFile "Packets/GetMessagesPacket.pbi"
|
||||||
XIncludeFile "Packets/MessagesPacket.pbi"
|
XIncludeFile "Packets/MessagesPacket.pbi"
|
||||||
|
XIncludeFile "Packets/UploadStartPacket.pbi"
|
||||||
|
XIncludeFile "Packets/UploadStartedPacket.pbi"
|
||||||
|
XIncludeFile "Packets/UploadChunkPacket.pbi"
|
||||||
|
XIncludeFile "Packets/ChunkStoredPacket.pbi"
|
||||||
|
XIncludeFile "Packets/GetAttachmentPacket.pbi"
|
||||||
|
XIncludeFile "Packets/AttachmentChunkPacket.pbi"
|
||||||
|
XIncludeFile "Packets/MissingAttachmentsRequestPacket.pbi"
|
||||||
|
XIncludeFile "Packets/MissingAttachmentsPacket.pbi"
|
||||||
|
XIncludeFile "Packets/ReplicateAttachmentChunkPacket.pbi"
|
||||||
|
|
||||||
|
|
||||||
; Reads the type of a received packet, to know which decoder to use.
|
; Reads the type of a received packet, to know which decoder to use.
|
||||||
|
|||||||
@@ -20,7 +20,8 @@ EndStructure
|
|||||||
; 3: the Hello sealed for the server, a key per connection, everything after
|
; 3: the Hello sealed for the server, a key per connection, everything after
|
||||||
; the ChallengeRequest encrypted (Connections.pbi). Messages carry when
|
; the ChallengeRequest encrypted (Connections.pbi). Messages carry when
|
||||||
; they were pushed (PushedAt).
|
; they were pushed (PushedAt).
|
||||||
#BakaShrot_ProtocolVersion = 3
|
; 4: attachments (Design/Attachments.md).
|
||||||
|
#BakaShrot_ProtocolVersion = 4
|
||||||
|
|
||||||
; Size in bytes of the nonce sent in a challenge request and echoed in its response.
|
; Size in bytes of the nonce sent in a challenge request and echoed in its response.
|
||||||
; It MUST be filled with CryptRandomData(), never reused, and be checked against the one the
|
; It MUST be filled with CryptRandomData(), never reused, and be checked against the one the
|
||||||
@@ -50,6 +51,32 @@ Procedure.i BakaShrot_IsValidTimestamp(Timestamp.q)
|
|||||||
ProcedureReturn Bool(Timestamp >= 1 And Timestamp <= #BakaShrot_MaxTimestamp)
|
ProcedureReturn Bool(Timestamp >= 1 And Timestamp <= #BakaShrot_MaxTimestamp)
|
||||||
EndProcedure
|
EndProcedure
|
||||||
|
|
||||||
|
; Attachments (Design/Attachments.md): at most one per message, sent and
|
||||||
|
; stored in parts of #BakaShrot_AttachmentChunkSize bytes (the last one what's
|
||||||
|
; left), checked with their SHA-256. #BakaShrot_MaxAttachmentSize is the
|
||||||
|
; protocol's limit, each server sets its own ([BakaShrot.Server]
|
||||||
|
; MaxAttachmentSize).
|
||||||
|
#BakaShrot_AttachmentChunkSize = 1048576
|
||||||
|
#BakaShrot_MaxAttachmentSize = 1099511627776
|
||||||
|
#BakaShrot_MaxAttachmentChunks = #BakaShrot_MaxAttachmentSize / #BakaShrot_AttachmentChunkSize
|
||||||
|
#BakaShrot_Sha256Size = 32
|
||||||
|
|
||||||
|
; How many parts Size bytes take.
|
||||||
|
Procedure.q BakaShrot_AttachmentChunkCount(Size.q)
|
||||||
|
ProcedureReturn (Size + #BakaShrot_AttachmentChunkSize - 1) / #BakaShrot_AttachmentChunkSize
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
; How big part Index of Size bytes is, 0 if there's no such part.
|
||||||
|
Procedure.i BakaShrot_AttachmentChunkBytes(Size.q, Index.q)
|
||||||
|
Protected Left.q = Size - Index * #BakaShrot_AttachmentChunkSize
|
||||||
|
If Index < 0 Or Left <= 0
|
||||||
|
ProcedureReturn 0
|
||||||
|
ElseIf Left > #BakaShrot_AttachmentChunkSize
|
||||||
|
ProcedureReturn #BakaShrot_AttachmentChunkSize
|
||||||
|
EndIf
|
||||||
|
ProcedureReturn Left
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
; Biggest packet accepted on the wire once authenticated, anything bigger
|
; Biggest packet accepted on the wire once authenticated, anything bigger
|
||||||
; aborts the connection. Before that, only #BakaShrot_MaxHandshakePacketSize
|
; aborts the connection. Before that, only #BakaShrot_MaxHandshakePacketSize
|
||||||
; (Connections.pbi).
|
; (Connections.pbi).
|
||||||
@@ -97,6 +124,20 @@ Enumeration BakaShrot_PacketTypes
|
|||||||
; A run of messages of a topic/node, only accepted once authenticated.
|
; A run of messages of a topic/node, only accepted once authenticated.
|
||||||
#BakaShrot_PacketType_GetMessages = 22
|
#BakaShrot_PacketType_GetMessages = 22
|
||||||
#BakaShrot_PacketType_Messages = 23
|
#BakaShrot_PacketType_Messages = 23
|
||||||
|
|
||||||
|
; Attachments, only accepted once authenticated: uploading one (before
|
||||||
|
; its PushMessage), and reading one, in parts.
|
||||||
|
#BakaShrot_PacketType_UploadStart = 24
|
||||||
|
#BakaShrot_PacketType_UploadStarted = 25
|
||||||
|
#BakaShrot_PacketType_UploadChunk = 26
|
||||||
|
#BakaShrot_PacketType_ChunkStored = 27
|
||||||
|
#BakaShrot_PacketType_GetAttachment = 28
|
||||||
|
#BakaShrot_PacketType_AttachmentChunk = 29
|
||||||
|
|
||||||
|
; Replicating attachments, only accepted from peers, once their messages are.
|
||||||
|
#BakaShrot_PacketType_MissingAttachmentsRequest = 30
|
||||||
|
#BakaShrot_PacketType_MissingAttachments = 31
|
||||||
|
#BakaShrot_PacketType_ReplicateAttachmentChunk = 32
|
||||||
EndEnumeration
|
EndEnumeration
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,195 @@
|
|||||||
|
; ============================================================================
|
||||||
|
; ...
|
||||||
|
; ============================================================================
|
||||||
|
|
||||||
|
|
||||||
|
XIncludeFile "../Packets.pbi"
|
||||||
|
|
||||||
|
; S2C, answers a GetAttachment: part ChunkIndex of the attachment of
|
||||||
|
; TopicId:NodeId#MessageId (the server's ids), Size bytes in all, in parts of
|
||||||
|
; #BakaShrot_AttachmentChunkSize, whose SHA-256 is Sha256.
|
||||||
|
Structure BakaShrot_AttachmentChunk Extends BakaShrot_PacketBase
|
||||||
|
TopicId.l
|
||||||
|
NodeId.l
|
||||||
|
MessageId.q
|
||||||
|
Size.q
|
||||||
|
Sha256.a[#BakaShrot_Sha256Size]
|
||||||
|
ChunkIndex.l
|
||||||
|
*Data
|
||||||
|
DataSize.l
|
||||||
|
EndStructure
|
||||||
|
|
||||||
|
|
||||||
|
; Encodes *Chunk into a freshly allocated buffer, its base fields are set by this procedure.
|
||||||
|
; *OutSize receives its size in bytes.
|
||||||
|
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
|
||||||
|
Procedure.i BakaShrot_AttachmentChunkPacket_Encode(*Chunk.BakaShrot_AttachmentChunk, *OutSize.Integer)
|
||||||
|
Protected *MsgPackData.MsgPackData, *Buffer
|
||||||
|
|
||||||
|
*Chunk\Magic = #BakaShrot_ProtocolMagic
|
||||||
|
*Chunk\Version = #BakaShrot_ProtocolVersion
|
||||||
|
*Chunk\PacketType = #BakaShrot_PacketType_AttachmentChunk
|
||||||
|
|
||||||
|
If *Chunk\TopicId < 0 Or *Chunk\TopicId > #BakaShrot_MaxId Or *Chunk\NodeId < 0 Or *Chunk\NodeId > #BakaShrot_MaxId Or *Chunk\MessageId < 1 Or *Chunk\Size < 1 Or *Chunk\Size > #BakaShrot_MaxAttachmentSize Or *Chunk\ChunkIndex < 0 Or *Chunk\ChunkIndex > #BakaShrot_MaxAttachmentChunks Or Not *Chunk\Data Or *Chunk\DataSize < 1 Or *Chunk\DataSize > #BakaShrot_AttachmentChunkSize
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
*MsgPackData = MsgPackCreate(#BakaShrot_AttachmentChunkSize + 256)
|
||||||
|
If Not *MsgPackData
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If Not BakaShrot_WritePacketBase(*Chunk, *MsgPackData)
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If MsgPackWriteInteger(*MsgPackData, *Chunk\TopicId) <> #MsgPack_Error_Success
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If MsgPackWriteInteger(*MsgPackData, *Chunk\NodeId) <> #MsgPack_Error_Success
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If MsgPackWriteInteger(*MsgPackData, *Chunk\MessageId) <> #MsgPack_Error_Success
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If MsgPackWriteInteger(*MsgPackData, *Chunk\Size) <> #MsgPack_Error_Success
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If MsgPackWriteBinary(*MsgPackData, @*Chunk\Sha256[0], #BakaShrot_Sha256Size) <> #MsgPack_Error_Success
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If MsgPackWriteInteger(*MsgPackData, *Chunk\ChunkIndex) <> #MsgPack_Error_Success
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If MsgPackWriteBinary(*MsgPackData, *Chunk\Data, *Chunk\DataSize) <> #MsgPack_Error_Success
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; Frees *MsgPackData on success, leaves it untouched on failure.
|
||||||
|
*Buffer = MsgPackFinalize(*MsgPackData)
|
||||||
|
If Not *Buffer
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
*OutSize\i = MemorySize(*Buffer)
|
||||||
|
ProcedureReturn *Buffer
|
||||||
|
|
||||||
|
EncodeFailed:
|
||||||
|
MsgPackFree(*MsgPackData, #True)
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
; Frees a decoded *Chunk and the data it holds.
|
||||||
|
Procedure BakaShrot_AttachmentChunkPacket_Free(*Chunk.BakaShrot_AttachmentChunk)
|
||||||
|
If Not *Chunk
|
||||||
|
ProcedureReturn
|
||||||
|
EndIf
|
||||||
|
If *Chunk\Data
|
||||||
|
FreeMemory(*Chunk\Data)
|
||||||
|
EndIf
|
||||||
|
FreeStructure(*Chunk)
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
|
||||||
|
; *MsgPackData stays owned by the caller, and should be discarded on failure.
|
||||||
|
; Returns 0 on failure, the caller owns the returned struct - free it with BakaShrot_AttachmentChunkPacket_Free().
|
||||||
|
Procedure.i BakaShrot_AttachmentChunkPacket_Decode(*MsgPackData.MsgPackData)
|
||||||
|
Protected *Chunk.BakaShrot_AttachmentChunk, Value.q, ReadSize.q
|
||||||
|
|
||||||
|
*Chunk = AllocateStructure(BakaShrot_AttachmentChunk)
|
||||||
|
If Not *Chunk
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; The base parser doesn't check which packet it is, that's on us.
|
||||||
|
If Not BakaShrot_ReadPacketBase(*Chunk, *MsgPackData) Or *Chunk\PacketType <> #BakaShrot_PacketType_AttachmentChunk
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; TopicId
|
||||||
|
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
Value = MsgPackReadInteger(*MsgPackData)
|
||||||
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > #BakaShrot_MaxId
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
*Chunk\TopicId = Value
|
||||||
|
|
||||||
|
; NodeId
|
||||||
|
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
Value = MsgPackReadInteger(*MsgPackData)
|
||||||
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > #BakaShrot_MaxId
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
*Chunk\NodeId = Value
|
||||||
|
|
||||||
|
; MessageId
|
||||||
|
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
Value = MsgPackReadInteger(*MsgPackData)
|
||||||
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 1
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
*Chunk\MessageId = Value
|
||||||
|
|
||||||
|
; Size
|
||||||
|
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
Value = MsgPackReadInteger(*MsgPackData)
|
||||||
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 1 Or Value > #BakaShrot_MaxAttachmentSize
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
*Chunk\Size = Value
|
||||||
|
|
||||||
|
; Sha256
|
||||||
|
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
; Anything bigger than the struct's array is rejected by MsgPackReadBinary, anything smaller by the size check.
|
||||||
|
ReadSize = MsgPackReadBinary(*MsgPackData, @*Chunk\Sha256[0], #BakaShrot_Sha256Size)
|
||||||
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or ReadSize <> #BakaShrot_Sha256Size
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; ChunkIndex
|
||||||
|
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
Value = MsgPackReadInteger(*MsgPackData)
|
||||||
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > #BakaShrot_MaxAttachmentChunks
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
*Chunk\ChunkIndex = Value
|
||||||
|
|
||||||
|
; Data
|
||||||
|
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
; A copy, freed with the packet (_Free()).
|
||||||
|
*Chunk\Data = MsgPackCopyBinary(*MsgPackData)
|
||||||
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not *Chunk\Data
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
*Chunk\DataSize = MemorySize(*Chunk\Data)
|
||||||
|
If *Chunk\DataSize > #BakaShrot_AttachmentChunkSize
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
ProcedureReturn *Chunk
|
||||||
|
|
||||||
|
; Everything read so far is tainted, drop it.
|
||||||
|
DecodeFailed:
|
||||||
|
BakaShrot_AttachmentChunkPacket_Free(*Chunk)
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndProcedure
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
; ============================================================================
|
||||||
|
; ...
|
||||||
|
; ============================================================================
|
||||||
|
|
||||||
|
|
||||||
|
XIncludeFile "../Packets.pbi"
|
||||||
|
|
||||||
|
; S2C (and S2P), answers an UploadChunk (or a ReplicateAttachmentChunk): Received
|
||||||
|
; bytes are stored so far. Complete is 1 once they all are, and their SHA-256
|
||||||
|
; checked out.
|
||||||
|
Structure BakaShrot_ChunkStored Extends BakaShrot_PacketBase
|
||||||
|
Received.q
|
||||||
|
Complete.l
|
||||||
|
EndStructure
|
||||||
|
|
||||||
|
|
||||||
|
; Encodes *Stored into a freshly allocated buffer, its base fields are set by this procedure.
|
||||||
|
; *OutSize receives its size in bytes.
|
||||||
|
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
|
||||||
|
Procedure.i BakaShrot_ChunkStoredPacket_Encode(*Stored.BakaShrot_ChunkStored, *OutSize.Integer)
|
||||||
|
Protected *MsgPackData.MsgPackData, *Buffer
|
||||||
|
|
||||||
|
*Stored\Magic = #BakaShrot_ProtocolMagic
|
||||||
|
*Stored\Version = #BakaShrot_ProtocolVersion
|
||||||
|
*Stored\PacketType = #BakaShrot_PacketType_ChunkStored
|
||||||
|
|
||||||
|
If *Stored\Received < 0 Or *Stored\Received > #BakaShrot_MaxAttachmentSize Or *Stored\Complete < 0 Or *Stored\Complete > 1
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
*MsgPackData = MsgPackCreate(64)
|
||||||
|
If Not *MsgPackData
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If Not BakaShrot_WritePacketBase(*Stored, *MsgPackData)
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If MsgPackWriteInteger(*MsgPackData, *Stored\Received) <> #MsgPack_Error_Success
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If MsgPackWriteInteger(*MsgPackData, *Stored\Complete) <> #MsgPack_Error_Success
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; Frees *MsgPackData on success, leaves it untouched on failure.
|
||||||
|
*Buffer = MsgPackFinalize(*MsgPackData)
|
||||||
|
If Not *Buffer
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
*OutSize\i = MemorySize(*Buffer)
|
||||||
|
ProcedureReturn *Buffer
|
||||||
|
|
||||||
|
EncodeFailed:
|
||||||
|
MsgPackFree(*MsgPackData, #True)
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
|
||||||
|
; *MsgPackData stays owned by the caller, and should be discarded on failure.
|
||||||
|
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
|
||||||
|
Procedure.i BakaShrot_ChunkStoredPacket_Decode(*MsgPackData.MsgPackData)
|
||||||
|
Protected *Stored.BakaShrot_ChunkStored, Value.q
|
||||||
|
|
||||||
|
*Stored = AllocateStructure(BakaShrot_ChunkStored)
|
||||||
|
If Not *Stored
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; The base parser doesn't check which packet it is, that's on us.
|
||||||
|
If Not BakaShrot_ReadPacketBase(*Stored, *MsgPackData) Or *Stored\PacketType <> #BakaShrot_PacketType_ChunkStored
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; Received
|
||||||
|
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
Value = MsgPackReadInteger(*MsgPackData)
|
||||||
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > #BakaShrot_MaxAttachmentSize
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
*Stored\Received = Value
|
||||||
|
|
||||||
|
; Complete
|
||||||
|
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
Value = MsgPackReadInteger(*MsgPackData)
|
||||||
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > 1
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
*Stored\Complete = Value
|
||||||
|
|
||||||
|
ProcedureReturn *Stored
|
||||||
|
|
||||||
|
; Everything read so far is tainted, drop it.
|
||||||
|
DecodeFailed:
|
||||||
|
FreeStructure(*Stored)
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndProcedure
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
; ============================================================================
|
||||||
|
; ...
|
||||||
|
; ============================================================================
|
||||||
|
|
||||||
|
|
||||||
|
XIncludeFile "../Packets.pbi"
|
||||||
|
|
||||||
|
; C2S, asks for part ChunkIndex (0 for the first) of the attachment of a message.
|
||||||
|
; Topic, Node: each a name or an id in digits, as GetMessages'. ReadTopics must
|
||||||
|
; allow the topic.
|
||||||
|
; Answered with an AttachmentChunk, or a RequestRefused (no such message, no
|
||||||
|
; attachment, or not here yet: replicated attachments come after their message).
|
||||||
|
Structure BakaShrot_GetAttachment Extends BakaShrot_PacketBase
|
||||||
|
Topic.s
|
||||||
|
Node.s
|
||||||
|
MessageId.q
|
||||||
|
ChunkIndex.l
|
||||||
|
EndStructure
|
||||||
|
|
||||||
|
|
||||||
|
; Encodes *Request into a freshly allocated buffer, its base fields are set by this procedure.
|
||||||
|
; *OutSize receives its size in bytes.
|
||||||
|
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
|
||||||
|
Procedure.i BakaShrot_GetAttachmentPacket_Encode(*Request.BakaShrot_GetAttachment, *OutSize.Integer)
|
||||||
|
Protected *MsgPackData.MsgPackData, *Buffer
|
||||||
|
|
||||||
|
*Request\Magic = #BakaShrot_ProtocolMagic
|
||||||
|
*Request\Version = #BakaShrot_ProtocolVersion
|
||||||
|
*Request\PacketType = #BakaShrot_PacketType_GetAttachment
|
||||||
|
|
||||||
|
If *Request\MessageId < 1 Or *Request\ChunkIndex < 0 Or *Request\ChunkIndex > #BakaShrot_MaxAttachmentChunks
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
*MsgPackData = MsgPackCreate(64)
|
||||||
|
If Not *MsgPackData
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If Not BakaShrot_WritePacketBase(*Request, *MsgPackData)
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If MsgPackWriteString(*MsgPackData, *Request\Topic) <> #MsgPack_Error_Success
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If MsgPackWriteString(*MsgPackData, *Request\Node) <> #MsgPack_Error_Success
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If MsgPackWriteInteger(*MsgPackData, *Request\MessageId) <> #MsgPack_Error_Success
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If MsgPackWriteInteger(*MsgPackData, *Request\ChunkIndex) <> #MsgPack_Error_Success
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; Frees *MsgPackData on success, leaves it untouched on failure.
|
||||||
|
*Buffer = MsgPackFinalize(*MsgPackData)
|
||||||
|
If Not *Buffer
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
*OutSize\i = MemorySize(*Buffer)
|
||||||
|
ProcedureReturn *Buffer
|
||||||
|
|
||||||
|
EncodeFailed:
|
||||||
|
MsgPackFree(*MsgPackData, #True)
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
|
||||||
|
; *MsgPackData stays owned by the caller, and should be discarded on failure.
|
||||||
|
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
|
||||||
|
Procedure.i BakaShrot_GetAttachmentPacket_Decode(*MsgPackData.MsgPackData)
|
||||||
|
Protected *Request.BakaShrot_GetAttachment, Value.q
|
||||||
|
|
||||||
|
*Request = AllocateStructure(BakaShrot_GetAttachment)
|
||||||
|
If Not *Request
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; The base parser doesn't check which packet it is, that's on us.
|
||||||
|
If Not BakaShrot_ReadPacketBase(*Request, *MsgPackData) Or *Request\PacketType <> #BakaShrot_PacketType_GetAttachment
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; Topic
|
||||||
|
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
*Request\Topic = MsgPackReadString(*MsgPackData)
|
||||||
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; Node
|
||||||
|
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
*Request\Node = MsgPackReadString(*MsgPackData)
|
||||||
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; MessageId
|
||||||
|
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
Value = MsgPackReadInteger(*MsgPackData)
|
||||||
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 1
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
*Request\MessageId = Value
|
||||||
|
|
||||||
|
; ChunkIndex
|
||||||
|
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
Value = MsgPackReadInteger(*MsgPackData)
|
||||||
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > #BakaShrot_MaxAttachmentChunks
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
*Request\ChunkIndex = Value
|
||||||
|
|
||||||
|
ProcedureReturn *Request
|
||||||
|
|
||||||
|
; Everything read so far is tainted, drop it.
|
||||||
|
DecodeFailed:
|
||||||
|
FreeStructure(*Request)
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndProcedure
|
||||||
@@ -17,6 +17,10 @@ Structure BakaShrot_LatestMessage Extends BakaShrot_PacketBase
|
|||||||
MessageId.q
|
MessageId.q
|
||||||
PushedAt.q
|
PushedAt.q
|
||||||
JsonData.s
|
JsonData.s
|
||||||
|
; Its attachment's size in bytes, 0 for none, and whether this server has
|
||||||
|
; all of it yet (a replicated one comes after its message).
|
||||||
|
AttachmentSize.q
|
||||||
|
AttachmentReady.l
|
||||||
EndStructure
|
EndStructure
|
||||||
|
|
||||||
|
|
||||||
@@ -65,6 +69,12 @@ Procedure.i BakaShrot_LatestMessagePacket_Encode(*Latest.BakaShrot_LatestMessage
|
|||||||
If MsgPackWriteString(*MsgPackData, *Latest\JsonData) <> #MsgPack_Error_Success
|
If MsgPackWriteString(*MsgPackData, *Latest\JsonData) <> #MsgPack_Error_Success
|
||||||
Goto EncodeFailed
|
Goto EncodeFailed
|
||||||
EndIf
|
EndIf
|
||||||
|
If MsgPackWriteInteger(*MsgPackData, *Latest\AttachmentSize) <> #MsgPack_Error_Success
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
If MsgPackWriteInteger(*MsgPackData, *Latest\AttachmentReady) <> #MsgPack_Error_Success
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
; Frees *MsgPackData on success, leaves it untouched on failure.
|
; Frees *MsgPackData on success, leaves it untouched on failure.
|
||||||
*Buffer = MsgPackFinalize(*MsgPackData)
|
*Buffer = MsgPackFinalize(*MsgPackData)
|
||||||
@@ -161,6 +171,23 @@ Procedure.i BakaShrot_LatestMessagePacket_Decode(*MsgPackData.MsgPackData)
|
|||||||
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
|
||||||
Goto DecodeFailed
|
Goto DecodeFailed
|
||||||
EndIf
|
EndIf
|
||||||
|
; AttachmentSize
|
||||||
|
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
*Latest\AttachmentSize = MsgPackReadInteger(*MsgPackData)
|
||||||
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Latest\AttachmentSize < 0 Or *Latest\AttachmentSize > #BakaShrot_MaxAttachmentSize
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; AttachmentReady
|
||||||
|
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
*Latest\AttachmentReady = MsgPackReadInteger(*MsgPackData)
|
||||||
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Latest\AttachmentReady < 0 Or *Latest\AttachmentReady > 1
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
ProcedureReturn *Latest
|
ProcedureReturn *Latest
|
||||||
|
|
||||||
|
|||||||
@@ -11,6 +11,10 @@ Structure BakaShrot_MessagesEntry
|
|||||||
MessageId.q
|
MessageId.q
|
||||||
; When it was pushed, see Packets.pbi.
|
; When it was pushed, see Packets.pbi.
|
||||||
PushedAt.q
|
PushedAt.q
|
||||||
|
; Its attachment's size in bytes, 0 for none, and whether this server has
|
||||||
|
; all of it yet (a replicated one comes after its message).
|
||||||
|
AttachmentSize.q
|
||||||
|
AttachmentReady.l
|
||||||
JsonData.s
|
JsonData.s
|
||||||
EndStructure
|
EndStructure
|
||||||
|
|
||||||
@@ -21,7 +25,7 @@ EndStructure
|
|||||||
; Encoded size of the answer's own fields, and of each message on top of its
|
; Encoded size of the answer's own fields, and of each message on top of its
|
||||||
; JSON, rounded up. Used to stop an answer before it gets over #BakaShrot_MaxPacketSize.
|
; JSON, rounded up. Used to stop an answer before it gets over #BakaShrot_MaxPacketSize.
|
||||||
#BakaShrot_MessagesOverhead = 64 + 2 * (#BakaShrot_MaxNameLength + 2)
|
#BakaShrot_MessagesOverhead = 64 + 2 * (#BakaShrot_MaxNameLength + 2)
|
||||||
#BakaShrot_MessagesMessageOverhead = 25
|
#BakaShrot_MessagesMessageOverhead = 40
|
||||||
|
|
||||||
; S2C, answers a GetMessages with the messages of that topic/node combination
|
; S2C, answers a GetMessages with the messages of that topic/node combination
|
||||||
; stored after the asked id, in message id order: as many as were asked for,
|
; stored after the asked id, in message id order: as many as were asked for,
|
||||||
@@ -99,6 +103,12 @@ Procedure.i BakaShrot_MessagesPacket_Encode(*Answer.BakaShrot_Messages, *OutSize
|
|||||||
If MsgPackWriteString(*MsgPackData, *Answer\Messages()\JsonData) <> #MsgPack_Error_Success
|
If MsgPackWriteString(*MsgPackData, *Answer\Messages()\JsonData) <> #MsgPack_Error_Success
|
||||||
Goto EncodeFailed
|
Goto EncodeFailed
|
||||||
EndIf
|
EndIf
|
||||||
|
If MsgPackWriteInteger(*MsgPackData, *Answer\Messages()\AttachmentSize) <> #MsgPack_Error_Success
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
If MsgPackWriteInteger(*MsgPackData, *Answer\Messages()\AttachmentReady) <> #MsgPack_Error_Success
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
Next
|
Next
|
||||||
|
|
||||||
; Frees *MsgPackData on success, leaves it untouched on failure.
|
; Frees *MsgPackData on success, leaves it untouched on failure.
|
||||||
@@ -222,6 +232,23 @@ Procedure.i BakaShrot_MessagesPacket_Decode(*MsgPackData.MsgPackData)
|
|||||||
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
|
||||||
Goto DecodeFailed
|
Goto DecodeFailed
|
||||||
EndIf
|
EndIf
|
||||||
|
; AttachmentSize
|
||||||
|
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
*Answer\Messages()\AttachmentSize = MsgPackReadInteger(*MsgPackData)
|
||||||
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Answer\Messages()\AttachmentSize < 0 Or *Answer\Messages()\AttachmentSize > #BakaShrot_MaxAttachmentSize
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; AttachmentReady
|
||||||
|
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
*Answer\Messages()\AttachmentReady = MsgPackReadInteger(*MsgPackData)
|
||||||
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Answer\Messages()\AttachmentReady < 0 Or *Answer\Messages()\AttachmentReady > 1
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
Next
|
Next
|
||||||
|
|
||||||
ProcedureReturn *Answer
|
ProcedureReturn *Answer
|
||||||
|
|||||||
@@ -0,0 +1,156 @@
|
|||||||
|
; ============================================================================
|
||||||
|
; ...
|
||||||
|
; ============================================================================
|
||||||
|
|
||||||
|
|
||||||
|
XIncludeFile "../Packets.pbi"
|
||||||
|
|
||||||
|
; Most attachments one MissingAttachments lists, the next check-in asks again.
|
||||||
|
#BakaShrot_MaxMissingAttachments = 256
|
||||||
|
|
||||||
|
; One attachment the server is missing: of Topic:Node#MessageId (names, never
|
||||||
|
; digits), from part NextChunk on (0 if it has none of it yet).
|
||||||
|
Structure BakaShrot_MissingAttachment
|
||||||
|
Topic.s
|
||||||
|
Node.s
|
||||||
|
MessageId.q
|
||||||
|
NextChunk.l
|
||||||
|
EndStructure
|
||||||
|
|
||||||
|
; S2P, answers a MissingAttachmentsRequest: attachments of messages the server
|
||||||
|
; has, that it takes from this peer, and doesn't have all of yet. Maybe none.
|
||||||
|
; On the wire: the count, then each one's topic, node, message id and next chunk.
|
||||||
|
Structure BakaShrot_MissingAttachments Extends BakaShrot_PacketBase
|
||||||
|
List Attachments.BakaShrot_MissingAttachment()
|
||||||
|
EndStructure
|
||||||
|
|
||||||
|
|
||||||
|
; Encodes *Answer into a freshly allocated buffer, its base fields are set by this procedure.
|
||||||
|
; *OutSize receives its size in bytes.
|
||||||
|
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
|
||||||
|
Procedure.i BakaShrot_MissingAttachmentsPacket_Encode(*Answer.BakaShrot_MissingAttachments, *OutSize.Integer)
|
||||||
|
Protected *MsgPackData.MsgPackData, *Buffer
|
||||||
|
|
||||||
|
*Answer\Magic = #BakaShrot_ProtocolMagic
|
||||||
|
*Answer\Version = #BakaShrot_ProtocolVersion
|
||||||
|
*Answer\PacketType = #BakaShrot_PacketType_MissingAttachments
|
||||||
|
|
||||||
|
If ListSize(*Answer\Attachments()) > #BakaShrot_MaxMissingAttachments
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
*MsgPackData = MsgPackCreate(256)
|
||||||
|
If Not *MsgPackData
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If Not BakaShrot_WritePacketBase(*Answer, *MsgPackData)
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If MsgPackWriteInteger(*MsgPackData, ListSize(*Answer\Attachments())) <> #MsgPack_Error_Success
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
ForEach *Answer\Attachments()
|
||||||
|
If MsgPackWriteString(*MsgPackData, *Answer\Attachments()\Topic) <> #MsgPack_Error_Success
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
If MsgPackWriteString(*MsgPackData, *Answer\Attachments()\Node) <> #MsgPack_Error_Success
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
If MsgPackWriteInteger(*MsgPackData, *Answer\Attachments()\MessageId) <> #MsgPack_Error_Success
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
If MsgPackWriteInteger(*MsgPackData, *Answer\Attachments()\NextChunk) <> #MsgPack_Error_Success
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
Next
|
||||||
|
|
||||||
|
; Frees *MsgPackData on success, leaves it untouched on failure.
|
||||||
|
*Buffer = MsgPackFinalize(*MsgPackData)
|
||||||
|
If Not *Buffer
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
*OutSize\i = MemorySize(*Buffer)
|
||||||
|
ProcedureReturn *Buffer
|
||||||
|
|
||||||
|
EncodeFailed:
|
||||||
|
MsgPackFree(*MsgPackData, #True)
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
|
||||||
|
; *MsgPackData stays owned by the caller, and should be discarded on failure.
|
||||||
|
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
|
||||||
|
Procedure.i BakaShrot_MissingAttachmentsPacket_Decode(*MsgPackData.MsgPackData)
|
||||||
|
Protected *Answer.BakaShrot_MissingAttachments
|
||||||
|
Protected Value.q, Count.q, i.q
|
||||||
|
|
||||||
|
*Answer = AllocateStructure(BakaShrot_MissingAttachments)
|
||||||
|
If Not *Answer
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; The base parser doesn't check which packet it is, that's on us.
|
||||||
|
If Not BakaShrot_ReadPacketBase(*Answer, *MsgPackData) Or *Answer\PacketType <> #BakaShrot_PacketType_MissingAttachments
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; Count
|
||||||
|
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
Count = MsgPackReadInteger(*MsgPackData)
|
||||||
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Count < 0 Or Count > #BakaShrot_MaxMissingAttachments
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
For i = 1 To Count
|
||||||
|
AddElement(*Answer\Attachments())
|
||||||
|
|
||||||
|
; Topic
|
||||||
|
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
*Answer\Attachments()\Topic = MsgPackReadString(*MsgPackData)
|
||||||
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsValidName(*Answer\Attachments()\Topic)
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; Node
|
||||||
|
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
*Answer\Attachments()\Node = MsgPackReadString(*MsgPackData)
|
||||||
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsValidName(*Answer\Attachments()\Node)
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; MessageId
|
||||||
|
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
*Answer\Attachments()\MessageId = MsgPackReadInteger(*MsgPackData)
|
||||||
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Answer\Attachments()\MessageId < 1
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; NextChunk
|
||||||
|
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
Value = MsgPackReadInteger(*MsgPackData)
|
||||||
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > #BakaShrot_MaxAttachmentChunks
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
*Answer\Attachments()\NextChunk = Value
|
||||||
|
Next
|
||||||
|
|
||||||
|
ProcedureReturn *Answer
|
||||||
|
|
||||||
|
; Everything read so far is tainted, drop it.
|
||||||
|
DecodeFailed:
|
||||||
|
FreeStructure(*Answer)
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndProcedure
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
; ============================================================================
|
||||||
|
; ...
|
||||||
|
; ============================================================================
|
||||||
|
|
||||||
|
|
||||||
|
XIncludeFile "../Packets.pbi"
|
||||||
|
|
||||||
|
; P2S, asks which attachments the server is still missing from this peer, once
|
||||||
|
; the messages are caught up. Only the base fields.
|
||||||
|
; Answered with a MissingAttachments, or a RequestRefused.
|
||||||
|
Structure BakaShrot_MissingAttachmentsRequest Extends BakaShrot_PacketBase
|
||||||
|
|
||||||
|
EndStructure
|
||||||
|
|
||||||
|
|
||||||
|
; Encodes *Request into a freshly allocated buffer, its base fields are set by this procedure.
|
||||||
|
; *OutSize receives its size in bytes.
|
||||||
|
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
|
||||||
|
Procedure.i BakaShrot_MissingAttachmentsRequestPacket_Encode(*Request.BakaShrot_MissingAttachmentsRequest, *OutSize.Integer)
|
||||||
|
Protected *MsgPackData.MsgPackData, *Buffer
|
||||||
|
|
||||||
|
*Request\Magic = #BakaShrot_ProtocolMagic
|
||||||
|
*Request\Version = #BakaShrot_ProtocolVersion
|
||||||
|
*Request\PacketType = #BakaShrot_PacketType_MissingAttachmentsRequest
|
||||||
|
|
||||||
|
*MsgPackData = MsgPackCreate(64)
|
||||||
|
If Not *MsgPackData
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If Not BakaShrot_WritePacketBase(*Request, *MsgPackData)
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; Frees *MsgPackData on success, leaves it untouched on failure.
|
||||||
|
*Buffer = MsgPackFinalize(*MsgPackData)
|
||||||
|
If Not *Buffer
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
*OutSize\i = MemorySize(*Buffer)
|
||||||
|
ProcedureReturn *Buffer
|
||||||
|
|
||||||
|
EncodeFailed:
|
||||||
|
MsgPackFree(*MsgPackData, #True)
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
|
||||||
|
; *MsgPackData stays owned by the caller, and should be discarded on failure.
|
||||||
|
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
|
||||||
|
Procedure.i BakaShrot_MissingAttachmentsRequestPacket_Decode(*MsgPackData.MsgPackData)
|
||||||
|
Protected *Request.BakaShrot_MissingAttachmentsRequest
|
||||||
|
|
||||||
|
*Request = AllocateStructure(BakaShrot_MissingAttachmentsRequest)
|
||||||
|
If Not *Request
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; The base parser doesn't check which packet it is, that's on us.
|
||||||
|
If Not BakaShrot_ReadPacketBase(*Request, *MsgPackData) Or *Request\PacketType <> #BakaShrot_PacketType_MissingAttachmentsRequest
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
ProcedureReturn *Request
|
||||||
|
|
||||||
|
; Everything read so far is tainted, drop it.
|
||||||
|
DecodeFailed:
|
||||||
|
FreeStructure(*Request)
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndProcedure
|
||||||
@@ -10,10 +10,12 @@ XIncludeFile "../Packets.pbi"
|
|||||||
; "" for the topic of the client's authenticated identity. The client's
|
; "" for the topic of the client's authenticated identity. The client's
|
||||||
; [BakaShrot.Client.<name>] PushTopics must allow it.
|
; [BakaShrot.Client.<name>] PushTopics must allow it.
|
||||||
; The node is always the client's authenticated one, the client can't pick it.
|
; The node is always the client's authenticated one, the client can't pick it.
|
||||||
|
; UploadId: the attachment uploaded for it (UploadStart, all of it stored), 0 for none.
|
||||||
; Answered with a MessagePushed or a RequestRefused.
|
; Answered with a MessagePushed or a RequestRefused.
|
||||||
Structure BakaShrot_PushMessage Extends BakaShrot_PacketBase
|
Structure BakaShrot_PushMessage Extends BakaShrot_PacketBase
|
||||||
Topic.s
|
Topic.s
|
||||||
JsonData.s
|
JsonData.s
|
||||||
|
UploadId.q
|
||||||
EndStructure
|
EndStructure
|
||||||
|
|
||||||
|
|
||||||
@@ -44,6 +46,10 @@ Procedure.i BakaShrot_PushMessagePacket_Encode(*Push.BakaShrot_PushMessage, *Out
|
|||||||
Goto EncodeFailed
|
Goto EncodeFailed
|
||||||
EndIf
|
EndIf
|
||||||
|
|
||||||
|
If *Push\UploadId < 0 Or MsgPackWriteInteger(*MsgPackData, *Push\UploadId) <> #MsgPack_Error_Success
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
; Frees *MsgPackData on success, leaves it untouched on failure.
|
; Frees *MsgPackData on success, leaves it untouched on failure.
|
||||||
*Buffer = MsgPackFinalize(*MsgPackData)
|
*Buffer = MsgPackFinalize(*MsgPackData)
|
||||||
If Not *Buffer
|
If Not *Buffer
|
||||||
@@ -92,6 +98,15 @@ Procedure.i BakaShrot_PushMessagePacket_Decode(*MsgPackData.MsgPackData)
|
|||||||
Goto DecodeFailed
|
Goto DecodeFailed
|
||||||
EndIf
|
EndIf
|
||||||
|
|
||||||
|
; UploadId
|
||||||
|
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
*Push\UploadId = MsgPackReadInteger(*MsgPackData)
|
||||||
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Push\UploadId < 0
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
ProcedureReturn *Push
|
ProcedureReturn *Push
|
||||||
|
|
||||||
; Everything read so far is tainted, drop it.
|
; Everything read so far is tainted, drop it.
|
||||||
|
|||||||
@@ -0,0 +1,164 @@
|
|||||||
|
; ============================================================================
|
||||||
|
; ...
|
||||||
|
; ============================================================================
|
||||||
|
|
||||||
|
|
||||||
|
XIncludeFile "../Packets.pbi"
|
||||||
|
|
||||||
|
; P2S, part ChunkIndex of the attachment of Topic:Node#MessageId (names, never
|
||||||
|
; digits), a message the server already has, as MissingAttachments asked for.
|
||||||
|
; The size and SHA-256 came with the message (ReplicateMessages).
|
||||||
|
; Answered with a ChunkStored, or a RequestRefused.
|
||||||
|
Structure BakaShrot_ReplicateAttachmentChunk Extends BakaShrot_PacketBase
|
||||||
|
Topic.s
|
||||||
|
Node.s
|
||||||
|
MessageId.q
|
||||||
|
ChunkIndex.l
|
||||||
|
*Data
|
||||||
|
DataSize.l
|
||||||
|
EndStructure
|
||||||
|
|
||||||
|
|
||||||
|
; Encodes *Chunk into a freshly allocated buffer, its base fields are set by this procedure.
|
||||||
|
; *OutSize receives its size in bytes.
|
||||||
|
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
|
||||||
|
Procedure.i BakaShrot_ReplicateAttachmentChunkPacket_Encode(*Chunk.BakaShrot_ReplicateAttachmentChunk, *OutSize.Integer)
|
||||||
|
Protected *MsgPackData.MsgPackData, *Buffer
|
||||||
|
|
||||||
|
*Chunk\Magic = #BakaShrot_ProtocolMagic
|
||||||
|
*Chunk\Version = #BakaShrot_ProtocolVersion
|
||||||
|
*Chunk\PacketType = #BakaShrot_PacketType_ReplicateAttachmentChunk
|
||||||
|
|
||||||
|
If Not BakaShrot_IsValidName(*Chunk\Topic) Or Not BakaShrot_IsValidName(*Chunk\Node) Or *Chunk\MessageId < 1 Or *Chunk\ChunkIndex < 0 Or *Chunk\ChunkIndex > #BakaShrot_MaxAttachmentChunks Or Not *Chunk\Data Or *Chunk\DataSize < 1 Or *Chunk\DataSize > #BakaShrot_AttachmentChunkSize
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
*MsgPackData = MsgPackCreate(#BakaShrot_AttachmentChunkSize + 256)
|
||||||
|
If Not *MsgPackData
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If Not BakaShrot_WritePacketBase(*Chunk, *MsgPackData)
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If MsgPackWriteString(*MsgPackData, *Chunk\Topic) <> #MsgPack_Error_Success
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If MsgPackWriteString(*MsgPackData, *Chunk\Node) <> #MsgPack_Error_Success
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If MsgPackWriteInteger(*MsgPackData, *Chunk\MessageId) <> #MsgPack_Error_Success
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If MsgPackWriteInteger(*MsgPackData, *Chunk\ChunkIndex) <> #MsgPack_Error_Success
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If MsgPackWriteBinary(*MsgPackData, *Chunk\Data, *Chunk\DataSize) <> #MsgPack_Error_Success
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; Frees *MsgPackData on success, leaves it untouched on failure.
|
||||||
|
*Buffer = MsgPackFinalize(*MsgPackData)
|
||||||
|
If Not *Buffer
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
*OutSize\i = MemorySize(*Buffer)
|
||||||
|
ProcedureReturn *Buffer
|
||||||
|
|
||||||
|
EncodeFailed:
|
||||||
|
MsgPackFree(*MsgPackData, #True)
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
; Frees a decoded *Chunk and the data it holds.
|
||||||
|
Procedure BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk.BakaShrot_ReplicateAttachmentChunk)
|
||||||
|
If Not *Chunk
|
||||||
|
ProcedureReturn
|
||||||
|
EndIf
|
||||||
|
If *Chunk\Data
|
||||||
|
FreeMemory(*Chunk\Data)
|
||||||
|
EndIf
|
||||||
|
FreeStructure(*Chunk)
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
|
||||||
|
; *MsgPackData stays owned by the caller, and should be discarded on failure.
|
||||||
|
; Returns 0 on failure, the caller owns the returned struct - free it with BakaShrot_ReplicateAttachmentChunkPacket_Free().
|
||||||
|
Procedure.i BakaShrot_ReplicateAttachmentChunkPacket_Decode(*MsgPackData.MsgPackData)
|
||||||
|
Protected *Chunk.BakaShrot_ReplicateAttachmentChunk, Value.q
|
||||||
|
|
||||||
|
*Chunk = AllocateStructure(BakaShrot_ReplicateAttachmentChunk)
|
||||||
|
If Not *Chunk
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; The base parser doesn't check which packet it is, that's on us.
|
||||||
|
If Not BakaShrot_ReadPacketBase(*Chunk, *MsgPackData) Or *Chunk\PacketType <> #BakaShrot_PacketType_ReplicateAttachmentChunk
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; Topic
|
||||||
|
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
*Chunk\Topic = MsgPackReadString(*MsgPackData)
|
||||||
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsValidName(*Chunk\Topic)
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; Node
|
||||||
|
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
*Chunk\Node = MsgPackReadString(*MsgPackData)
|
||||||
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsValidName(*Chunk\Node)
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; MessageId
|
||||||
|
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
Value = MsgPackReadInteger(*MsgPackData)
|
||||||
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 1
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
*Chunk\MessageId = Value
|
||||||
|
|
||||||
|
; ChunkIndex
|
||||||
|
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
Value = MsgPackReadInteger(*MsgPackData)
|
||||||
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > #BakaShrot_MaxAttachmentChunks
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
*Chunk\ChunkIndex = Value
|
||||||
|
|
||||||
|
; Data
|
||||||
|
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
; A copy, freed with the packet (_Free()).
|
||||||
|
*Chunk\Data = MsgPackCopyBinary(*MsgPackData)
|
||||||
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not *Chunk\Data
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
*Chunk\DataSize = MemorySize(*Chunk\Data)
|
||||||
|
If *Chunk\DataSize > #BakaShrot_AttachmentChunkSize
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
ProcedureReturn *Chunk
|
||||||
|
|
||||||
|
; Everything read so far is tainted, drop it.
|
||||||
|
DecodeFailed:
|
||||||
|
BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk)
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndProcedure
|
||||||
@@ -7,10 +7,15 @@ XIncludeFile "../Packets.pbi"
|
|||||||
|
|
||||||
; One message of a ReplicateMessages batch.
|
; One message of a ReplicateMessages batch.
|
||||||
; PushedAt: when it was pushed to its origin (Packets.pbi), stored as is.
|
; PushedAt: when it was pushed to its origin (Packets.pbi), stored as is.
|
||||||
|
; AttachmentSize, AttachmentSha256: its attachment's, 0 for none. The data
|
||||||
|
; itself follows on its own, once the messages are caught up
|
||||||
|
; (MissingAttachments, ReplicateAttachmentChunk).
|
||||||
Structure BakaShrot_ReplicatedMessage
|
Structure BakaShrot_ReplicatedMessage
|
||||||
MessageId.q
|
MessageId.q
|
||||||
PushedAt.q
|
PushedAt.q
|
||||||
JsonData.s
|
JsonData.s
|
||||||
|
AttachmentSize.q
|
||||||
|
AttachmentSha256.a[#BakaShrot_Sha256Size]
|
||||||
EndStructure
|
EndStructure
|
||||||
|
|
||||||
; Most messages a batch may carry, whatever the sender's PeerBatchSize.
|
; Most messages a batch may carry, whatever the sender's PeerBatchSize.
|
||||||
@@ -26,14 +31,15 @@ EndStructure
|
|||||||
; Encoded size of a batch's own fields, and of each message on top of its
|
; Encoded size of a batch's own fields, and of each message on top of its
|
||||||
; JSON, rounded up. Used to stop a batch before it gets over #BakaShrot_MaxPacketSize.
|
; JSON, rounded up. Used to stop a batch before it gets over #BakaShrot_MaxPacketSize.
|
||||||
#BakaShrot_ReplicateBatchOverhead = 64 + 2 * (#BakaShrot_MaxNameLength + 2)
|
#BakaShrot_ReplicateBatchOverhead = 64 + 2 * (#BakaShrot_MaxNameLength + 2)
|
||||||
#BakaShrot_ReplicateMessageOverhead = 25
|
#BakaShrot_ReplicateMessageOverhead = 70
|
||||||
|
|
||||||
; Peer -> Server, messages the server is missing for one topic/node, in
|
; Peer -> Server, messages the server is missing for one topic/node, in
|
||||||
; message id order, with the message ids they were stored under on their
|
; message id order, with the message ids they were stored under on their
|
||||||
; origin. Topic and Node are names, never ids (Commons/Networking/Names.pbi):
|
; origin. Topic and Node are names, never ids (Commons/Networking/Names.pbi):
|
||||||
; the server stores them under its own ids for those names, and refuses
|
; the server stores them under its own ids for those names, and refuses
|
||||||
; names it doesn't know.
|
; names it doesn't know.
|
||||||
; On the wire: topic, node, message count, then each message's id, PushedAt and JSON.
|
; On the wire: topic, node, message count, then each message's id, PushedAt,
|
||||||
|
; JSON, attachment size and SHA-256.
|
||||||
; Answered with a MessagePushed carrying the last message's id, or a RequestRefused.
|
; Answered with a MessagePushed carrying the last message's id, or a RequestRefused.
|
||||||
Structure BakaShrot_ReplicateMessages Extends BakaShrot_PacketBase
|
Structure BakaShrot_ReplicateMessages Extends BakaShrot_PacketBase
|
||||||
Topic.s
|
Topic.s
|
||||||
@@ -87,6 +93,17 @@ Procedure.i BakaShrot_ReplicateMessagesPacket_Encode(*Batch.BakaShrot_ReplicateM
|
|||||||
If MsgPackWriteString(*MsgPackData, *Batch\Messages()\JsonData) <> #MsgPack_Error_Success
|
If MsgPackWriteString(*MsgPackData, *Batch\Messages()\JsonData) <> #MsgPack_Error_Success
|
||||||
Goto EncodeFailed
|
Goto EncodeFailed
|
||||||
EndIf
|
EndIf
|
||||||
|
If MsgPackWriteInteger(*MsgPackData, *Batch\Messages()\AttachmentSize) <> #MsgPack_Error_Success
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
; Empty without an attachment.
|
||||||
|
If *Batch\Messages()\AttachmentSize > 0
|
||||||
|
If MsgPackWriteBinary(*MsgPackData, @*Batch\Messages()\AttachmentSha256[0], #BakaShrot_Sha256Size) <> #MsgPack_Error_Success
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
ElseIf MsgPackWriteBinary(*MsgPackData, @*Batch\Messages()\AttachmentSha256[0], 0) <> #MsgPack_Error_Success
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
Next
|
Next
|
||||||
|
|
||||||
; Frees *MsgPackData on success, leaves it untouched on failure.
|
; Frees *MsgPackData on success, leaves it untouched on failure.
|
||||||
@@ -109,7 +126,7 @@ EndProcedure
|
|||||||
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
|
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
|
||||||
Procedure.i BakaShrot_ReplicateMessagesPacket_Decode(*MsgPackData.MsgPackData)
|
Procedure.i BakaShrot_ReplicateMessagesPacket_Decode(*MsgPackData.MsgPackData)
|
||||||
Protected *Batch.BakaShrot_ReplicateMessages
|
Protected *Batch.BakaShrot_ReplicateMessages
|
||||||
Protected Value.q, Count.q, i.q, PreviousMessageId.q
|
Protected Value.q, Count.q, i.q, PreviousMessageId.q, ReadSize.q
|
||||||
|
|
||||||
*Batch = AllocateStructure(BakaShrot_ReplicateMessages)
|
*Batch = AllocateStructure(BakaShrot_ReplicateMessages)
|
||||||
If Not *Batch
|
If Not *Batch
|
||||||
@@ -180,6 +197,23 @@ Procedure.i BakaShrot_ReplicateMessagesPacket_Decode(*MsgPackData.MsgPackData)
|
|||||||
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
|
||||||
Goto DecodeFailed
|
Goto DecodeFailed
|
||||||
EndIf
|
EndIf
|
||||||
|
; AttachmentSize
|
||||||
|
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
*Batch\Messages()\AttachmentSize = MsgPackReadInteger(*MsgPackData)
|
||||||
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Batch\Messages()\AttachmentSize < 0 Or *Batch\Messages()\AttachmentSize > #BakaShrot_MaxAttachmentSize
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; AttachmentSha256: 32 bytes with an attachment, empty without.
|
||||||
|
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
ReadSize = MsgPackReadBinary(*MsgPackData, @*Batch\Messages()\AttachmentSha256[0], #BakaShrot_Sha256Size)
|
||||||
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or (ReadSize <> #BakaShrot_Sha256Size And *Batch\Messages()\AttachmentSize > 0) Or (ReadSize <> 0 And *Batch\Messages()\AttachmentSize = 0)
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
Next
|
Next
|
||||||
|
|
||||||
ProcedureReturn *Batch
|
ProcedureReturn *Batch
|
||||||
|
|||||||
@@ -0,0 +1,134 @@
|
|||||||
|
; ============================================================================
|
||||||
|
; ...
|
||||||
|
; ============================================================================
|
||||||
|
|
||||||
|
|
||||||
|
XIncludeFile "../Packets.pbi"
|
||||||
|
|
||||||
|
; C2S, the next part of an upload: ChunkIndex (0 for the first) of UploadId.
|
||||||
|
; Answered with a ChunkStored, or a RequestRefused (the upload is then dropped).
|
||||||
|
Structure BakaShrot_UploadChunk Extends BakaShrot_PacketBase
|
||||||
|
UploadId.q
|
||||||
|
ChunkIndex.l
|
||||||
|
*Data
|
||||||
|
DataSize.l
|
||||||
|
EndStructure
|
||||||
|
|
||||||
|
|
||||||
|
; Encodes *Chunk into a freshly allocated buffer, its base fields are set by this procedure.
|
||||||
|
; *OutSize receives its size in bytes.
|
||||||
|
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
|
||||||
|
Procedure.i BakaShrot_UploadChunkPacket_Encode(*Chunk.BakaShrot_UploadChunk, *OutSize.Integer)
|
||||||
|
Protected *MsgPackData.MsgPackData, *Buffer
|
||||||
|
|
||||||
|
*Chunk\Magic = #BakaShrot_ProtocolMagic
|
||||||
|
*Chunk\Version = #BakaShrot_ProtocolVersion
|
||||||
|
*Chunk\PacketType = #BakaShrot_PacketType_UploadChunk
|
||||||
|
|
||||||
|
If *Chunk\UploadId < 1 Or *Chunk\ChunkIndex < 0 Or *Chunk\ChunkIndex > #BakaShrot_MaxAttachmentChunks Or Not *Chunk\Data Or *Chunk\DataSize < 1 Or *Chunk\DataSize > #BakaShrot_AttachmentChunkSize
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
*MsgPackData = MsgPackCreate(#BakaShrot_AttachmentChunkSize + 256)
|
||||||
|
If Not *MsgPackData
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If Not BakaShrot_WritePacketBase(*Chunk, *MsgPackData)
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If MsgPackWriteInteger(*MsgPackData, *Chunk\UploadId) <> #MsgPack_Error_Success
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If MsgPackWriteInteger(*MsgPackData, *Chunk\ChunkIndex) <> #MsgPack_Error_Success
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If MsgPackWriteBinary(*MsgPackData, *Chunk\Data, *Chunk\DataSize) <> #MsgPack_Error_Success
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; Frees *MsgPackData on success, leaves it untouched on failure.
|
||||||
|
*Buffer = MsgPackFinalize(*MsgPackData)
|
||||||
|
If Not *Buffer
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
*OutSize\i = MemorySize(*Buffer)
|
||||||
|
ProcedureReturn *Buffer
|
||||||
|
|
||||||
|
EncodeFailed:
|
||||||
|
MsgPackFree(*MsgPackData, #True)
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
; Frees a decoded *Chunk and the data it holds.
|
||||||
|
Procedure BakaShrot_UploadChunkPacket_Free(*Chunk.BakaShrot_UploadChunk)
|
||||||
|
If Not *Chunk
|
||||||
|
ProcedureReturn
|
||||||
|
EndIf
|
||||||
|
If *Chunk\Data
|
||||||
|
FreeMemory(*Chunk\Data)
|
||||||
|
EndIf
|
||||||
|
FreeStructure(*Chunk)
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
|
||||||
|
; *MsgPackData stays owned by the caller, and should be discarded on failure.
|
||||||
|
; Returns 0 on failure, the caller owns the returned struct - free it with BakaShrot_UploadChunkPacket_Free().
|
||||||
|
Procedure.i BakaShrot_UploadChunkPacket_Decode(*MsgPackData.MsgPackData)
|
||||||
|
Protected *Chunk.BakaShrot_UploadChunk, Value.q
|
||||||
|
|
||||||
|
*Chunk = AllocateStructure(BakaShrot_UploadChunk)
|
||||||
|
If Not *Chunk
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; The base parser doesn't check which packet it is, that's on us.
|
||||||
|
If Not BakaShrot_ReadPacketBase(*Chunk, *MsgPackData) Or *Chunk\PacketType <> #BakaShrot_PacketType_UploadChunk
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; UploadId
|
||||||
|
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
Value = MsgPackReadInteger(*MsgPackData)
|
||||||
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 1
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
*Chunk\UploadId = Value
|
||||||
|
|
||||||
|
; ChunkIndex
|
||||||
|
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
Value = MsgPackReadInteger(*MsgPackData)
|
||||||
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > #BakaShrot_MaxAttachmentChunks
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
*Chunk\ChunkIndex = Value
|
||||||
|
|
||||||
|
; Data
|
||||||
|
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
; A copy, freed with the packet (_Free()).
|
||||||
|
*Chunk\Data = MsgPackCopyBinary(*MsgPackData)
|
||||||
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not *Chunk\Data
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
*Chunk\DataSize = MemorySize(*Chunk\Data)
|
||||||
|
If *Chunk\DataSize > #BakaShrot_AttachmentChunkSize
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
ProcedureReturn *Chunk
|
||||||
|
|
||||||
|
; Everything read so far is tainted, drop it.
|
||||||
|
DecodeFailed:
|
||||||
|
BakaShrot_UploadChunkPacket_Free(*Chunk)
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndProcedure
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
; ============================================================================
|
||||||
|
; ...
|
||||||
|
; ============================================================================
|
||||||
|
|
||||||
|
|
||||||
|
XIncludeFile "../Packets.pbi"
|
||||||
|
|
||||||
|
; C2S, starts uploading an attachment, before pushing the message it goes with
|
||||||
|
; (PushMessage's UploadId): Size bytes (1 to #BakaShrot_MaxAttachmentSize, and the
|
||||||
|
; server's [BakaShrot.Server] MaxAttachmentSize), whose SHA-256 is Sha256.
|
||||||
|
; Topic: where the message will be pushed, as PushMessage's: "" for the client's
|
||||||
|
; own. The client's PushTopics must allow it.
|
||||||
|
; Answered with an UploadStarted, or a RequestRefused.
|
||||||
|
Structure BakaShrot_UploadStart Extends BakaShrot_PacketBase
|
||||||
|
Topic.s
|
||||||
|
Size.q
|
||||||
|
Sha256.a[#BakaShrot_Sha256Size]
|
||||||
|
EndStructure
|
||||||
|
|
||||||
|
|
||||||
|
; Encodes *Start into a freshly allocated buffer, its base fields are set by this procedure.
|
||||||
|
; *OutSize receives its size in bytes.
|
||||||
|
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
|
||||||
|
Procedure.i BakaShrot_UploadStartPacket_Encode(*Start.BakaShrot_UploadStart, *OutSize.Integer)
|
||||||
|
Protected *MsgPackData.MsgPackData, *Buffer
|
||||||
|
|
||||||
|
*Start\Magic = #BakaShrot_ProtocolMagic
|
||||||
|
*Start\Version = #BakaShrot_ProtocolVersion
|
||||||
|
*Start\PacketType = #BakaShrot_PacketType_UploadStart
|
||||||
|
|
||||||
|
If *Start\Size < 1 Or *Start\Size > #BakaShrot_MaxAttachmentSize
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
*MsgPackData = MsgPackCreate(64)
|
||||||
|
If Not *MsgPackData
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If Not BakaShrot_WritePacketBase(*Start, *MsgPackData)
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If MsgPackWriteString(*MsgPackData, *Start\Topic) <> #MsgPack_Error_Success
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If MsgPackWriteInteger(*MsgPackData, *Start\Size) <> #MsgPack_Error_Success
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If MsgPackWriteBinary(*MsgPackData, @*Start\Sha256[0], #BakaShrot_Sha256Size) <> #MsgPack_Error_Success
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; Frees *MsgPackData on success, leaves it untouched on failure.
|
||||||
|
*Buffer = MsgPackFinalize(*MsgPackData)
|
||||||
|
If Not *Buffer
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
*OutSize\i = MemorySize(*Buffer)
|
||||||
|
ProcedureReturn *Buffer
|
||||||
|
|
||||||
|
EncodeFailed:
|
||||||
|
MsgPackFree(*MsgPackData, #True)
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
|
||||||
|
; *MsgPackData stays owned by the caller, and should be discarded on failure.
|
||||||
|
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
|
||||||
|
Procedure.i BakaShrot_UploadStartPacket_Decode(*MsgPackData.MsgPackData)
|
||||||
|
Protected *Start.BakaShrot_UploadStart, Value.q, ReadSize.q
|
||||||
|
|
||||||
|
*Start = AllocateStructure(BakaShrot_UploadStart)
|
||||||
|
If Not *Start
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; The base parser doesn't check which packet it is, that's on us.
|
||||||
|
If Not BakaShrot_ReadPacketBase(*Start, *MsgPackData) Or *Start\PacketType <> #BakaShrot_PacketType_UploadStart
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; Topic
|
||||||
|
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
*Start\Topic = MsgPackReadString(*MsgPackData)
|
||||||
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; Size
|
||||||
|
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
Value = MsgPackReadInteger(*MsgPackData)
|
||||||
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 1 Or Value > #BakaShrot_MaxAttachmentSize
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
*Start\Size = Value
|
||||||
|
|
||||||
|
; Sha256
|
||||||
|
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
; Anything bigger than the struct's array is rejected by MsgPackReadBinary, anything smaller by the size check.
|
||||||
|
ReadSize = MsgPackReadBinary(*MsgPackData, @*Start\Sha256[0], #BakaShrot_Sha256Size)
|
||||||
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or ReadSize <> #BakaShrot_Sha256Size
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
ProcedureReturn *Start
|
||||||
|
|
||||||
|
; Everything read so far is tainted, drop it.
|
||||||
|
DecodeFailed:
|
||||||
|
FreeStructure(*Start)
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndProcedure
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
; ============================================================================
|
||||||
|
; ...
|
||||||
|
; ============================================================================
|
||||||
|
|
||||||
|
|
||||||
|
XIncludeFile "../Packets.pbi"
|
||||||
|
|
||||||
|
; S2C, answers an UploadStart: send the data with UploadChunks for UploadId, in
|
||||||
|
; order, ChunkSize bytes each (the last one what's left).
|
||||||
|
Structure BakaShrot_UploadStarted Extends BakaShrot_PacketBase
|
||||||
|
UploadId.q
|
||||||
|
ChunkSize.l
|
||||||
|
EndStructure
|
||||||
|
|
||||||
|
|
||||||
|
; Encodes *Started into a freshly allocated buffer, its base fields are set by this procedure.
|
||||||
|
; *OutSize receives its size in bytes.
|
||||||
|
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
|
||||||
|
Procedure.i BakaShrot_UploadStartedPacket_Encode(*Started.BakaShrot_UploadStarted, *OutSize.Integer)
|
||||||
|
Protected *MsgPackData.MsgPackData, *Buffer
|
||||||
|
|
||||||
|
*Started\Magic = #BakaShrot_ProtocolMagic
|
||||||
|
*Started\Version = #BakaShrot_ProtocolVersion
|
||||||
|
*Started\PacketType = #BakaShrot_PacketType_UploadStarted
|
||||||
|
|
||||||
|
If *Started\UploadId < 1 Or *Started\ChunkSize < 1 Or *Started\ChunkSize > #BakaShrot_AttachmentChunkSize
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
*MsgPackData = MsgPackCreate(64)
|
||||||
|
If Not *MsgPackData
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If Not BakaShrot_WritePacketBase(*Started, *MsgPackData)
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If MsgPackWriteInteger(*MsgPackData, *Started\UploadId) <> #MsgPack_Error_Success
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If MsgPackWriteInteger(*MsgPackData, *Started\ChunkSize) <> #MsgPack_Error_Success
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; Frees *MsgPackData on success, leaves it untouched on failure.
|
||||||
|
*Buffer = MsgPackFinalize(*MsgPackData)
|
||||||
|
If Not *Buffer
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
*OutSize\i = MemorySize(*Buffer)
|
||||||
|
ProcedureReturn *Buffer
|
||||||
|
|
||||||
|
EncodeFailed:
|
||||||
|
MsgPackFree(*MsgPackData, #True)
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
|
||||||
|
; *MsgPackData stays owned by the caller, and should be discarded on failure.
|
||||||
|
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
|
||||||
|
Procedure.i BakaShrot_UploadStartedPacket_Decode(*MsgPackData.MsgPackData)
|
||||||
|
Protected *Started.BakaShrot_UploadStarted, Value.q
|
||||||
|
|
||||||
|
*Started = AllocateStructure(BakaShrot_UploadStarted)
|
||||||
|
If Not *Started
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; The base parser doesn't check which packet it is, that's on us.
|
||||||
|
If Not BakaShrot_ReadPacketBase(*Started, *MsgPackData) Or *Started\PacketType <> #BakaShrot_PacketType_UploadStarted
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; UploadId
|
||||||
|
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
Value = MsgPackReadInteger(*MsgPackData)
|
||||||
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 1
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
*Started\UploadId = Value
|
||||||
|
|
||||||
|
; ChunkSize
|
||||||
|
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
Value = MsgPackReadInteger(*MsgPackData)
|
||||||
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 1 Or Value > #BakaShrot_AttachmentChunkSize
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
*Started\ChunkSize = Value
|
||||||
|
|
||||||
|
ProcedureReturn *Started
|
||||||
|
|
||||||
|
; Everything read so far is tainted, drop it.
|
||||||
|
DecodeFailed:
|
||||||
|
FreeStructure(*Started)
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndProcedure
|
||||||
@@ -0,0 +1,162 @@
|
|||||||
|
# Attachments
|
||||||
|
|
||||||
|
A message can have **one attachment**: any bytes (a file, a photo, a dump),
|
||||||
|
of any size up to the server's `MaxAttachmentSize` (default 1 GB, at most
|
||||||
|
1 TB). Most messages have none. The message's JSON can say what it is: the
|
||||||
|
attachment itself has no name or type, only its size and SHA-256.
|
||||||
|
|
||||||
|
Protocol version 4. Code: `Server/Storage/Attachments.pbi` (storage),
|
||||||
|
`Server/Networking/Networking.pbi` (requests), `Server/Networking/Peers.pbi`
|
||||||
|
(replication), `Client/BakaShrot_Client.pbi` (DLL).
|
||||||
|
|
||||||
|
## The rules
|
||||||
|
|
||||||
|
- **Sent and stored in parts** of 1 MB (`#BakaShrot_AttachmentChunkSize`, the
|
||||||
|
last one what's left), one request each: neither end ever holds a whole
|
||||||
|
attachment in memory (a 512 MB one: the server peaked at 15 MB).
|
||||||
|
- **Checked with its SHA-256**, given before the first part: the server
|
||||||
|
checks it once all parts are in (uploads and replicated ones alike), the
|
||||||
|
client when it reads one back.
|
||||||
|
- **A message is only stored once all of its attachment is.** The client
|
||||||
|
uploads it first, then pushes the message with the upload's id: readers
|
||||||
|
never see a message whose attachment is missing on the server it was
|
||||||
|
pushed to. Messages stay immutable.
|
||||||
|
- **Replicated after the messages**, separately: a peer gets the message
|
||||||
|
first (with the attachment's size and SHA-256), then its data once the
|
||||||
|
messages are caught up. So on the other servers, a message can be there
|
||||||
|
before its attachment: `AttachmentReady` tells.
|
||||||
|
- **Deleted with its message** (the retention): its parts go a few at a
|
||||||
|
time, in the background.
|
||||||
|
|
||||||
|
## Pushing one
|
||||||
|
|
||||||
|
```
|
||||||
|
C -> S UploadStart(topic, size, sha256) same permissions as pushing to that
|
||||||
|
topic, size <= MaxAttachmentSize
|
||||||
|
S -> C UploadStarted(upload id, 1 MB)
|
||||||
|
C -> S UploadChunk(upload id, 0, data) in order, each the right size
|
||||||
|
S -> C ChunkStored(received, complete 0)
|
||||||
|
...
|
||||||
|
C -> S UploadChunk(upload id, last, data)
|
||||||
|
server: reads all of it back, checks the SHA-256 (or drops it, refused)
|
||||||
|
S -> C ChunkStored(received = size, complete 1)
|
||||||
|
C -> S PushMessage(topic, json, upload id)
|
||||||
|
server: the upload must be this client's (its node), for that topic,
|
||||||
|
complete: the message and its attachment are stored together
|
||||||
|
S -> C MessagePushed(id)
|
||||||
|
```
|
||||||
|
|
||||||
|
- An upload belongs to the client's node and the topic it was started for.
|
||||||
|
- One not pushed within `UploadTimeout` seconds (default 3600) is deleted.
|
||||||
|
- A refused part doesn't drop the upload; a SHA-256 mismatch does.
|
||||||
|
- The DLL does all of it in `BakaShrot_PushMessageWithFile()` /
|
||||||
|
`_WithData()`; it reads a file twice (the SHA-256 first).
|
||||||
|
|
||||||
|
## Reading one
|
||||||
|
|
||||||
|
```
|
||||||
|
C -> S GetAttachment(topic, node, message id, part) same permissions as reading
|
||||||
|
S -> C AttachmentChunk(ids, message id, size, sha256, part, data)
|
||||||
|
```
|
||||||
|
|
||||||
|
Any part, in any order (the DLL reads them in order). Refused if the
|
||||||
|
message has none, or if it isn't all on this server yet (replicated after
|
||||||
|
its message), or isn't kept here (bigger than this server's
|
||||||
|
`MaxAttachmentSize`).
|
||||||
|
|
||||||
|
## Replicating
|
||||||
|
|
||||||
|
On its link to a peer, at every check-in, once the messages are sent
|
||||||
|
(`Design/Packets.md`, Replication):
|
||||||
|
|
||||||
|
```
|
||||||
|
P -> S MissingAttachmentsRequest
|
||||||
|
S -> P MissingAttachments([(topic, node, message id, next part)])
|
||||||
|
up to 256 attachments of messages S has,
|
||||||
|
from what it takes from P, not all here
|
||||||
|
P: for each one it has, all of it, and sends S (SendTopics/SendNodes):
|
||||||
|
P -> S ReplicateAttachmentChunk(topic, node, message id, part, data)
|
||||||
|
S -> P ChunkStored(received, complete)
|
||||||
|
... from the part S asked for: resumes after a dropped link
|
||||||
|
S: once all of it is in, checks the SHA-256 its message came with:
|
||||||
|
ready, or dropped and asked for again from the start
|
||||||
|
```
|
||||||
|
|
||||||
|
- A server relays what it has: an attachment that isn't on P either is
|
||||||
|
skipped, S asks again at the next check-in, maybe of another peer.
|
||||||
|
- An attachment bigger than S's `MaxAttachmentSize` is marked not kept
|
||||||
|
when its message arrives: S never asks for it.
|
||||||
|
- A message skipped on arrival (past S's max age) has no attachment row:
|
||||||
|
never asked for either.
|
||||||
|
|
||||||
|
## Storage (schema v7, `db_schema_v7.dbml`)
|
||||||
|
|
||||||
|
| Table | What |
|
||||||
|
|---|---|
|
||||||
|
| `attachments` | A message's: size, SHA-256, its blob once any of it is here, state: 0 missing, 1 receiving, 2 ready, 3 not kept. |
|
||||||
|
| `blobs` | The data of one attachment: whose (topic, node), size, SHA-256, bytes received, state: 0 receiving, 1 complete (an upload waiting for its message), 2 attached, 3 to delete. |
|
||||||
|
| `blob_chunks` | Its parts, 1 MB each, by (blob, index). |
|
||||||
|
|
||||||
|
- Triggers: deleting a message deletes its `attachments` row, which marks
|
||||||
|
its blob to delete. The retention thread (`Retention.pbi`) deletes those
|
||||||
|
parts 32 at a time, along with uploads past `UploadTimeout`, every
|
||||||
|
`RetentionInterval` seconds, retention rules or not.
|
||||||
|
- Parts are written through the writer (each one its own transaction), read
|
||||||
|
on each thread's own connection.
|
||||||
|
- SQLite reuses the freed pages; `vacuum` gives the space back to the disk.
|
||||||
|
|
||||||
|
## In the clients
|
||||||
|
|
||||||
|
| | DLL | Python | Tools |
|
||||||
|
|---|---|---|---|
|
||||||
|
| Push with one | `BakaShrot_PushMessageWithFile(Topic, Json, Path)`, `_WithData(Topic, Json, *Data, Size)` | `push(data, topic, attachment=bytes or path)` | `PushMessage -a <File>` |
|
||||||
|
| Does a message have one | `BakaShrot_GetMessageAttachmentSize()`, `BakaShrot_IsMessageAttachmentReady()` | `Message.attachment_size`, `.attachment_ready` | `GetLatestMessage` prints it |
|
||||||
|
| Read one | `BakaShrot_SaveAttachment(Topic, Node, Id, Path)`, `_LoadAttachment()` + `_GetAttachmentData()` | `save_attachment()`, `get_attachment()` | `GetAttachment <Topic> <Node> <Id> <OutFile>` |
|
||||||
|
|
||||||
|
## Speed
|
||||||
|
|
||||||
|
On one machine (i5-13500, localhost, PB 5.73): 5 MB up in ~80 ms and down
|
||||||
|
in ~65 ms through the tools; 512 MB up in 8.5 s (SHA-256 on both ends
|
||||||
|
included) and down in 3.9 s. One part per round trip: over a slow link,
|
||||||
|
latency adds up (1000 round trips per GB).
|
||||||
|
|
||||||
|
## Tested
|
||||||
|
|
||||||
|
- `Tests/Attachments-Test.ps1` (39 checks, two servers, ports 12410-12411):
|
||||||
|
one part, several, an exact multiple, one byte; none; replicated
|
||||||
|
identical; not kept past the other server's limit; too big to push;
|
||||||
|
deleted with its message, parts included.
|
||||||
|
- `Tests/AttachmentEdges-Test.ps1` (51 checks, ports 12413-12414), with a
|
||||||
|
raw protocol client (`Tests/AttachmentEdgeClient.pb`) for what the DLL
|
||||||
|
never sends:
|
||||||
|
- a wrong SHA-256: refused at the last part, the upload dropped, pushing
|
||||||
|
with it refused;
|
||||||
|
- parts out of order, of the wrong size, repeated, past the end, from
|
||||||
|
another client: refused, the upload goes on;
|
||||||
|
- someone else's upload, the wrong topic, attached twice, an unknown id,
|
||||||
|
too big, a topic the client may not push to or read: refused, the
|
||||||
|
connection stays up;
|
||||||
|
- uploads left behind (half sent, complete but never pushed): kept within
|
||||||
|
`UploadTimeout`, deleted past it (10.7 s for 10), then refused;
|
||||||
|
- replication resuming: the receiver killed at ~45 MB of 400 MB,
|
||||||
|
restarted: what it had committed is still there, the sender goes on
|
||||||
|
from that part, the result is identical;
|
||||||
|
- a byte flipped in the sender's database: the client refuses it
|
||||||
|
(SHA-256), the peer drops it, serves nothing, and asks again.
|
||||||
|
- `check_bakashrot.py` (Python): bytes and files, round trips, refusals.
|
||||||
|
|
||||||
|
## Not done
|
||||||
|
|
||||||
|
- **Resuming an upload** after a dropped connection: the parts are kept
|
||||||
|
until `UploadTimeout`, but the DLL starts over. (Replication resumes.)
|
||||||
|
- **Several parts in flight**, for links with high latency.
|
||||||
|
- **A corrupted copy is sent again and again.** If a server's own stored
|
||||||
|
copy is damaged (disk, a bug), its peers drop it at every check-in and
|
||||||
|
ask again: the whole attachment is re-sent every `PeerSyncInterval`
|
||||||
|
(6 times in 6 s in the test). The server itself never notices, it serves
|
||||||
|
the damaged parts to clients too (they refuse them, by their SHA-256).
|
||||||
|
Fix: when a peer answers "doesn't match", the sender checks its own copy
|
||||||
|
(`HashStorageBlob()`); if it's damaged, it marks it missing, so it gets a
|
||||||
|
good one back from another peer, and stops sending it. Details, and how
|
||||||
|
the test should change: `Notes.md`, open item 3.
|
||||||
|
- **No deduplication**: the same file attached twice is stored twice.
|
||||||
+31
-9
@@ -20,13 +20,17 @@ Reference for working on BakaShrot's networking. Related docs:
|
|||||||
| Sealed Hello, key exchange; encrypting a buffer | `Commons/Cryptography/Session.pbi`, `Commons/Cryptography/Cipher.pbi` |
|
| Sealed Hello, key exchange; encrypting a buffer | `Commons/Cryptography/Session.pbi`, `Commons/Cryptography/Cipher.pbi` |
|
||||||
| Client side of the handshake, on any connection | `Commons/Networking/Outbound.pbi` |
|
| Client side of the handshake, on any connection | `Commons/Networking/Outbound.pbi` |
|
||||||
| Server: listener, one thread per client, request handlers | `Server/Networking/Networking.pbi` |
|
| Server: listener, one thread per client, request handlers | `Server/Networking/Networking.pbi` |
|
||||||
| Server: links to peers, check-ins, sending missing messages | `Server/Networking/Peers.pbi` |
|
| Server: links to peers, check-ins, sending missing messages and attachments | `Server/Networking/Peers.pbi` |
|
||||||
|
| Server: storing messages (the writer), attachments, deleting old ones | `Server/Storage/Writer.pbi`, `Attachments.pbi`, `Retention.pbi` |
|
||||||
|
| Server: its config, and the example one | `Server/Config/Config.pbi`, `Server/Config/schema.ini` |
|
||||||
| Server: the root thread, which stops and starts every worker (restart, vacuum) | `Server/Root.pbi` |
|
| Server: the root thread, which stops and starts every worker (restart, vacuum) | `Server/Root.pbi` |
|
||||||
| Client DLL (one connection) | `Client/BakaShrot_Client.pbi`, used through `BakaShrot_Client_Prototypes.pbi` |
|
| Client DLL (one connection) | `Client/BakaShrot_Client.pbi`, used through `BakaShrot_Client_Prototypes.pbi` |
|
||||||
| Python client, over the DLL | `Interactors/Python/bakashrot.py` |
|
| Python client, over the DLL | `Interactors/Python/bakashrot.py` |
|
||||||
| Tests of the packets alone, without sockets | `Tests/HandshakeTest.pb` |
|
| Tests of the packets alone, without sockets | `Tests/HandshakeTest.pb` |
|
||||||
| Tests of the cipher and the session crypto, without sockets | `Tests/CipherTest.pb` |
|
| Tests of the cipher and the session crypto, without sockets | `Tests/CipherTest.pb` |
|
||||||
| What goes over the wire (a recording proxy) | `Tests/wire_check.py`, run by `Tests/Python-Test.ps1` |
|
| What goes over the wire (a recording proxy) | `Tests/wire_check.py`, run by `Tests/Python-Test.ps1` |
|
||||||
|
| A raw protocol client, for what the DLL never sends | `Tests/AttachmentEdgeClient.pb`, run by `Tests/AttachmentEdges-Test.ps1` |
|
||||||
|
| Every end-to-end suite | `Tests/*.ps1`, listed in `CLAUDE.md` |
|
||||||
|
|
||||||
## Transport and framing
|
## Transport and framing
|
||||||
|
|
||||||
@@ -70,10 +74,10 @@ Reference for working on BakaShrot's networking. Related docs:
|
|||||||
array, read in order with PB-MessagePack:
|
array, read in order with PB-MessagePack:
|
||||||
1. `Magic` (integer), always `#BakaShrot_ProtocolMagic` (`0x42534854`,
|
1. `Magic` (integer), always `#BakaShrot_ProtocolMagic` (`0x42534854`,
|
||||||
"BSHT").
|
"BSHT").
|
||||||
2. `Version` (integer), always `#BakaShrot_ProtocolVersion` (3: the
|
2. `Version` (integer), always `#BakaShrot_ProtocolVersion` (4:
|
||||||
Hello sealed, a key per connection, everything after the
|
attachments; 3: the Hello sealed, a key per connection, everything
|
||||||
ChallengeRequest encrypted; 2 had topics and nodes by name, in plain
|
after the ChallengeRequest encrypted, times; 2 had topics and nodes by
|
||||||
text; 1 had ids only).
|
name, in plain text; 1 had ids only).
|
||||||
3. `PacketType` (integer), one of the ids below.
|
3. `PacketType` (integer), one of the ids below.
|
||||||
4. The packet's own fields, in the order listed.
|
4. The packet's own fields, in the order listed.
|
||||||
- **Encodings:** strings are UTF-8 MessagePack strings, the nonce a
|
- **Encodings:** strings are UTF-8 MessagePack strings, the nonce a
|
||||||
@@ -119,14 +123,14 @@ over its own link to another server.
|
|||||||
| 5 | ChallengeRequest | S→C | `ChallengeB64` str (32 bytes), `Nonce` bin (32 bytes), `ServerSessionKey` bin (32 bytes), `ServerSignature` bin (64 bytes, of the transcript). The last packet in plain text | ChallengeResponse |
|
| 5 | ChallengeRequest | S→C | `ChallengeB64` str (32 bytes), `Nonce` bin (32 bytes), `ServerSessionKey` bin (32 bytes), `ServerSignature` bin (64 bytes, of the transcript). The last packet in plain text | ChallengeResponse |
|
||||||
| 6 | ChallengeResponse | C→S | `ChallengeResponseB64` str (64-byte signature of the transcript), `Nonce` bin (32 bytes) | AuthAccepted |
|
| 6 | ChallengeResponse | C→S | `ChallengeResponseB64` str (64-byte signature of the transcript), `Nonce` bin (32 bytes) | AuthAccepted |
|
||||||
| 7 | AuthAccepted | S→C | None. | |
|
| 7 | AuthAccepted | S→C | None. | |
|
||||||
| 8 | PushMessage | C→S | `Topic` str (ref, "" for the client's own), `JsonData` str | MessagePushed / RequestRefused |
|
| 8 | PushMessage | C→S | `Topic` str (ref, "" for the client's own), `JsonData` str, `UploadId` int (its attachment, 0 for none) | MessagePushed / RequestRefused |
|
||||||
| 9 | MessagePushed | S→C | `MessageId` int ≥ 1 | |
|
| 9 | MessagePushed | S→C | `MessageId` int ≥ 1 | |
|
||||||
| 10 | GetLatestMessage | C→S | `Topic` str (ref), `Node` str (ref) | LatestMessage / RequestRefused |
|
| 10 | GetLatestMessage | C→S | `Topic` str (ref), `Node` str (ref) | LatestMessage / RequestRefused |
|
||||||
| 11 | LatestMessage | S→C | `TopicId`, `NodeId` int 0-65535 (the server's), `TopicName`, `NodeName` str (names, or ids in digits), `MessageId` int ≥ 1, `PushedAt` int (time, see below), `JsonData` str | |
|
| 11 | LatestMessage | S→C | `TopicId`, `NodeId` int 0-65535 (the server's), `TopicName`, `NodeName` str (names, or ids in digits), `MessageId` int ≥ 1, `PushedAt` int (time, see below), `JsonData` str, `AttachmentSize` int (0 for none), `AttachmentReady` int 0/1 | |
|
||||||
| 12 | RequestRefused | S→C | `Reason` str, for logs and humans | |
|
| 12 | RequestRefused | S→C | `Reason` str, for logs and humans | |
|
||||||
| 13 | SyncStateRequest | P→S | None. | SyncState / RequestRefused |
|
| 13 | SyncStateRequest | P→S | None. | SyncState / RequestRefused |
|
||||||
| 14 | SyncState | S→P | `TopicCount` int, then each topic's `Id` int and `Name` str (the named topics S takes from P); `NodeCount` int, then each node's `Id` and `Name` (the named nodes S takes from P); `TopicPatternCount` int, then each pattern str; `NodePatternCount` int, then each pattern str (S's wildcards for P, `*` included); `PairCount` int, then each pair's `TopicId`, `NodeId`, `MessageId`. Ids are S's own, names are never digits | |
|
| 14 | SyncState | S→P | `TopicCount` int, then each topic's `Id` int and `Name` str (the named topics S takes from P); `NodeCount` int, then each node's `Id` and `Name` (the named nodes S takes from P); `TopicPatternCount` int, then each pattern str; `NodePatternCount` int, then each pattern str (S's wildcards for P, `*` included); `PairCount` int, then each pair's `TopicId`, `NodeId`, `MessageId`. Ids are S's own, names are never digits | |
|
||||||
| 15 | ReplicateMessages | P→S | `Topic` str, `Node` str (names, never digits), `Count` int 1-10000, then each message's `MessageId` int (≥ 1, strictly increasing), `PushedAt` int (as stored, from its origin) and `JsonData` str | MessagePushed (last id) / RequestRefused |
|
| 15 | ReplicateMessages | P→S | `Topic` str, `Node` str (names, never digits), `Count` int 1-10000, then each message's `MessageId` int (≥ 1, strictly increasing), `PushedAt` int (as stored, from its origin), `JsonData` str, `AttachmentSize` int (0 for none) and `AttachmentSha256` bin (32 bytes, empty for none) | MessagePushed (last id) / RequestRefused |
|
||||||
| 16 | QueryRequest | C→S | `Sql` str | QueryResult / RequestRefused |
|
| 16 | QueryRequest | C→S | `Sql` str | QueryResult / RequestRefused |
|
||||||
| 17 | QueryResult | S→C | `JsonResult` str: `{"columns":[...],"rows":[[...],...]}`, every value a string or null | |
|
| 17 | QueryResult | S→C | `JsonResult` str: `{"columns":[...],"rows":[[...],...]}`, every value a string or null | |
|
||||||
| 18 | ResolveName | C→S | `Kind` int (1 topic, 2 node), `Ref` str | NameResolved / RequestRefused |
|
| 18 | ResolveName | C→S | `Kind` int (1 topic, 2 node), `Ref` str | NameResolved / RequestRefused |
|
||||||
@@ -134,7 +138,20 @@ over its own link to another server.
|
|||||||
| 20 | ListNames | C→S | `Kind` int (1 topics, 2 nodes) | NamesList |
|
| 20 | ListNames | C→S | `Kind` int (1 topics, 2 nodes) | NamesList |
|
||||||
| 21 | NamesList | S→C | `Kind` int, `Truncated` int 0/1, `Count` int, then each entry's `Id` int, `Name` str ("" if unnamed), `Origin` str ("config", "id") | |
|
| 21 | NamesList | S→C | `Kind` int, `Truncated` int 0/1, `Count` int, then each entry's `Id` int, `Name` str ("" if unnamed), `Origin` str ("config", "id") | |
|
||||||
| 22 | GetMessages | C→S | `Topic` str (ref), `Node` str (ref), `AfterMessageId` int ≥ 0, `Limit` int 1-10000 | Messages / RequestRefused |
|
| 22 | GetMessages | C→S | `Topic` str (ref), `Node` str (ref), `AfterMessageId` int ≥ 0, `Limit` int 1-10000 | Messages / RequestRefused |
|
||||||
| 23 | Messages | S→C | `TopicId`, `NodeId` int 0-65535 (the server's), `TopicName`, `NodeName` str (names, or ids in digits), `More` int 0/1, `Count` int 0-10000, then each message's `MessageId` int (≥ 1, strictly increasing, above `AfterMessageId`), `PushedAt` int and `JsonData` str | |
|
| 23 | Messages | S→C | `TopicId`, `NodeId` int 0-65535 (the server's), `TopicName`, `NodeName` str (names, or ids in digits), `More` int 0/1, `Count` int 0-10000, then each message's `MessageId` int (≥ 1, strictly increasing, above `AfterMessageId`), `PushedAt` int, `JsonData` str, `AttachmentSize` int (0 for none) and `AttachmentReady` int 0/1 | |
|
||||||
|
| 24 | UploadStart | C→S | `Topic` str (ref, "" for the client's own), `Size` int 1-MaxAttachmentSize, `Sha256` bin (32 bytes) | UploadStarted / RequestRefused |
|
||||||
|
| 25 | UploadStarted | S→C | `UploadId` int ≥ 1, `ChunkSize` int (1 MB) | |
|
||||||
|
| 26 | UploadChunk | C→S | `UploadId` int, `ChunkIndex` int ≥ 0 (the next one), `Data` bin (1 MB, the last one what's left) | ChunkStored / RequestRefused |
|
||||||
|
| 27 | ChunkStored | S→C, S→P | `Received` int (bytes so far), `Complete` int 0/1 (all of it, SHA-256 checked) | |
|
||||||
|
| 28 | GetAttachment | C→S | `Topic`, `Node` str (refs), `MessageId` int ≥ 1, `ChunkIndex` int ≥ 0 | AttachmentChunk / RequestRefused |
|
||||||
|
| 29 | AttachmentChunk | S→C | `TopicId`, `NodeId` int (the server's), `MessageId` int, `Size` int, `Sha256` bin (32 bytes), `ChunkIndex` int, `Data` bin | |
|
||||||
|
| 30 | MissingAttachmentsRequest | P→S | None. | MissingAttachments / RequestRefused |
|
||||||
|
| 31 | MissingAttachments | S→P | `Count` int 0-256, then each one's `Topic`, `Node` str (names), `MessageId` int, `NextChunk` int | |
|
||||||
|
| 32 | ReplicateAttachmentChunk | P→S | `Topic`, `Node` str (names), `MessageId` int, `ChunkIndex` int (the next one), `Data` bin | ChunkStored / RequestRefused |
|
||||||
|
|
||||||
|
**Attachments** (24-32, and the attachment fields): see
|
||||||
|
`Design/Attachments.md`. At most one per message, in parts of 1 MB, checked
|
||||||
|
with their SHA-256, replicated after their message.
|
||||||
|
|
||||||
**Times** (`PushedAt`): milliseconds since 1970-01-01 00:00:00 UTC, 1 to
|
**Times** (`PushedAt`): milliseconds since 1970-01-01 00:00:00 UTC, 1 to
|
||||||
`#BakaShrot_MaxTimestamp` (9999-12-31), anything else aborts. A message is
|
`#BakaShrot_MaxTimestamp` (9999-12-31), anything else aborts. A message is
|
||||||
@@ -267,6 +284,11 @@ P -> S ReplicateMessages the topic and node names, the next missing messages
|
|||||||
S -> P MessagePushed(id) the batch stored in one transaction with
|
S -> P MessagePushed(id) the batch stored in one transaction with
|
||||||
INSERT OR IGNORE, the last id echoed
|
INSERT OR IGNORE, the last id echoed
|
||||||
... until caught up, or the first refusal for that pair
|
... until caught up, or the first refusal for that pair
|
||||||
|
then the attachments of the messages S now has:
|
||||||
|
P -> S MissingAttachmentsRequest
|
||||||
|
S -> P MissingAttachments what S lacks, among what it takes from P
|
||||||
|
P -> S ReplicateAttachmentChunk ... -> S -> P ChunkStored, per part
|
||||||
|
(Design/Attachments.md)
|
||||||
```
|
```
|
||||||
|
|
||||||
- **Batch size:** `PeerBatchSize` is set on the sending side, in
|
- **Batch size:** `PeerBatchSize` is set on the sending side, in
|
||||||
|
|||||||
+7
-4
@@ -24,11 +24,14 @@ database:
|
|||||||
view with `is_json = 1`;
|
view with `is_json = 1`;
|
||||||
- if `python` is on the PATH, reads them and pushes one with
|
- if `python` is on the PATH, reads them and pushes one with
|
||||||
`python\bakashrot.py`;
|
`python\bakashrot.py`;
|
||||||
|
- pushes a 3 MB attachment with `PushMessage.exe -a` and reads it back
|
||||||
|
identical with `GetAttachment.exe`;
|
||||||
- then force-kills the server and deletes everything.
|
- then force-kills the server and deletes everything.
|
||||||
|
|
||||||
The end-to-end tests in `Tests/` cover much more (names, replication, big
|
The end-to-end tests in `Tests/` cover much more (names, replication, big
|
||||||
messages, GetMessages, the Python client), but against `Build\` (PB 5.73)
|
messages, GetMessages, the Python client, retention, attachments and their
|
||||||
and `BenchServer.exe`, not the release.
|
edge cases), but against `Build\` (PB 5.73) and `BenchServer.exe`, not the
|
||||||
|
release. The list is in `CLAUDE.md`.
|
||||||
|
|
||||||
## Fixed: the release needed the Visual C++ runtime
|
## Fixed: the release needed the Visual C++ runtime
|
||||||
|
|
||||||
@@ -110,7 +113,7 @@ in `Tests/` already, to be pointed at the release instead.
|
|||||||
10. **Version hygiene**:
|
10. **Version hygiene**:
|
||||||
- `-Version 1.0.0` refuses a dirty tree instead of appending `-dirty`;
|
- `-Version 1.0.0` refuses a dirty tree instead of appending `-dirty`;
|
||||||
- the release commit is tagged (`v1.0.0`), the version comes from it;
|
- the release commit is tagged (`v1.0.0`), the version comes from it;
|
||||||
- `VERSION.txt` gives the protocol version (3) and the runtime needed;
|
- `VERSION.txt` gives the protocol version (4) and the runtime needed;
|
||||||
- the Python client is checked on the oldest version it claims (3.8),
|
- the Python client is checked on the oldest version it claims (3.8),
|
||||||
not only on the latest (3.14 here).
|
not only on the latest (3.14 here).
|
||||||
|
|
||||||
@@ -210,7 +213,7 @@ Notes for when the builds move to a pipeline.
|
|||||||
- `Build.ps1` ends by running the server, which waits on its console:
|
- `Build.ps1` ends by running the server, which waits on its console:
|
||||||
needs a `-NoRun` switch. It also writes private keys into `Build\`,
|
needs a `-NoRun` switch. It also writes private keys into `Build\`,
|
||||||
which must never be published as an artifact.
|
which must never be published as an artifact.
|
||||||
- The tests use fixed ports (12399 for the release, 12401-12409 for
|
- The tests use fixed ports (12399 for the release, 12401-12414 for
|
||||||
`Tests/`): parallel jobs on one runner collide, make them parameters
|
`Tests/`): parallel jobs on one runner collide, make them parameters
|
||||||
or pick free ones.
|
or pick free ones.
|
||||||
- One entry point that runs every test (`Tests/*.ps1`, the handshake
|
- One entry point that runs every test (`Tests/*.ps1`, the handshake
|
||||||
|
|||||||
@@ -13,10 +13,16 @@ to the app (Message.json() helps).
|
|||||||
print(message.id, message.data)
|
print(message.id, message.data)
|
||||||
for message in client.follow("logs", "kitchen"): # until stopped
|
for message in client.follow("logs", "kitchen"): # until stopped
|
||||||
print(message.id, message.json())
|
print(message.id, message.json())
|
||||||
|
photo_id = client.push({"kind": "photo"}, attachment="photo.jpg")
|
||||||
|
client.save_attachment("logs", "kitchen", photo_id, "copy.jpg")
|
||||||
|
|
||||||
Topics and nodes are "refs": a name ("logs") or an id (12, or "12"), ids
|
Topics and nodes are "refs": a name ("logs") or an id (12, or "12"), ids
|
||||||
being the server's own.
|
being the server's own.
|
||||||
|
|
||||||
|
A message can have one attachment (a file, or bytes), of any size the
|
||||||
|
server takes: uploaded in parts before the message is stored, read back in
|
||||||
|
parts, checked with its SHA-256 (Design/Attachments.md).
|
||||||
|
|
||||||
The connection only goes through to the server holding the private key of
|
The connection only goes through to the server holding the private key of
|
||||||
server_public_key (client.ini's ServerPublicKey, the server logs it when it
|
server_public_key (client.ini's ServerPublicKey, the server logs it when it
|
||||||
starts), and everything on it is encrypted.
|
starts), and everything on it is encrypted.
|
||||||
@@ -76,7 +82,10 @@ class Message:
|
|||||||
"""A stored message. data is as stored: JSON or not (the server's
|
"""A stored message. data is as stored: JSON or not (the server's
|
||||||
is_json column tells which, json() parses it). pushed_at: when it was
|
is_json column tells which, json() parses it). pushed_at: when it was
|
||||||
pushed, to whichever server it was pushed to, in milliseconds since
|
pushed, to whichever server it was pushed to, in milliseconds since
|
||||||
1970-01-01 UTC (pushed is the same as a datetime)."""
|
1970-01-01 UTC (pushed is the same as a datetime). attachment_size: its
|
||||||
|
attachment's, 0 for none; attachment_ready: whether all of it is on
|
||||||
|
this server (a replicated one comes after its message), see
|
||||||
|
Client.get_attachment() and save_attachment()."""
|
||||||
|
|
||||||
id: int
|
id: int
|
||||||
topic: str
|
topic: str
|
||||||
@@ -85,6 +94,8 @@ class Message:
|
|||||||
node_id: int
|
node_id: int
|
||||||
data: str
|
data: str
|
||||||
pushed_at: int = 0
|
pushed_at: int = 0
|
||||||
|
attachment_size: int = 0
|
||||||
|
attachment_ready: bool = False
|
||||||
|
|
||||||
def json(self) -> Any:
|
def json(self) -> Any:
|
||||||
"""The data parsed as JSON, raises ValueError if it isn't."""
|
"""The data parsed as JSON, raises ValueError if it isn't."""
|
||||||
@@ -191,6 +202,14 @@ class _Dll:
|
|||||||
"BakaShrot_HasMoreMessages": (I, []),
|
"BakaShrot_HasMoreMessages": (I, []),
|
||||||
"BakaShrot_GetMessageId": (Q, []),
|
"BakaShrot_GetMessageId": (Q, []),
|
||||||
"BakaShrot_GetMessagePushedAt": (Q, []),
|
"BakaShrot_GetMessagePushedAt": (Q, []),
|
||||||
|
"BakaShrot_GetMessageAttachmentSize": (Q, []),
|
||||||
|
"BakaShrot_IsMessageAttachmentReady": (I, []),
|
||||||
|
"BakaShrot_PushMessageWithFileA": (Q, [P, P, P]),
|
||||||
|
"BakaShrot_PushMessageWithDataA": (Q, [P, P, S, Q]),
|
||||||
|
"BakaShrot_SaveAttachmentA": (Q, [P, P, Q, P]),
|
||||||
|
"BakaShrot_LoadAttachmentA": (Q, [P, P, Q]),
|
||||||
|
"BakaShrot_GetAttachmentData": (Q, [S, Q]),
|
||||||
|
"BakaShrot_FreeAttachmentData": (I, []),
|
||||||
"BakaShrot_GetMessageTopicId": (L, []),
|
"BakaShrot_GetMessageTopicId": (L, []),
|
||||||
"BakaShrot_GetMessageNodeId": (L, []),
|
"BakaShrot_GetMessageNodeId": (L, []),
|
||||||
"BakaShrot_GetMessageTopicA": (I, [S, I]),
|
"BakaShrot_GetMessageTopicA": (I, [S, I]),
|
||||||
@@ -325,27 +344,73 @@ class Client:
|
|||||||
|
|
||||||
# --- Requests ----------------------------------------------------------
|
# --- Requests ----------------------------------------------------------
|
||||||
|
|
||||||
def push(self, data: Any, topic: Optional[Ref] = None) -> int:
|
def push(self, data: Any, topic: Optional[Ref] = None,
|
||||||
|
attachment: Union[None, bytes, bytearray, memoryview, str, os.PathLike] = None) -> int:
|
||||||
"""Pushes a message into topic (default: the client's own), under
|
"""Pushes a message into topic (default: the client's own), under
|
||||||
the client's node. data is stored as is if it's a str (JSON or not),
|
the client's node. data is stored as is if it's a str (JSON or not),
|
||||||
anything else is turned into JSON first. Returns its message id."""
|
anything else is turned into JSON first. Returns its message id.
|
||||||
|
|
||||||
|
attachment: bytes, or the path of a file, uploaded first (in parts,
|
||||||
|
any size the server's MaxAttachmentSize allows): the message is only
|
||||||
|
stored once all of it is."""
|
||||||
if not isinstance(data, str):
|
if not isinstance(data, str):
|
||||||
data = json.dumps(data, separators=(",", ":"), ensure_ascii=False)
|
data = json.dumps(data, separators=(",", ":"), ensure_ascii=False)
|
||||||
encoded = data.encode("utf-8")
|
encoded = data.encode("utf-8")
|
||||||
if len(encoded) > MAX_MESSAGE_SIZE:
|
if len(encoded) > MAX_MESSAGE_SIZE:
|
||||||
raise BakaShrotError(f"The message is too big: {len(encoded)} bytes, at most {MAX_MESSAGE_SIZE}")
|
raise BakaShrotError(f"The message is too big: {len(encoded)} bytes, at most {MAX_MESSAGE_SIZE}")
|
||||||
|
topic_ref = b"" if topic is None else _ref(topic)
|
||||||
with self._lock:
|
with self._lock:
|
||||||
self._check_connected()
|
self._check_connected()
|
||||||
message_id = self._dll.PushMessageToA(b"" if topic is None else _ref(topic), encoded)
|
if attachment is None:
|
||||||
|
message_id = self._dll.PushMessageToA(topic_ref, encoded)
|
||||||
|
elif isinstance(attachment, (bytes, bytearray, memoryview)):
|
||||||
|
raw = bytes(attachment)
|
||||||
|
if not raw:
|
||||||
|
raise BakaShrotError("The attachment is empty")
|
||||||
|
buffer = ctypes.create_string_buffer(raw, len(raw))
|
||||||
|
message_id = self._dll.PushMessageWithDataA(topic_ref, encoded, ctypes.cast(buffer, ctypes.c_void_p), len(raw))
|
||||||
|
else:
|
||||||
|
path = os.fspath(attachment)
|
||||||
|
if not os.path.isfile(path) or os.path.getsize(path) == 0:
|
||||||
|
raise BakaShrotError(f"Can't attach {path!r}: no such file, or empty")
|
||||||
|
message_id = self._dll.PushMessageWithFileA(topic_ref, encoded, path.encode("utf-8"))
|
||||||
if message_id < 1:
|
if message_id < 1:
|
||||||
raise self._failed("Push")
|
raise self._failed("Push")
|
||||||
return message_id
|
return message_id
|
||||||
|
|
||||||
|
def get_attachment(self, topic: Ref, node: Ref, message_id: int) -> bytes:
|
||||||
|
"""The attachment of topic:node#message_id, all of it in memory
|
||||||
|
(save_attachment() for big ones), checked with its SHA-256. Raises
|
||||||
|
RefusedError if the message has none, or it isn't on this server
|
||||||
|
yet."""
|
||||||
|
with self._lock:
|
||||||
|
self._check_connected()
|
||||||
|
size = self._dll.LoadAttachmentA(_ref(topic), _ref(node), int(message_id))
|
||||||
|
if size < 0:
|
||||||
|
raise self._failed("Attachment")
|
||||||
|
try:
|
||||||
|
buffer = ctypes.create_string_buffer(size)
|
||||||
|
self._dll.GetAttachmentData(ctypes.cast(buffer, ctypes.c_void_p), size)
|
||||||
|
return buffer.raw[:size]
|
||||||
|
finally:
|
||||||
|
self._dll.FreeAttachmentData()
|
||||||
|
|
||||||
|
def save_attachment(self, topic: Ref, node: Ref, message_id: int, path: Union[str, os.PathLike]) -> int:
|
||||||
|
"""Saves the attachment of topic:node#message_id to path (replaced),
|
||||||
|
a part at a time, checked with its SHA-256. Returns its size. A
|
||||||
|
failed one leaves no file."""
|
||||||
|
with self._lock:
|
||||||
|
self._check_connected()
|
||||||
|
size = self._dll.SaveAttachmentA(_ref(topic), _ref(node), int(message_id), os.fspath(path).encode("utf-8"))
|
||||||
|
if size < 0:
|
||||||
|
raise self._failed("Attachment")
|
||||||
|
return size
|
||||||
|
|
||||||
def _current(self) -> Message:
|
def _current(self) -> Message:
|
||||||
dll = self._dll
|
dll = self._dll
|
||||||
return Message(dll.GetMessageId(), dll.string(dll.GetMessageTopicA), dll.string(dll.GetMessageNodeA),
|
return Message(dll.GetMessageId(), dll.string(dll.GetMessageTopicA), dll.string(dll.GetMessageNodeA),
|
||||||
dll.GetMessageTopicId(), dll.GetMessageNodeId(), dll.string(dll.GetMessageDataA),
|
dll.GetMessageTopicId(), dll.GetMessageNodeId(), dll.string(dll.GetMessageDataA),
|
||||||
dll.GetMessagePushedAt())
|
dll.GetMessagePushedAt(), dll.GetMessageAttachmentSize(), bool(dll.IsMessageAttachmentReady()))
|
||||||
|
|
||||||
def latest(self, topic: Ref, node: Ref) -> Optional[Message]:
|
def latest(self, topic: Ref, node: Ref) -> Optional[Message]:
|
||||||
"""The latest message of topic/node, None if there's none yet."""
|
"""The latest message of topic/node, None if there's none yet."""
|
||||||
|
|||||||
@@ -6,7 +6,10 @@ Usage: python check_bakashrot.py <DllPath> <KitchenIni> <LoungeIni>
|
|||||||
Expects an empty database. Prints PASS/FAIL per check, exits 1 if any failed.
|
Expects an empty database. Prints PASS/FAIL per check, exits 1 if any failed.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import os
|
||||||
import sys
|
import sys
|
||||||
|
import tempfile
|
||||||
import threading
|
import threading
|
||||||
import time
|
import time
|
||||||
|
|
||||||
@@ -159,6 +162,44 @@ with kitchen:
|
|||||||
not thread.is_alive() and not errors and [m.id for m in followed] == new_ids,
|
not thread.is_alive() and not errors and [m.id for m in followed] == new_ids,
|
||||||
f"{[m.id for m in followed]} vs {new_ids}, errors {errors}")
|
f"{[m.id for m in followed]} vs {new_ids}, errors {errors}")
|
||||||
|
|
||||||
|
# --- Attachments (in secret, the other checks count logs) -------------------
|
||||||
|
blob = os.urandom(3 * 1024 * 1024 + 7)
|
||||||
|
started = time.perf_counter()
|
||||||
|
blob_id = kitchen.push({"kind": "blob"}, topic="secret", attachment=blob)
|
||||||
|
up = time.perf_counter() - started
|
||||||
|
message = kitchen.latest("secret", "kitchen")
|
||||||
|
check("push(attachment=bytes): the message has it, ready",
|
||||||
|
message is not None and message.id == blob_id and message.attachment_size == len(blob) and message.attachment_ready,
|
||||||
|
message)
|
||||||
|
started = time.perf_counter()
|
||||||
|
data = kitchen.get_attachment("secret", "kitchen", blob_id)
|
||||||
|
down = time.perf_counter() - started
|
||||||
|
check("get_attachment(): the same bytes", data == blob, f"{len(data)} bytes, {up * 1000:.0f} ms up, {down * 1000:.0f} ms down")
|
||||||
|
|
||||||
|
folder = tempfile.mkdtemp()
|
||||||
|
source = os.path.join(folder, "source.bin")
|
||||||
|
with open(source, "wb") as file:
|
||||||
|
file.write(os.urandom(1500 * 1024))
|
||||||
|
file_id = kitchen.push("from a file", topic="secret", attachment=source)
|
||||||
|
copy = os.path.join(folder, "copy.bin")
|
||||||
|
size = kitchen.save_attachment("secret", "kitchen", file_id, copy)
|
||||||
|
with open(source, "rb") as a, open(copy, "rb") as b:
|
||||||
|
same = hashlib.sha256(a.read()).digest() == hashlib.sha256(b.read()).digest()
|
||||||
|
check("push(attachment=path), save_attachment(): the same file", size == os.path.getsize(source) and same, size)
|
||||||
|
|
||||||
|
plain_id = kitchen.push("no attachment", topic="secret")
|
||||||
|
page = kitchen.get_messages("secret", "kitchen", after=blob_id - 1)
|
||||||
|
sizes = [(m.id, m.attachment_size, m.attachment_ready) for m in page]
|
||||||
|
check("get_messages(): each message's attachment",
|
||||||
|
sizes == [(blob_id, len(blob), True), (file_id, os.path.getsize(source), True), (plain_id, 0, False)], sizes)
|
||||||
|
ok, detail = raises(lambda: kitchen.get_attachment("secret", "kitchen", plain_id), RefusedError, "No attachment")
|
||||||
|
check("get_attachment() of a message without: RefusedError", ok, detail)
|
||||||
|
ok, detail = raises(lambda: kitchen.push("x", topic="secret", attachment=b""), BakaShrotError, "empty")
|
||||||
|
check("An empty attachment: refused before sending", ok, detail)
|
||||||
|
ok, detail = raises(lambda: kitchen.push("x", topic="secret", attachment=os.path.join(folder, "missing.bin")), BakaShrotError, "no such file")
|
||||||
|
check("A missing file: refused before sending", ok, detail)
|
||||||
|
check("Still connected", kitchen.connected)
|
||||||
|
|
||||||
check("close(): disconnected", not kitchen.connected)
|
check("close(): disconnected", not kitchen.connected)
|
||||||
ok, detail = raises(lambda: kitchen.push("x"), ConnectionLostError)
|
ok, detail = raises(lambda: kitchen.push("x"), ConnectionLostError)
|
||||||
check("A request once closed: ConnectionLostError", ok, detail)
|
check("A request once closed: ConnectionLostError", ok, detail)
|
||||||
|
|||||||
@@ -1,11 +1,13 @@
|
|||||||
# BakaShrot - working notes
|
# BakaShrot - working notes
|
||||||
|
|
||||||
Where things stand and what's next, as of 2026-11-08. The detailed docs are in
|
Where things stand and what's next, as of 2026-11-08. A new session: read
|
||||||
`Design/`:
|
`CLAUDE.md` first (how to build, test, and the traps), then "Open items"
|
||||||
|
below. The detailed docs are in `Design/`:
|
||||||
|
|
||||||
| Doc | About |
|
| Doc | About |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `Design/Packets.md` | The protocol: framing, every packet, flows, conventions, how to add a packet. |
|
| `Design/Packets.md` | The protocol: framing, every packet, flows, conventions, how to add a packet. |
|
||||||
|
| `Design/Attachments.md` | Attachments: one per message, in 1 MB parts, uploaded before the message, replicated after it. |
|
||||||
| `Design/Cryptography.md` | What libsodium is used for: the handshake proving both ends, the connections' encryption. What isn't done, and ideas for abstracting it. |
|
| `Design/Cryptography.md` | What libsodium is used for: the handshake proving both ends, the connections' encryption. What isn't done, and ideas for abstracting it. |
|
||||||
| `Design/ReplicationIssues.md` | Known replication problems, with benchmarks. |
|
| `Design/ReplicationIssues.md` | Known replication problems, with benchmarks. |
|
||||||
| `Design/StorageConcurrency.md` | One connection per thread, WAL, the write mutex and the writer (done), and what's left. |
|
| `Design/StorageConcurrency.md` | One connection per thread, WAL, the write mutex and the writer (done), and what's left. |
|
||||||
@@ -24,7 +26,8 @@ Where things stand and what's next, as of 2026-11-08. The detailed docs are in
|
|||||||
- **Server:**
|
- **Server:**
|
||||||
- Every connection is encrypted, and both ends prove who they are: the
|
- Every connection is encrypted, and both ends prove who they are: the
|
||||||
client with an Ed25519 challenge, the server by signing the handshake
|
client with an Ed25519 challenge, the server by signing the handshake
|
||||||
with the key its clients know (protocol 3, `Design/Cryptography.md`).
|
with the key its clients know (since protocol 3, `Design/Cryptography.md`;
|
||||||
|
the protocol is at 4, with attachments).
|
||||||
- Clients can push messages (usually JSON, anything is stored, flagged
|
- Clients can push messages (usually JSON, anything is stored, flagged
|
||||||
in `is_json`), read the latest one of a topic/node pair or a run of
|
in `is_json`), read the latest one of a topic/node pair or a run of
|
||||||
them after an id, resolve names, and run raw read-only SQL, each depending on
|
them after an id, resolve names, and run raw read-only SQL, each depending on
|
||||||
@@ -35,12 +38,16 @@ Where things stand and what's next, as of 2026-11-08. The detailed docs are in
|
|||||||
- Stamps every push with the time it arrived (`pushed_at`, UTC ms), which
|
- Stamps every push with the time it arrived (`pushed_at`, UTC ms), which
|
||||||
replication carries as is, and deletes each topic's messages past its
|
replication carries as is, and deletes each topic's messages past its
|
||||||
max age (`[BakaShrot.Retention]`, per server).
|
max age (`[BakaShrot.Retention]`, per server).
|
||||||
|
- A message can have one attachment of any size up to `MaxAttachmentSize`
|
||||||
|
(default 1G), sent in 1 MB parts, replicated after its message
|
||||||
|
(`Design/Attachments.md`).
|
||||||
- One thread per client and per peer, each with its own SQLite connection.
|
- One thread per client and per peer, each with its own SQLite connection.
|
||||||
- The root thread can stop every worker (restart, vacuum).
|
- The root thread can stop every worker (restart, vacuum).
|
||||||
- **Client:** a DLL with A/W string exports, PureBasic prototypes in
|
- **Client:** a DLL with A/W string exports, PureBasic prototypes in
|
||||||
`Client/BakaShrot_Client_Prototypes.pbi`, and tools in `Tools/`:
|
`Client/BakaShrot_Client_Prototypes.pbi`, and tools in `Tools/`:
|
||||||
`PushMessage`, `GetLatestMessage`, `GetMessages` (with `--follow`),
|
`PushMessage` (`-a` to attach a file), `GetLatestMessage`, `GetMessages`
|
||||||
`Resolve`, `ListNames`, `Query`, `KeyGen`.
|
(with `--follow`), `GetAttachment`, `Resolve`, `ListNames`, `Query`,
|
||||||
|
`KeyGen`.
|
||||||
- **Python:** `Interactors/Python/bakashrot.py`, over the DLL with ctypes,
|
- **Python:** `Interactors/Python/bakashrot.py`, over the DLL with ctypes,
|
||||||
no dependencies, and `example.py`.
|
no dependencies, and `example.py`.
|
||||||
- **Release:** `Release.ps1` builds with PB 6.40's C backend into
|
- **Release:** `Release.ps1` builds with PB 6.40's C backend into
|
||||||
@@ -174,9 +181,8 @@ existing `data` means rebuilding the table. So: name tables, joined, no FKs.
|
|||||||
s), over it refused, non-JSON stored with is_json = 0 (10 edge cases), replicated intact to the
|
s), over it refused, non-JSON stored with is_json = 0 (10 edge cases), replicated intact to the
|
||||||
other server, a 16 MB read back from it (0.5 s), small ones still
|
other server, a 16 MB read back from it (0.5 s), small ones still
|
||||||
batched. `Names-Test.ps1` and the handshake test still pass.
|
batched. `Names-Test.ps1` and the handshake test still pass.
|
||||||
- **Left:** attachments for real files (the unused `attachements` table:
|
- **Left:** attachments for real files, if more than 16 MB is ever needed:
|
||||||
the message references a blob sent in chunks, only when wanted), if more
|
done since, see `Design/Attachments.md`. Memory: an authenticated connection can hold
|
||||||
than 16 MB is ever needed. Memory: an authenticated connection can hold
|
|
||||||
up to ~32 MB of inbox (64 MB in the worst case of the growth), plus the
|
up to ~32 MB of inbox (64 MB in the worst case of the growth), plus the
|
||||||
packet being handled.
|
packet being handled.
|
||||||
|
|
||||||
@@ -259,8 +265,9 @@ As judged for the threat model below (internal tool, trusted machines).
|
|||||||
**Good**
|
**Good**
|
||||||
- The core works and is tested end to end: push, latest, runs of messages
|
- The core works and is tested end to end: push, latest, runs of messages
|
||||||
and `--follow`, names and ids, filters and wildcards, raw read-only SQL,
|
and `--follow`, names and ids, filters and wildcards, raw read-only SQL,
|
||||||
per-client permissions; five suites, two `.pb` tests, the release's smoke
|
per-client permissions, retention, attachments; eight `Tests/*.ps1`
|
||||||
test (PB 6.40 C), all passing.
|
suites, two `.pb` tests, the release's smoke test (PB 6.40 C), all
|
||||||
|
passing (see `CLAUDE.md` for the list).
|
||||||
- Fast: ~40,800 msg/s pushed across 4 servers (10 nodes each, PB 5.73),
|
- Fast: ~40,800 msg/s pushed across 4 servers (10 nodes each, PB 5.73),
|
||||||
fully replicated; ~9,000 msg/s from one Python connection.
|
fully replicated; ~9,000 msg/s from one Python connection.
|
||||||
- Replication by name, each server with its own ids; restart catch-up is
|
- Replication by name, each server with its own ids; restart catch-up is
|
||||||
@@ -268,7 +275,8 @@ As judged for the threat model below (internal tool, trusted machines).
|
|||||||
- Security beyond what's needed here: encrypted connections, both ends
|
- Security beyond what's needed here: encrypted connections, both ends
|
||||||
proven, peer links verified.
|
proven, peer links verified.
|
||||||
- Data: 16 MB messages, anything stored (`is_json`), errors of queries
|
- Data: 16 MB messages, anything stored (`is_json`), errors of queries
|
||||||
surfaced; pushed times; retention per topic and server.
|
surfaced; pushed times; retention per topic and server; one attachment
|
||||||
|
per message, any size, flat memory (512 MB with the server at 15 MB).
|
||||||
- Clients: DLL for any language, CLI tools, dependency-free Python.
|
- Clients: DLL for any language, CLI tools, dependency-free Python.
|
||||||
- Packaging (runtime included) and docs that match the code.
|
- Packaging (runtime included) and docs that match the code.
|
||||||
|
|
||||||
@@ -289,11 +297,16 @@ As judged for the threat model below (internal tool, trusted machines).
|
|||||||
main blocker for deploying it.
|
main blocker for deploying it.
|
||||||
- Never run from the extracted zip, on a clean Windows, nor with two
|
- Never run from the extracted zip, on a clean Windows, nor with two
|
||||||
release servers, nor restarted after a kill: designed to work, unchecked.
|
release servers, nor restarted after a kill: designed to work, unchecked.
|
||||||
- Nothing committed: everything since the initial commit (the deleted
|
- A corrupted stored attachment is re-sent to peers forever (open item 3).
|
||||||
`Core/` included) lives only in the working tree.
|
|
||||||
|
|
||||||
Suggested order: commit; a stop file and running as a service; smoke-test
|
Commits (at this writing, check `git log`): `master` has everything up to
|
||||||
items 1-3 (`Design/Release.md`); a single test runner, then CI.
|
protocol 3 (`12fbe5f`); branch `timestamps-retention` adds timestamps and
|
||||||
|
retention (`9caf816`); attachments and their tests were left uncommitted on
|
||||||
|
that branch, waiting for the owner to ask.
|
||||||
|
|
||||||
|
Suggested order: a stop file and running as a service; smoke-test items
|
||||||
|
1-3 (`Design/Release.md`); the corrupted-attachment fix; a single test
|
||||||
|
runner, then CI.
|
||||||
|
|
||||||
## Done: pushed times, retention (2026-11-08)
|
## Done: pushed times, retention (2026-11-08)
|
||||||
|
|
||||||
@@ -340,6 +353,48 @@ items 1-3 (`Design/Release.md`); a single test runner, then CI.
|
|||||||
- **Removed:** the `archives` table, a leftover of the first schemas that
|
- **Removed:** the `archives` table, a leftover of the first schemas that
|
||||||
nothing ever used, dropped from existing databases at start.
|
nothing ever used, dropped from existing databases at start.
|
||||||
|
|
||||||
|
## Done: attachments (2026-11-08)
|
||||||
|
|
||||||
|
- **One per message**, optional: bytes of any size up to the server's
|
||||||
|
`MaxAttachmentSize` (default 1G, at most 1T), no name or type (the JSON
|
||||||
|
says what it is), a size and a SHA-256. Protocol version 4, schema v7.
|
||||||
|
- **Pushing:** uploaded first in 1 MB parts (UploadStart, UploadChunk), the
|
||||||
|
server checks the SHA-256, then the PushMessage carries the upload's id:
|
||||||
|
the message and its attachment are stored in the same transaction, so
|
||||||
|
readers never see one without the other. Uploads not pushed within
|
||||||
|
`UploadTimeout` (default 3600 s) are deleted.
|
||||||
|
- **Reading:** a part per request (GetAttachment), checked by the client.
|
||||||
|
Messages tell `AttachmentSize` and `AttachmentReady`.
|
||||||
|
- **Replication:** separate from the messages, after them: the message
|
||||||
|
carries the size and SHA-256, then at each check-in the peer lists what
|
||||||
|
it's missing (MissingAttachments), the sender sends the parts, from where
|
||||||
|
the peer stopped. Over the receiver's `MaxAttachmentSize`: the message
|
||||||
|
comes, the attachment is marked not kept and never asked for.
|
||||||
|
- **Deleted with its message** (retention): triggers mark the data, the
|
||||||
|
retention thread deletes its parts 32 at a time. It now always runs.
|
||||||
|
- **Clients:** DLL `BakaShrot_PushMessageWithFile/WithData()`,
|
||||||
|
`_SaveAttachment()`, `_LoadAttachment()` + `_GetAttachmentData()`,
|
||||||
|
`_GetMessageAttachmentSize()`, `_IsMessageAttachmentReady()`; Python
|
||||||
|
`push(..., attachment=bytes or path)`, `get_attachment()`,
|
||||||
|
`save_attachment()`, `Message.attachment_size/_ready`; tools
|
||||||
|
`PushMessage -a`, `GetAttachment`.
|
||||||
|
- **Measured:** 512 MB up in 8.5 s, down in 3.9 s, identical, the server
|
||||||
|
peaking at 15 MB of memory. The push benchmark isn't affected (messages
|
||||||
|
without attachments only gain a LEFT JOIN on reads).
|
||||||
|
- **Tested:** `Tests/Attachments-Test.ps1` (39 checks, ports 12410-12411),
|
||||||
|
Python's checks (55 in all now); every other suite still passes.
|
||||||
|
- **Edge cases tested:** `Tests/AttachmentEdges-Test.ps1` (51 checks, a raw
|
||||||
|
protocol client): wrong SHA-256, parts out of order / wrong size /
|
||||||
|
repeated, others' uploads, wrong topic, attached twice, too big, uploads
|
||||||
|
expiring past `UploadTimeout`, replication resuming after the receiver
|
||||||
|
was killed mid-transfer, a corrupted stored copy. All hold.
|
||||||
|
- **Found:** a server whose own copy is corrupted re-sends it to its peers
|
||||||
|
at every check-in, forever, and serves it to clients (who refuse it).
|
||||||
|
Not fixed: open item 3 below has the details and the proposed fix.
|
||||||
|
- **Left:** resuming an upload after a dropped connection (replication
|
||||||
|
does resume); several parts in flight for high-latency links.
|
||||||
|
See `Design/Attachments.md`.
|
||||||
|
|
||||||
## Threat model (2026-11-08)
|
## Threat model (2026-11-08)
|
||||||
|
|
||||||
BakaShrot is an **internal tool, on trusted machines and a trusted
|
BakaShrot is an **internal tool, on trusted machines and a trusted
|
||||||
@@ -370,58 +425,92 @@ network**, not exposed to the internet. So:
|
|||||||
replication between two release servers, restart catch-up (designed to
|
replication between two release servers, restart catch-up (designed to
|
||||||
work, never tested: kill a server, check ids continue and peers catch
|
work, never tested: kill a server, check ids continue and peers catch
|
||||||
up). (`Design/Release.md`, items 1-3)
|
up). (`Design/Release.md`, items 1-3)
|
||||||
3. **`synchronous = NORMAL`:** the last commits can be lost on a power loss
|
3. **A corrupted stored attachment is re-sent to peers forever.** Found
|
||||||
|
by `Tests/AttachmentEdges-Test.ps1` part 4 (a byte flipped in the
|
||||||
|
sender's `blob_chunks`, `flip.py`).
|
||||||
|
- What happens: the peer checks the SHA-256 once all parts are in,
|
||||||
|
drops its copy (`FinishReplicatedAttachment(..., #False)`), refuses the
|
||||||
|
last part ("The attachment doesn't match its SHA-256, send it again"),
|
||||||
|
and lists it as missing again. At the next check-in the sender sends
|
||||||
|
all of it again: every `PeerSyncInterval` (6 times in 6 s in the test),
|
||||||
|
1 GB each time for a 1 GB attachment. Forever.
|
||||||
|
- The sender never notices: it also serves the damaged parts to clients
|
||||||
|
(`GetAttachment`), who refuse them by their SHA-256 (the DLL checks at
|
||||||
|
the end of `BakaShrot_Download()`).
|
||||||
|
- Proposed fix, in `BakaShrot_PeerLink_SendAttachment()`
|
||||||
|
(`Server/Networking/Peers.pbi`): when the peer refuses with "doesn't
|
||||||
|
match", check this server's own copy with `HashStorageBlob()`
|
||||||
|
(`Server/Storage/Attachments.pbi`, the link's own `DbId`). If it's
|
||||||
|
damaged, `FinishReplicatedAttachment(TopicId, NodeId, MessageId,
|
||||||
|
BlobId, #False)` already does the rest: drops the blob, marks the
|
||||||
|
attachment missing (state 0), so this server stops sending it and asks
|
||||||
|
its own peers for a good copy (`MissingAttachments`), and stops
|
||||||
|
serving it. Log it loudly. If its copy is fine (the damage was in
|
||||||
|
transit), sending again is right.
|
||||||
|
- Better than matching the refusal's text: a distinct answer for "the
|
||||||
|
data doesn't match", e.g. a `ChunkStored` with `Complete = 0` and
|
||||||
|
`Received = 0` after the last part, or a new field.
|
||||||
|
- The origin (where it was pushed) has no other source: its attachment
|
||||||
|
then stays missing ("isn't here yet"), better than serving bad data;
|
||||||
|
maybe a "lost" state (4) so `GetAttachment` says so.
|
||||||
|
- Optional, to catch it on reads too: a SHA-256 per part in
|
||||||
|
`blob_chunks`, checked by `ReadStorageBlobChunk()`, at ~3 s/GB.
|
||||||
|
- Test: part 4 of `AttachmentEdges-Test.ps1` then expects the sender to
|
||||||
|
log its copy as damaged and the re-sends to stop (today it only prints
|
||||||
|
an INFO line with the count); its own `attachments` row goes to 0.
|
||||||
|
4. **`synchronous = NORMAL`:** the last commits can be lost on a power loss
|
||||||
or OS crash (not on a killed process). Decide, or switch to `FULL`.
|
or OS crash (not on a killed process). Decide, or switch to `FULL`.
|
||||||
(`Design/StorageConcurrency.md`)
|
(`Design/StorageConcurrency.md`)
|
||||||
4. **Drift between servers** when one topic/node pair is written to on two
|
5. **Drift between servers** when one topic/node pair is written to on two
|
||||||
servers: only partially resynced. Accepted while each pair has a single
|
servers: only partially resynced. Accepted while each pair has a single
|
||||||
writer; document that as the rule. (`Design/ReplicationIssues.md` #1)
|
writer; document that as the rule. (`Design/ReplicationIssues.md` #1)
|
||||||
5. **Gaps in a pair's ids aren't detected** on replication.
|
6. **Gaps in a pair's ids aren't detected** on replication.
|
||||||
(`Design/ReplicationIssues.md` #5)
|
(`Design/ReplicationIssues.md` #5)
|
||||||
6. **No single test runner**, and fixed ports (12399, 12401-12409): every
|
7. **No single test runner**, and fixed ports (12399, 12401-12414): every
|
||||||
`Tests/*.ps1` and the two `.pb` tests are run by hand. Needed for CI.
|
`Tests/*.ps1` and the two `.pb` tests are run by hand. Needed for CI.
|
||||||
(`Design/Release.md`, "For CI/CD")
|
(`Design/Release.md`, "For CI/CD")
|
||||||
7. **Is `DatabaseError()` per thread?** Messages could land in the wrong
|
8. **Is `DatabaseError()` per thread?** Messages could land in the wrong
|
||||||
thread's log or refusal; Windows queries no longer depend on it.
|
thread's log or refusal; Windows queries no longer depend on it.
|
||||||
(`Design/StorageConcurrency.md`)
|
(`Design/StorageConcurrency.md`)
|
||||||
8. **Limits:** the sync state must fit in one packet (65536 topic/node
|
9. **Limits:** the sync state must fit in one packet (65536 topic/node
|
||||||
pairs); `ReplicatingTopicIds` ranges are expanded to every id they cover.
|
pairs); `ReplicatingTopicIds` ranges are expanded to every id they cover.
|
||||||
(`Design/ReplicationIssues.md` #7)
|
(`Design/ReplicationIssues.md` #7)
|
||||||
|
|
||||||
### Client side
|
### Client side
|
||||||
|
|
||||||
9. **One connection per process** (the DLL's globals): a handle-based API
|
10. **One connection per process** (the DLL's globals): a handle-based API
|
||||||
for several. No reconnect in `GetMessages --follow` / `follow()`, polling
|
for several. No reconnect in `GetMessages --follow` / `follow()`, polling
|
||||||
rather than server-pushed subscriptions.
|
rather than server-pushed subscriptions.
|
||||||
10. **Breaking with protocol 3:** every client config needs
|
11. **Breaking with protocols 3 and 4:** every client config needs
|
||||||
`ServerPublicKey`; older clients can't connect. Fine while it's all
|
`ServerPublicKey`; older clients and servers can't connect (any
|
||||||
|
version difference refuses the connection). Fine while it's all
|
||||||
built from this repo, worth a line in the release notes of the first
|
built from this repo, worth a line in the release notes of the first
|
||||||
real release.
|
real release.
|
||||||
|
|
||||||
### Security, low priority under the threat model
|
### Security, low priority under the threat model
|
||||||
|
|
||||||
11. **Peers are trusted completely:** messages aren't signed by the node
|
12. **Peers are trusted completely:** messages aren't signed by the node
|
||||||
that first wrote them, a peer can replicate anything in what we accept
|
that first wrote them, a peer can replicate anything in what we accept
|
||||||
from it. (`Design/ReplicationIssues.md` #3)
|
from it. (`Design/ReplicationIssues.md` #3)
|
||||||
12. **Private keys sit in plain-text ini files**, readable by whoever can
|
13. **Private keys sit in plain-text ini files**, readable by whoever can
|
||||||
read the config. On trusted machines: file permissions are enough.
|
read the config. On trusted machines: file permissions are enough.
|
||||||
13. **No key rotation or revocation**, other than editing configs and
|
14. **No key rotation or revocation**, other than editing configs and
|
||||||
restarting; a server can't announce a new key, clients pin one.
|
restarting; a server can't announce a new key, clients pin one.
|
||||||
14. **The handshake costs the server work before the client proved
|
15. **The handshake costs the server work before the client proved
|
||||||
anything** (a sealed box, a key pair, a signature): no rate limit, only
|
anything** (a sealed box, a key pair, a signature): no rate limit, only
|
||||||
the 4 KB handshake limit and the 10 s timeout.
|
the 4 KB handshake limit and the 10 s timeout.
|
||||||
15. **Small ones:** the DLL doesn't wipe its private key; one identity key
|
16. **Small ones:** the DLL doesn't wipe its private key; one identity key
|
||||||
both signs and opens sealed boxes; `EncodeData`/`DecodeData` are
|
both signs and opens sealed boxes; `EncodeData`/`DecodeData` are
|
||||||
misnamed (they sign/verify). (`Design/Cryptography.md`)
|
misnamed (they sign/verify). (`Design/Cryptography.md`)
|
||||||
|
|
||||||
### Housekeeping
|
### Housekeeping
|
||||||
|
|
||||||
16. **Review.md rules** not checked against the newer code (`.i` in
|
17. **Review.md rules** not checked against the newer code (`.i` in
|
||||||
networking structures, explicit enumeration values), see below. The
|
networking structures, explicit enumeration values), see below. The
|
||||||
file itself says to ignore it for now.
|
file itself says to ignore it for now.
|
||||||
17. **Linux is untested** (libsodium via `-lsodium`, the query error check
|
18. **Linux is untested** (libsodium via `-lsodium`, the query error check
|
||||||
falls back to `DatabaseError()`).
|
falls back to `DatabaseError()`).
|
||||||
18. **Console commands can't be scripted** (see 1).
|
19. **Console commands can't be scripted** (see 1).
|
||||||
|
|
||||||
### Done recently (details in the sections above and `Design/`)
|
### Done recently (details in the sections above and `Design/`)
|
||||||
|
|
||||||
@@ -432,6 +521,10 @@ network**, not exposed to the internet. So:
|
|||||||
- GetMessages, `--follow`, the Python client; big messages (16 MB) and
|
- GetMessages, `--follow`, the Python client; big messages (16 MB) and
|
||||||
`is_json`; names, filters and wildcards; speed: ~34,300 msg/s for 4
|
`is_json`; names, filters and wildcards; speed: ~34,300 msg/s for 4
|
||||||
servers (2026-11-07/08).
|
servers (2026-11-07/08).
|
||||||
|
- `pushed_at` timestamps, carried by replication; retention per topic and
|
||||||
|
server, skipping on arrival what's past its age (2026-11-08).
|
||||||
|
- Attachments, protocol 4: one per message, in 1 MB parts, replicated after
|
||||||
|
their message, resumable; edge cases tested (2026-11-08).
|
||||||
|
|
||||||
## To check against Review.md
|
## To check against Review.md
|
||||||
|
|
||||||
@@ -457,3 +550,13 @@ network**, not exposed to the internet. So:
|
|||||||
- **Don't trust timestamps** from PowerShell's `Register-ObjectEvent`: lines
|
- **Don't trust timestamps** from PowerShell's `Register-ObjectEvent`: lines
|
||||||
queue up during `Start-Sleep`. PureBasic's console output into a pipe is
|
queue up during `Start-Sleep`. PureBasic's console output into a pipe is
|
||||||
also buffered until exit. Trust the order, not the times.
|
also buffered until exit. Trust the order, not the times.
|
||||||
|
- **JSON on a tool's command line loses its double quotes** (PowerShell 5
|
||||||
|
and PureBasic's `ProgramParameter()`): the tests write it to a file and
|
||||||
|
pass `@file`.
|
||||||
|
- **Things only a raw client can do** (a wrong SHA-256, abandoned uploads):
|
||||||
|
`Tests/AttachmentEdgeClient.pb`, over `Commons/Networking/Outbound.pbi`.
|
||||||
|
Copy its `Exchange()` / `Refusal()` helpers for new protocol tests.
|
||||||
|
- **Corrupting or seeding a database** from a test: Python's `sqlite3`,
|
||||||
|
with the server stopped through its stop file (its WAL is checkpointed
|
||||||
|
then), see `Retention-Test.ps1` (an old schema) and
|
||||||
|
`AttachmentEdges-Test.ps1` (`flip.py`).
|
||||||
|
|||||||
+19
-4
@@ -6,8 +6,8 @@
|
|||||||
# BakaShrot_Server.exe the server
|
# BakaShrot_Server.exe the server
|
||||||
# BakaShrot_Client.dll the client DLL, with
|
# BakaShrot_Client.dll the client DLL, with
|
||||||
# BakaShrot_Client_Prototypes.pbi its PureBasic prototypes
|
# BakaShrot_Client_Prototypes.pbi its PureBasic prototypes
|
||||||
# PushMessage.exe, GetLatestMessage.exe, GetMessages.exe, Query.exe,
|
# PushMessage.exe, GetLatestMessage.exe, GetMessages.exe, GetAttachment.exe,
|
||||||
# Resolve.exe, ListNames.exe, KeyGen.exe the tools
|
# Query.exe, Resolve.exe, ListNames.exe, KeyGen.exe the tools
|
||||||
# libsodium.dll, sqlite3.dll what they need next to them
|
# libsodium.dll, sqlite3.dll what they need next to them
|
||||||
# vcruntime140.dll what libsodium.dll needs (Libs\redist)
|
# vcruntime140.dll what libsodium.dll needs (Libs\redist)
|
||||||
# python\bakashrot.py, example.py the Python client, over the DLL
|
# python\bakashrot.py, example.py the Python client, over the DLL
|
||||||
@@ -115,6 +115,7 @@ $Targets = @(
|
|||||||
@("Tools\PushMessage\PushMessage.pb", "PushMessage.exe", @("/CONSOLE")),
|
@("Tools\PushMessage\PushMessage.pb", "PushMessage.exe", @("/CONSOLE")),
|
||||||
@("Tools\GetLatestMessage\GetLatestMessage.pb", "GetLatestMessage.exe", @("/CONSOLE")),
|
@("Tools\GetLatestMessage\GetLatestMessage.pb", "GetLatestMessage.exe", @("/CONSOLE")),
|
||||||
@("Tools\GetMessages\GetMessages.pb", "GetMessages.exe", @("/CONSOLE")),
|
@("Tools\GetMessages\GetMessages.pb", "GetMessages.exe", @("/CONSOLE")),
|
||||||
|
@("Tools\GetAttachment\GetAttachment.pb", "GetAttachment.exe", @("/CONSOLE")),
|
||||||
@("Tools\Query\Query.pb", "Query.exe", @("/CONSOLE")),
|
@("Tools\Query\Query.pb", "Query.exe", @("/CONSOLE")),
|
||||||
@("Tools\Resolve\Resolve.pb", "Resolve.exe", @("/CONSOLE")),
|
@("Tools\Resolve\Resolve.pb", "Resolve.exe", @("/CONSOLE")),
|
||||||
@("Tools\ListNames\ListNames.pb", "ListNames.exe", @("/CONSOLE")),
|
@("Tools\ListNames\ListNames.pb", "ListNames.exe", @("/CONSOLE")),
|
||||||
@@ -169,9 +170,10 @@ Run the server: BakaShrot_Server.exe config.ini
|
|||||||
Topics and nodes go by name ([BakaShrot.Topics], [BakaShrot.Nodes]) or id,
|
Topics and nodes go by name ([BakaShrot.Topics], [BakaShrot.Nodes]) or id,
|
||||||
each server has its own ids for the same names.
|
each server has its own ids for the same names.
|
||||||
Tools, next to BakaShrot_Client.dll, with a client.ini:
|
Tools, next to BakaShrot_Client.dll, with a client.ini:
|
||||||
PushMessage [-t <Topic>] <Json|@JsonFile> [ClientIni]
|
PushMessage [-t <Topic>] [-a <File>] <Json|@JsonFile> [ClientIni]
|
||||||
GetLatestMessage <Topic> <Node> [ClientIni]
|
GetLatestMessage <Topic> <Node> [ClientIni]
|
||||||
GetMessages <Topic> <Node> [--after <Id|latest>] [--limit <N>] [--follow] [--interval <Ms>] [ClientIni]
|
GetMessages <Topic> <Node> [--after <Id|latest>] [--limit <N>] [--follow] [--interval <Ms>] [--time] [ClientIni]
|
||||||
|
GetAttachment <Topic> <Node> <MessageId> <OutFile> [ClientIni]
|
||||||
Resolve <topic|node> <NameOrId> [ClientIni]
|
Resolve <topic|node> <NameOrId> [ClientIni]
|
||||||
ListNames [topics|nodes|all] [ClientIni] [--json]
|
ListNames [topics|nodes|all] [ClientIni] [--json]
|
||||||
Query <Sql|@SqlFile> [ClientIni] e.g. SELECT * FROM messages WHERE topic = 'logs'
|
Query <Sql|@SqlFile> [ClientIni] e.g. SELECT * FROM messages WHERE topic = 'logs'
|
||||||
@@ -310,6 +312,19 @@ ServerPublicKey = $($ServerKeys.PublicKey)
|
|||||||
else {
|
else {
|
||||||
Write-Host " No python on the PATH, the Python client wasn't checked"
|
Write-Host " No python on the PATH, the Python client wasn't checked"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# An attachment of 3 parts and a bit, up and back.
|
||||||
|
$Attach = Join-Path $TestDir "attach.bin"
|
||||||
|
$Bytes = New-Object byte[] (3 * 1024 * 1024 + 17)
|
||||||
|
(New-Object System.Random 5).NextBytes($Bytes)
|
||||||
|
[IO.File]::WriteAllBytes($Attach, $Bytes)
|
||||||
|
$Pushed = Invoke-Tool "PushMessage.exe" @("-a", $Attach, "@$(Join-Path $TestDir 'message.json')", $ClientIni)
|
||||||
|
if ($Pushed -notmatch "message #(\d+), with an attachment of 3145745 bytes") { throw "Unexpected push with an attachment: $Pushed" }
|
||||||
|
$AttachedId = $Matches[1]
|
||||||
|
$Copy = Join-Path $TestDir "attach-copy.bin"
|
||||||
|
$Saved = Invoke-Tool "GetAttachment.exe" @("releasetest", "tester", $AttachedId, $Copy, $ClientIni)
|
||||||
|
if ($Saved -notmatch "Saved 3145745 bytes" -or (Get-FileHash $Attach).Hash -ne (Get-FileHash $Copy).Hash) { throw "Unexpected attachment read back: $Saved" }
|
||||||
|
Write-Host " Pushed and read back an attachment: OK"
|
||||||
}
|
}
|
||||||
finally {
|
finally {
|
||||||
if ($Server -and -not $Server.HasExited) {
|
if ($Server -and -not $Server.HasExited) {
|
||||||
|
|||||||
@@ -34,6 +34,8 @@
|
|||||||
; ============================================================================
|
; ============================================================================
|
||||||
|
|
||||||
XIncludeFile "../../Commons/Networking/Names.pbi"
|
XIncludeFile "../../Commons/Networking/Names.pbi"
|
||||||
|
; #BakaShrot_MaxAttachmentSize.
|
||||||
|
XIncludeFile "../../Commons/Networking/Packets.pbi"
|
||||||
|
|
||||||
|
|
||||||
; Some topics or nodes, or all of them: what a topic list (or node list)
|
; Some topics or nodes, or all of them: what a topic list (or node list)
|
||||||
@@ -228,6 +230,16 @@ Structure BakaShrot_ServerConfig
|
|||||||
; max age ([BakaShrot.Retention]). Default 60.
|
; max age ([BakaShrot.Retention]). Default 60.
|
||||||
RetentionInterval.i
|
RetentionInterval.i
|
||||||
|
|
||||||
|
; Biggest attachment this server takes, in bytes: pushed with a message,
|
||||||
|
; or replicated (a bigger one's message is kept, not its attachment).
|
||||||
|
; Written with a unit: 500M, 1G (K M G T, 1024-based). Default 1G.
|
||||||
|
MaxAttachmentSize.q
|
||||||
|
MaxAttachmentSizeText.s
|
||||||
|
|
||||||
|
; Seconds an upload may take, before it's pushed with its message: past
|
||||||
|
; that it's deleted. Default 3600.
|
||||||
|
UploadTimeout.i
|
||||||
|
|
||||||
EndStructure
|
EndStructure
|
||||||
|
|
||||||
|
|
||||||
@@ -283,6 +295,8 @@ Macro Ptr_BakaShrot_CoreConfig : i : EndMacro
|
|||||||
#BakaShrot_Config_DefaultPeerSyncInterval = 5
|
#BakaShrot_Config_DefaultPeerSyncInterval = 5
|
||||||
#BakaShrot_Config_DefaultPeerBatchSize = 100
|
#BakaShrot_Config_DefaultPeerBatchSize = 100
|
||||||
#BakaShrot_Config_DefaultRetentionInterval = 60
|
#BakaShrot_Config_DefaultRetentionInterval = 60
|
||||||
|
#BakaShrot_Config_DefaultMaxAttachmentSize = "1G"
|
||||||
|
#BakaShrot_Config_DefaultUploadTimeout = 3600
|
||||||
|
|
||||||
; What ReadPreferenceString() returns for a missing key, to tell it from an
|
; What ReadPreferenceString() returns for a missing key, to tell it from an
|
||||||
; empty one: an empty PushTopics allows nothing, a missing one the default.
|
; empty one: an empty PushTopics allows nothing, a missing one the default.
|
||||||
@@ -422,6 +436,38 @@ Procedure.q ParseRetentionAge(Text.s)
|
|||||||
EndProcedure
|
EndProcedure
|
||||||
|
|
||||||
|
|
||||||
|
; A size as MaxAttachmentSize writes it ("500M", "1G", "1048576") in bytes,
|
||||||
|
; -1 if it isn't one. Units are 1024-based: K M G T.
|
||||||
|
Procedure.q ParseConfigSize(Text.s)
|
||||||
|
Protected Unit.q = 1, Digits.s, Last.s, i.i
|
||||||
|
|
||||||
|
Text = UCase(Trim(Text))
|
||||||
|
If Text = ""
|
||||||
|
ProcedureReturn -1
|
||||||
|
EndIf
|
||||||
|
Last = Right(Text, 1)
|
||||||
|
Select Last
|
||||||
|
Case "K" : Unit = 1024
|
||||||
|
Case "M" : Unit = 1024 * 1024
|
||||||
|
Case "G" : Unit = 1024 * 1024 * 1024
|
||||||
|
Case "T" : Unit = 1024 * 1024 * 1024 * 1024
|
||||||
|
EndSelect
|
||||||
|
Digits = Text
|
||||||
|
If Unit > 1
|
||||||
|
Digits = Left(Text, Len(Text) - 1)
|
||||||
|
EndIf
|
||||||
|
If Digits = "" Or Len(Digits) > 13
|
||||||
|
ProcedureReturn -1
|
||||||
|
EndIf
|
||||||
|
For i = 1 To Len(Digits)
|
||||||
|
If Mid(Digits, i, 1) < "0" Or Mid(Digits, i, 1) > "9"
|
||||||
|
ProcedureReturn -1
|
||||||
|
EndIf
|
||||||
|
Next
|
||||||
|
ProcedureReturn Val(Digits) * Unit
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
|
||||||
; Reads [BakaShrot.Retention] into *Config\Retention().
|
; Reads [BakaShrot.Retention] into *Config\Retention().
|
||||||
; Returns #False on an invalid line, with the reason in BakaShrot_ConfigError.
|
; Returns #False on an invalid line, with the reason in BakaShrot_ConfigError.
|
||||||
Procedure.i ParseRetentionSection(*Config.BakaShrot_CoreConfig)
|
Procedure.i ParseRetentionSection(*Config.BakaShrot_CoreConfig)
|
||||||
@@ -835,6 +881,17 @@ Procedure.Ptr_BakaShrot_CoreConfig LoadConfig(IniFilePath.s)
|
|||||||
BakaShrot_ConfigError = "[BakaShrot.Server] RetentionInterval must be 1 second or more"
|
BakaShrot_ConfigError = "[BakaShrot.Server] RetentionInterval must be 1 second or more"
|
||||||
Goto LoadFailed
|
Goto LoadFailed
|
||||||
EndIf
|
EndIf
|
||||||
|
*Config\Server\MaxAttachmentSizeText = Trim(ReadPreferenceString("MaxAttachmentSize", #BakaShrot_Config_DefaultMaxAttachmentSize))
|
||||||
|
*Config\Server\MaxAttachmentSize = ParseConfigSize(*Config\Server\MaxAttachmentSizeText)
|
||||||
|
If *Config\Server\MaxAttachmentSize < 0 Or *Config\Server\MaxAttachmentSize > #BakaShrot_MaxAttachmentSize
|
||||||
|
BakaShrot_ConfigError = "[BakaShrot.Server] MaxAttachmentSize = '" + *Config\Server\MaxAttachmentSizeText + "' isn't a size up to 1T: bytes, or a number with K, M, G or T, like 500M (0: no attachments)"
|
||||||
|
Goto LoadFailed
|
||||||
|
EndIf
|
||||||
|
*Config\Server\UploadTimeout = ReadPreferenceLong("UploadTimeout", #BakaShrot_Config_DefaultUploadTimeout)
|
||||||
|
If *Config\Server\UploadTimeout < 10
|
||||||
|
BakaShrot_ConfigError = "[BakaShrot.Server] UploadTimeout must be 10 seconds or more"
|
||||||
|
Goto LoadFailed
|
||||||
|
EndIf
|
||||||
*Config\Server\ReplicatingTopicsText = ReadConfigKey("ReplicatingTopics", "ReplicatingTopicIds", "")
|
*Config\Server\ReplicatingTopicsText = ReadConfigKey("ReplicatingTopics", "ReplicatingTopicIds", "")
|
||||||
If Not ParseTopicSet(*Config, *Config\Server\ReplicatingTopicsText, @*Config\Server\ReplicatingTopics, "[BakaShrot.Server] ReplicatingTopics")
|
If Not ParseTopicSet(*Config, *Config\Server\ReplicatingTopicsText, @*Config\Server\ReplicatingTopics, "[BakaShrot.Server] ReplicatingTopics")
|
||||||
Goto LoadFailed
|
Goto LoadFailed
|
||||||
@@ -997,6 +1054,8 @@ Procedure.i SaveConfig(IniFilePath.s, *Config.BakaShrot_CoreConfig)
|
|||||||
WritePreferenceLong("PeerSyncInterval", *Config\Server\PeerSyncInterval)
|
WritePreferenceLong("PeerSyncInterval", *Config\Server\PeerSyncInterval)
|
||||||
WritePreferenceLong("PeerBatchSize", *Config\Server\PeerBatchSize)
|
WritePreferenceLong("PeerBatchSize", *Config\Server\PeerBatchSize)
|
||||||
WritePreferenceLong("RetentionInterval", *Config\Server\RetentionInterval)
|
WritePreferenceLong("RetentionInterval", *Config\Server\RetentionInterval)
|
||||||
|
WritePreferenceString("MaxAttachmentSize", *Config\Server\MaxAttachmentSizeText)
|
||||||
|
WritePreferenceLong("UploadTimeout", *Config\Server\UploadTimeout)
|
||||||
|
|
||||||
PreferenceGroup("BakaShrot.Topics")
|
PreferenceGroup("BakaShrot.Topics")
|
||||||
ForEach *Config\TopicNames()
|
ForEach *Config\TopicNames()
|
||||||
|
|||||||
@@ -102,9 +102,18 @@ PeerSyncInterval = 5
|
|||||||
PeerBatchSize = 100
|
PeerBatchSize = 100
|
||||||
|
|
||||||
; Seconds between two passes deleting the messages past their topic's age
|
; Seconds between two passes deleting the messages past their topic's age
|
||||||
; ([BakaShrot.Retention] above). Only runs if a topic has one.
|
; ([BakaShrot.Retention] above), and the attachments' leftovers.
|
||||||
RetentionInterval = 60
|
RetentionInterval = 60
|
||||||
|
|
||||||
|
; Biggest attachment this server takes (one per message, see
|
||||||
|
; Design/Attachments.md): pushed to it, or replicated (a bigger one's message
|
||||||
|
; is kept, its attachment isn't). Bytes, or K M G T (1024-based). 0: none.
|
||||||
|
MaxAttachmentSize = 1G
|
||||||
|
|
||||||
|
; Seconds a client may take to upload an attachment and push its message,
|
||||||
|
; after which the upload is deleted.
|
||||||
|
UploadTimeout = 3600
|
||||||
|
|
||||||
|
|
||||||
; One [BakaShrot.Peer.<name>] section per peer this node talks to.
|
; One [BakaShrot.Peer.<name>] section per peer this node talks to.
|
||||||
; <name> is only a key for this file; it is never sent on the wire.
|
; <name> is only a key for this file; it is never sent on the wire.
|
||||||
|
|||||||
@@ -17,10 +17,12 @@
|
|||||||
;
|
;
|
||||||
; Once authenticated, a client's thread answers its requests one at a time
|
; Once authenticated, a client's thread answers its requests one at a time
|
||||||
; until it disconnects: PushMessage, GetLatestMessage, GetMessages,
|
; until it disconnects: PushMessage, GetLatestMessage, GetMessages,
|
||||||
; QueryRequest, ResolveName and ListNames, each one only if its
|
; QueryRequest, ResolveName and ListNames, UploadStart, UploadChunk and
|
||||||
|
; GetAttachment (Design/Attachments.md), each one only if its
|
||||||
; [BakaShrot.Client.<name>] allows it (AllowWrite and PushTopics, AllowRead
|
; [BakaShrot.Client.<name>] allows it (AllowWrite and PushTopics, AllowRead
|
||||||
; and ReadTopics, AllowQuery), and for
|
; and ReadTopics, AllowQuery), and for
|
||||||
; peers, SyncStateRequest and ReplicateMessages, refused for regular clients,
|
; peers, SyncStateRequest and ReplicateMessages, then MissingAttachmentsRequest
|
||||||
|
; and ReplicateAttachmentChunk, refused for regular clients,
|
||||||
; within the peer's AcceptTopics and AcceptNodes. Any other packet aborts it.
|
; within the peer's AcceptTopics and AcceptNodes. Any other packet aborts it.
|
||||||
;
|
;
|
||||||
; Topics and nodes come by name or id (Commons/Networking/Names.pbi), and
|
; Topics and nodes come by name or id (Commons/Networking/Names.pbi), and
|
||||||
@@ -421,7 +423,8 @@ EndProcedure
|
|||||||
Procedure.i BakaShrot_NetClient_HandlePushMessage(*Client.BakaShrot_NetClient, *Packet, PacketSize.i)
|
Procedure.i BakaShrot_NetClient_HandlePushMessage(*Client.BakaShrot_NetClient, *Packet, PacketSize.i)
|
||||||
Protected *View.MsgPackData, *Push.BakaShrot_PushMessage
|
Protected *View.MsgPackData, *Push.BakaShrot_PushMessage
|
||||||
Protected Pushed.BakaShrot_MessagePushed
|
Protected Pushed.BakaShrot_MessagePushed
|
||||||
Protected JsonData.s, TopicRef.s, TopicId.i, JsonSize.i, MessageId.q, StoreError.String
|
Protected JsonData.s, TopicRef.s, TopicId.i, JsonSize.i, MessageId.q, StoreError.String, UploadId.q
|
||||||
|
Protected Blob.BakaShrot_StorageBlob
|
||||||
Protected *Answer, AnswerSize.Integer, Sent.i
|
Protected *Answer, AnswerSize.Integer, Sent.i
|
||||||
|
|
||||||
*Push = 0
|
*Push = 0
|
||||||
@@ -436,6 +439,7 @@ Procedure.i BakaShrot_NetClient_HandlePushMessage(*Client.BakaShrot_NetClient, *
|
|||||||
EndIf
|
EndIf
|
||||||
JsonData = *Push\JsonData
|
JsonData = *Push\JsonData
|
||||||
TopicRef = *Push\Topic
|
TopicRef = *Push\Topic
|
||||||
|
UploadId = *Push\UploadId
|
||||||
FreeStructure(*Push)
|
FreeStructure(*Push)
|
||||||
|
|
||||||
; The node is the authenticated one, the client never sends it here.
|
; The node is the authenticated one, the client never sends it here.
|
||||||
@@ -473,7 +477,20 @@ Procedure.i BakaShrot_NetClient_HandlePushMessage(*Client.BakaShrot_NetClient, *
|
|||||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The message couldn't be stored")
|
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The message couldn't be stored")
|
||||||
EndIf
|
EndIf
|
||||||
|
|
||||||
MessageId = InsertNextMessage(TopicId, *Client\Metadata\NodeId, JsonData, @StoreError)
|
; Its attachment: one of this client's complete uploads, for that topic.
|
||||||
|
If UploadId
|
||||||
|
If Not GetStorageBlob(*Client\DbId, UploadId, @Blob) Or Blob\NodeId <> *Client\Metadata\NodeId
|
||||||
|
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "No such upload")
|
||||||
|
EndIf
|
||||||
|
If Blob\State <> #BakaShrot_Blob_Complete
|
||||||
|
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The upload isn't complete, or is attached already")
|
||||||
|
EndIf
|
||||||
|
If Blob\TopicId <> TopicId
|
||||||
|
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The upload is for topic '" + BakaShrot_Names_TopicRef(Blob\TopicId) + "'")
|
||||||
|
EndIf
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
MessageId = InsertNextMessage(TopicId, *Client\Metadata\NodeId, JsonData, @StoreError, UploadId)
|
||||||
If MessageId < 1
|
If MessageId < 1
|
||||||
PrintN("[Net] Failed to store a message from client " + Str(*Client\ClientId) + ": " + StoreError\s)
|
PrintN("[Net] Failed to store a message from client " + Str(*Client\ClientId) + ": " + StoreError\s)
|
||||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The message couldn't be stored")
|
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The message couldn't be stored")
|
||||||
@@ -551,6 +568,8 @@ Procedure.i BakaShrot_NetClient_HandleGetLatestMessage(*Client.BakaShrot_NetClie
|
|||||||
Latest\MessageId = Message\MessageId
|
Latest\MessageId = Message\MessageId
|
||||||
Latest\PushedAt = Message\PushedAt
|
Latest\PushedAt = Message\PushedAt
|
||||||
Latest\JsonData = Message\JsonData
|
Latest\JsonData = Message\JsonData
|
||||||
|
Latest\AttachmentSize = Message\AttachmentSize
|
||||||
|
Latest\AttachmentReady = Message\AttachmentReady
|
||||||
*Answer = BakaShrot_LatestMessagePacket_Encode(@Latest, @AnswerSize)
|
*Answer = BakaShrot_LatestMessagePacket_Encode(@Latest, @AnswerSize)
|
||||||
If Not *Answer
|
If Not *Answer
|
||||||
ProcedureReturn #False
|
ProcedureReturn #False
|
||||||
@@ -636,6 +655,8 @@ Procedure.i BakaShrot_NetClient_HandleGetMessages(*Client.BakaShrot_NetClient, *
|
|||||||
Answer\Messages()\MessageId = Messages()\MessageId
|
Answer\Messages()\MessageId = Messages()\MessageId
|
||||||
Answer\Messages()\PushedAt = Messages()\PushedAt
|
Answer\Messages()\PushedAt = Messages()\PushedAt
|
||||||
Answer\Messages()\JsonData = Messages()\JsonData
|
Answer\Messages()\JsonData = Messages()\JsonData
|
||||||
|
Answer\Messages()\AttachmentSize = Messages()\AttachmentSize
|
||||||
|
Answer\Messages()\AttachmentReady = Messages()\AttachmentReady
|
||||||
Next
|
Next
|
||||||
ClearList(Messages())
|
ClearList(Messages())
|
||||||
|
|
||||||
@@ -975,7 +996,7 @@ Procedure.i BakaShrot_NetClient_HandleReplicateMessages(*Client.BakaShrot_NetCli
|
|||||||
If MaxAge > 0
|
If MaxAge > 0
|
||||||
SkipBefore = BakaShrot_NowUtcMs() - MaxAge
|
SkipBefore = BakaShrot_NowUtcMs() - MaxAge
|
||||||
EndIf
|
EndIf
|
||||||
IsStored = InsertReplicatedMessages(TopicId, NodeId, *Batch\Messages(), @StoreError, SkipBefore, @Skipped)
|
IsStored = InsertReplicatedMessages(TopicId, NodeId, *Batch\Messages(), @StoreError, SkipBefore, @Skipped, *Client\Server\Config\Server\MaxAttachmentSize)
|
||||||
FreeStructure(*Batch)
|
FreeStructure(*Batch)
|
||||||
If #BakaShrot_Net_LogRequests And Skipped\i > 0
|
If #BakaShrot_Net_LogRequests And Skipped\i > 0
|
||||||
PrintN("[Net] Skipped " + Str(Skipped\i) + " messages of " + TopicRef + ":" + NodeRef + " from peer '" + *Client\PeerName + "', past their max age here")
|
PrintN("[Net] Skipped " + Str(Skipped\i) + " messages of " + TopicRef + ":" + NodeRef + " from peer '" + *Client\PeerName + "', past their max age here")
|
||||||
@@ -996,6 +1017,358 @@ Procedure.i BakaShrot_NetClient_HandleReplicateMessages(*Client.BakaShrot_NetCli
|
|||||||
ProcedureReturn Sent
|
ProcedureReturn Sent
|
||||||
EndProcedure
|
EndProcedure
|
||||||
|
|
||||||
|
; --- Attachments -----------------------------------------------------------------
|
||||||
|
; See Design/Attachments.md and Storage/Attachments.pbi.
|
||||||
|
|
||||||
|
; Sends a ChunkStored. Returns #False if it couldn't be sent.
|
||||||
|
Procedure.i BakaShrot_NetClient_SendChunkStored(*Client.BakaShrot_NetClient, Received.q, Complete.i)
|
||||||
|
Protected Stored.BakaShrot_ChunkStored, *Answer, AnswerSize.Integer, Sent.i
|
||||||
|
|
||||||
|
Stored\Received = Received
|
||||||
|
Stored\Complete = Complete
|
||||||
|
*Answer = BakaShrot_ChunkStoredPacket_Encode(@Stored, @AnswerSize)
|
||||||
|
If Not *Answer
|
||||||
|
ProcedureReturn #False
|
||||||
|
EndIf
|
||||||
|
Sent = BakaShrot_SendPacket(*Client\ClientId, *Answer, AnswerSize\i, @*Client\Metadata\Cipher)
|
||||||
|
FreeMemory(*Answer)
|
||||||
|
ProcedureReturn Sent
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
|
||||||
|
; Starts an upload, for a message the client will push to that topic.
|
||||||
|
; Same permissions as pushing, and at most MaxAttachmentSize bytes.
|
||||||
|
; Returns #False if the client must be aborted.
|
||||||
|
Procedure.i BakaShrot_NetClient_HandleUploadStart(*Client.BakaShrot_NetClient, *Packet, PacketSize.i)
|
||||||
|
Protected *View.MsgPackData, *Start.BakaShrot_UploadStart
|
||||||
|
Protected Started.BakaShrot_UploadStarted
|
||||||
|
Protected TopicRef.s, TopicId.i, Size.q, MaxSize.q, BlobId.q, StoreError.String
|
||||||
|
Protected Dim Sha256.a(#BakaShrot_Sha256Size - 1)
|
||||||
|
Protected *Answer, AnswerSize.Integer, Sent.i
|
||||||
|
|
||||||
|
*Start = 0
|
||||||
|
*View = MsgPackWrapMsgBuffer(*Packet, PacketSize)
|
||||||
|
If *View
|
||||||
|
*Start = BakaShrot_UploadStartPacket_Decode(*View)
|
||||||
|
MsgPackFree(*View, #False)
|
||||||
|
EndIf
|
||||||
|
If Not *Start
|
||||||
|
PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an invalid upload start")
|
||||||
|
ProcedureReturn #False
|
||||||
|
EndIf
|
||||||
|
TopicRef = *Start\Topic
|
||||||
|
Size = *Start\Size
|
||||||
|
CopyMemory(@*Start\Sha256[0], @Sha256(0), #BakaShrot_Sha256Size)
|
||||||
|
FreeStructure(*Start)
|
||||||
|
|
||||||
|
If Not *Client\Permissions\Write
|
||||||
|
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to write")
|
||||||
|
EndIf
|
||||||
|
If TopicRef = ""
|
||||||
|
TopicId = *Client\Metadata\TopicId
|
||||||
|
Else
|
||||||
|
TopicId = BakaShrot_Names_ResolveTopic(TopicRef)
|
||||||
|
If TopicId < 0
|
||||||
|
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown topic '" + Left(TopicRef, 80) + "'")
|
||||||
|
EndIf
|
||||||
|
EndIf
|
||||||
|
If Not NameSetHas(@*Client\PushTopics, TopicId, BakaShrot_Names_TopicName(TopicId))
|
||||||
|
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to push to topic '" + BakaShrot_Names_TopicRef(TopicId) + "'")
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
MaxSize = *Client\Server\Config\Server\MaxAttachmentSize
|
||||||
|
If Size > MaxSize
|
||||||
|
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The attachment is too big: " + Str(Size) + " bytes, at most " + Str(MaxSize) + " here")
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
BlobId = CreateStorageBlob(TopicId, *Client\Metadata\NodeId, Size, @Sha256(0), @StoreError)
|
||||||
|
If Not BlobId
|
||||||
|
PrintN("[Net] Failed to start an upload for client " + Str(*Client\ClientId) + ": " + StoreError\s)
|
||||||
|
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The upload couldn't be started")
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
Started\UploadId = BlobId
|
||||||
|
Started\ChunkSize = #BakaShrot_AttachmentChunkSize
|
||||||
|
*Answer = BakaShrot_UploadStartedPacket_Encode(@Started, @AnswerSize)
|
||||||
|
If Not *Answer
|
||||||
|
ProcedureReturn #False
|
||||||
|
EndIf
|
||||||
|
Sent = BakaShrot_SendPacket(*Client\ClientId, *Answer, AnswerSize\i, @*Client\Metadata\Cipher)
|
||||||
|
FreeMemory(*Answer)
|
||||||
|
ProcedureReturn Sent
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
|
||||||
|
; Stores the next part of one of this client's uploads. Once all of it is
|
||||||
|
; here, checks its SHA-256: complete, or dropped and refused.
|
||||||
|
; Returns #False if the client must be aborted.
|
||||||
|
Procedure.i BakaShrot_NetClient_HandleUploadChunk(*Client.BakaShrot_NetClient, *Packet, PacketSize.i)
|
||||||
|
Protected *View.MsgPackData, *Chunk.BakaShrot_UploadChunk
|
||||||
|
Protected Blob.BakaShrot_StorageBlob, Received.q, StoreError.String, Expected.i
|
||||||
|
|
||||||
|
*Chunk = 0
|
||||||
|
*View = MsgPackWrapMsgBuffer(*Packet, PacketSize)
|
||||||
|
If *View
|
||||||
|
*Chunk = BakaShrot_UploadChunkPacket_Decode(*View)
|
||||||
|
MsgPackFree(*View, #False)
|
||||||
|
EndIf
|
||||||
|
If Not *Chunk
|
||||||
|
PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an invalid upload chunk")
|
||||||
|
ProcedureReturn #False
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; Only its own uploads: same node, a topic it may still push to.
|
||||||
|
If Not GetStorageBlob(*Client\DbId, *Chunk\UploadId, @Blob) Or Blob\NodeId <> *Client\Metadata\NodeId Or Blob\State <> #BakaShrot_Blob_Receiving
|
||||||
|
BakaShrot_UploadChunkPacket_Free(*Chunk)
|
||||||
|
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "No such upload in progress")
|
||||||
|
EndIf
|
||||||
|
If Not *Client\Permissions\Write Or Not NameSetHas(@*Client\PushTopics, Blob\TopicId, BakaShrot_Names_TopicName(Blob\TopicId))
|
||||||
|
BakaShrot_UploadChunkPacket_Free(*Chunk)
|
||||||
|
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to push to topic '" + BakaShrot_Names_TopicRef(Blob\TopicId) + "'")
|
||||||
|
EndIf
|
||||||
|
Expected = BakaShrot_AttachmentChunkBytes(Blob\Size, *Chunk\ChunkIndex)
|
||||||
|
If *Chunk\ChunkIndex * #BakaShrot_AttachmentChunkSize <> Blob\Received Or *Chunk\DataSize <> Expected
|
||||||
|
BakaShrot_UploadChunkPacket_Free(*Chunk)
|
||||||
|
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Expected part " + Str(Blob\Received / #BakaShrot_AttachmentChunkSize) + " of " + Str(BakaShrot_AttachmentChunkCount(Blob\Size)) + ", " + Str(BakaShrot_AttachmentChunkBytes(Blob\Size, Blob\Received / #BakaShrot_AttachmentChunkSize)) + " bytes")
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
Received = StoreStorageBlobChunk(Blob\BlobId, *Chunk\ChunkIndex, *Chunk\Data, *Chunk\DataSize, @StoreError)
|
||||||
|
BakaShrot_UploadChunkPacket_Free(*Chunk)
|
||||||
|
If Received < 0
|
||||||
|
PrintN("[Net] Failed to store a part of an upload from client " + Str(*Client\ClientId) + ": " + StoreError\s)
|
||||||
|
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The part couldn't be stored")
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If Received < Blob\Size
|
||||||
|
ProcedureReturn BakaShrot_NetClient_SendChunkStored(*Client, Received, #False)
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; All of it: the SHA-256 given at the start must match.
|
||||||
|
If Not HashStorageBlob(*Client\DbId, Blob\BlobId, Blob\Size, @Blob\Sha256[0])
|
||||||
|
SetStorageBlobState(Blob\BlobId, #BakaShrot_Blob_Deleted)
|
||||||
|
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The upload doesn't match its SHA-256, it's dropped")
|
||||||
|
EndIf
|
||||||
|
If Not SetStorageBlobState(Blob\BlobId, #BakaShrot_Blob_Complete)
|
||||||
|
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The upload couldn't be stored")
|
||||||
|
EndIf
|
||||||
|
ProcedureReturn BakaShrot_NetClient_SendChunkStored(*Client, Received, #True)
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
|
||||||
|
; Answers with a part of a message's attachment, same permissions as
|
||||||
|
; reading the message. Refuses one that isn't all here yet.
|
||||||
|
; Returns #False if the client must be aborted.
|
||||||
|
Procedure.i BakaShrot_NetClient_HandleGetAttachment(*Client.BakaShrot_NetClient, *Packet, PacketSize.i)
|
||||||
|
Protected *View.MsgPackData, *Request.BakaShrot_GetAttachment
|
||||||
|
Protected Chunk.BakaShrot_AttachmentChunk, Attachment.BakaShrot_StorageAttachment
|
||||||
|
Protected TopicId.i, NodeId.i, TopicRef.s, NodeRef.s, MessageId.q, Index.q, DataSize.Integer
|
||||||
|
Protected *Answer, AnswerSize.Integer, Sent.i
|
||||||
|
|
||||||
|
*Request = 0
|
||||||
|
*View = MsgPackWrapMsgBuffer(*Packet, PacketSize)
|
||||||
|
If *View
|
||||||
|
*Request = BakaShrot_GetAttachmentPacket_Decode(*View)
|
||||||
|
MsgPackFree(*View, #False)
|
||||||
|
EndIf
|
||||||
|
If Not *Request
|
||||||
|
PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an invalid attachment request")
|
||||||
|
ProcedureReturn #False
|
||||||
|
EndIf
|
||||||
|
TopicRef = *Request\Topic
|
||||||
|
NodeRef = *Request\Node
|
||||||
|
MessageId = *Request\MessageId
|
||||||
|
Index = *Request\ChunkIndex
|
||||||
|
FreeStructure(*Request)
|
||||||
|
|
||||||
|
If Not *Client\Permissions\Read
|
||||||
|
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to read")
|
||||||
|
EndIf
|
||||||
|
TopicId = BakaShrot_Names_ResolveTopic(TopicRef)
|
||||||
|
If TopicId < 0
|
||||||
|
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown topic '" + Left(TopicRef, 80) + "'")
|
||||||
|
EndIf
|
||||||
|
If Not NameSetHas(@*Client\ReadTopics, TopicId, BakaShrot_Names_TopicName(TopicId))
|
||||||
|
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to read topic '" + BakaShrot_Names_TopicRef(TopicId) + "'")
|
||||||
|
EndIf
|
||||||
|
NodeId = BakaShrot_Names_ResolveNode(NodeRef)
|
||||||
|
If NodeId < 0
|
||||||
|
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown node '" + Left(NodeRef, 80) + "'")
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If Not GetStorageAttachment(*Client\DbId, TopicId, NodeId, MessageId, @Attachment)
|
||||||
|
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "No attachment for " + BakaShrot_Names_TopicRef(TopicId) + ":" + BakaShrot_Names_NodeRef(NodeId) + "#" + Str(MessageId))
|
||||||
|
EndIf
|
||||||
|
Select Attachment\State
|
||||||
|
Case #BakaShrot_Attachment_NotKept
|
||||||
|
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The attachment isn't kept here: " + Str(Attachment\Size) + " bytes, more than MaxAttachmentSize")
|
||||||
|
Case #BakaShrot_Attachment_Missing, #BakaShrot_Attachment_Receiving
|
||||||
|
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The attachment isn't here yet: " + Str(Attachment\Received) + " of " + Str(Attachment\Size) + " bytes")
|
||||||
|
EndSelect
|
||||||
|
If Index >= BakaShrot_AttachmentChunkCount(Attachment\Size)
|
||||||
|
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The attachment has " + Str(BakaShrot_AttachmentChunkCount(Attachment\Size)) + " parts")
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
Chunk\Data = ReadStorageBlobChunk(*Client\DbId, Attachment\BlobId, Index, @DataSize)
|
||||||
|
If Not Chunk\Data
|
||||||
|
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The attachment couldn't be read")
|
||||||
|
EndIf
|
||||||
|
Chunk\DataSize = DataSize\i
|
||||||
|
Chunk\TopicId = TopicId
|
||||||
|
Chunk\NodeId = NodeId
|
||||||
|
Chunk\MessageId = MessageId
|
||||||
|
Chunk\Size = Attachment\Size
|
||||||
|
Chunk\ChunkIndex = Index
|
||||||
|
CopyMemory(@Attachment\Sha256[0], @Chunk\Sha256[0], #BakaShrot_Sha256Size)
|
||||||
|
*Answer = BakaShrot_AttachmentChunkPacket_Encode(@Chunk, @AnswerSize)
|
||||||
|
FreeMemory(Chunk\Data)
|
||||||
|
If Not *Answer
|
||||||
|
ProcedureReturn #False
|
||||||
|
EndIf
|
||||||
|
Sent = BakaShrot_SendPacket(*Client\ClientId, *Answer, AnswerSize\i, @*Client\Metadata\Cipher)
|
||||||
|
FreeMemory(*Answer)
|
||||||
|
ProcedureReturn Sent
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
|
||||||
|
; Tells a peer which attachments this server is missing, among what it
|
||||||
|
; takes from it (AcceptTopics, AcceptNodes): the peer sends what it has.
|
||||||
|
; Returns #False if the client must be aborted.
|
||||||
|
Procedure.i BakaShrot_NetClient_HandleMissingAttachmentsRequest(*Client.BakaShrot_NetClient, *Packet, PacketSize.i)
|
||||||
|
Protected *View.MsgPackData, *Request.BakaShrot_MissingAttachmentsRequest
|
||||||
|
Protected Answer.BakaShrot_MissingAttachments
|
||||||
|
Protected NewList Missing.BakaShrot_StorageMissingAttachment()
|
||||||
|
Protected *Answer, AnswerSize.Integer, Sent.i
|
||||||
|
|
||||||
|
*Request = 0
|
||||||
|
*View = MsgPackWrapMsgBuffer(*Packet, PacketSize)
|
||||||
|
If *View
|
||||||
|
*Request = BakaShrot_MissingAttachmentsRequestPacket_Decode(*View)
|
||||||
|
MsgPackFree(*View, #False)
|
||||||
|
EndIf
|
||||||
|
If Not *Request
|
||||||
|
PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an invalid missing attachments request")
|
||||||
|
ProcedureReturn #False
|
||||||
|
EndIf
|
||||||
|
FreeStructure(*Request)
|
||||||
|
|
||||||
|
If *Client\PeerName = ""
|
||||||
|
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Only peers can replicate")
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; More than one answer holds, some of them may be someone else's.
|
||||||
|
If Not GetMissingStorageAttachments(*Client\DbId, 4 * #BakaShrot_MaxMissingAttachments, Missing())
|
||||||
|
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The missing attachments couldn't be read")
|
||||||
|
EndIf
|
||||||
|
ForEach Missing()
|
||||||
|
If ListSize(Answer\Attachments()) >= #BakaShrot_MaxMissingAttachments
|
||||||
|
Break
|
||||||
|
EndIf
|
||||||
|
If Not NameSetHas(@*Client\AcceptTopics, Missing()\TopicId, Missing()\Topic) Or Not NameSetHas(@*Client\AcceptNodes, Missing()\NodeId, Missing()\Node)
|
||||||
|
Continue
|
||||||
|
EndIf
|
||||||
|
If Not BakaShrot_IsValidName(Missing()\Topic) Or Not BakaShrot_IsValidName(Missing()\Node)
|
||||||
|
Continue
|
||||||
|
EndIf
|
||||||
|
AddElement(Answer\Attachments())
|
||||||
|
Answer\Attachments()\Topic = Missing()\Topic
|
||||||
|
Answer\Attachments()\Node = Missing()\Node
|
||||||
|
Answer\Attachments()\MessageId = Missing()\MessageId
|
||||||
|
Answer\Attachments()\NextChunk = Missing()\Received / #BakaShrot_AttachmentChunkSize
|
||||||
|
Next
|
||||||
|
|
||||||
|
*Answer = BakaShrot_MissingAttachmentsPacket_Encode(@Answer, @AnswerSize)
|
||||||
|
If Not *Answer
|
||||||
|
ProcedureReturn #False
|
||||||
|
EndIf
|
||||||
|
Sent = BakaShrot_SendPacket(*Client\ClientId, *Answer, AnswerSize\i, @*Client\Metadata\Cipher)
|
||||||
|
FreeMemory(*Answer)
|
||||||
|
ProcedureReturn Sent
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
|
||||||
|
; Stores a part of an attachment a peer replicates, of a message this server
|
||||||
|
; already has: in order, resuming where a previous link stopped. Once all of
|
||||||
|
; it is here, checks its SHA-256 (the one its message came with): ready, or
|
||||||
|
; dropped to be sent again.
|
||||||
|
; Returns #False if the client must be aborted.
|
||||||
|
Procedure.i BakaShrot_NetClient_HandleReplicateAttachmentChunk(*Client.BakaShrot_NetClient, *Packet, PacketSize.i)
|
||||||
|
Protected *View.MsgPackData, *Chunk.BakaShrot_ReplicateAttachmentChunk
|
||||||
|
Protected Attachment.BakaShrot_StorageAttachment
|
||||||
|
Protected TopicId.i, NodeId.i, TopicRef.s, NodeRef.s, MessageId.q, BlobId.q, Received.q, IsValid.i, StoreError.String
|
||||||
|
|
||||||
|
*Chunk = 0
|
||||||
|
*View = MsgPackWrapMsgBuffer(*Packet, PacketSize)
|
||||||
|
If *View
|
||||||
|
*Chunk = BakaShrot_ReplicateAttachmentChunkPacket_Decode(*View)
|
||||||
|
MsgPackFree(*View, #False)
|
||||||
|
EndIf
|
||||||
|
If Not *Chunk
|
||||||
|
PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an invalid attachment chunk")
|
||||||
|
ProcedureReturn #False
|
||||||
|
EndIf
|
||||||
|
TopicRef = *Chunk\Topic
|
||||||
|
NodeRef = *Chunk\Node
|
||||||
|
MessageId = *Chunk\MessageId
|
||||||
|
|
||||||
|
If *Client\PeerName = ""
|
||||||
|
BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk)
|
||||||
|
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Only peers can replicate")
|
||||||
|
EndIf
|
||||||
|
TopicId = BakaShrot_Names_TopicByName(TopicRef)
|
||||||
|
NodeId = BakaShrot_Names_NodeByName(NodeRef)
|
||||||
|
If TopicId < 0 Or NodeId < 0 Or Not NameSetHas(@*Client\AcceptTopics, TopicId, TopicRef) Or Not NameSetHas(@*Client\AcceptNodes, NodeId, NodeRef)
|
||||||
|
BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk)
|
||||||
|
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "'" + TopicRef + "':'" + NodeRef + "' isn't replicated here")
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If Not GetStorageAttachment(*Client\DbId, TopicId, NodeId, MessageId, @Attachment)
|
||||||
|
BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk)
|
||||||
|
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "No attachment expected for " + TopicRef + ":" + NodeRef + "#" + Str(MessageId))
|
||||||
|
EndIf
|
||||||
|
If Attachment\State = #BakaShrot_Attachment_Ready
|
||||||
|
; Someone else's link was faster: done.
|
||||||
|
BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk)
|
||||||
|
ProcedureReturn BakaShrot_NetClient_SendChunkStored(*Client, Attachment\Size, #True)
|
||||||
|
EndIf
|
||||||
|
If Attachment\State = #BakaShrot_Attachment_NotKept
|
||||||
|
BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk)
|
||||||
|
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The attachment isn't kept here")
|
||||||
|
EndIf
|
||||||
|
If *Chunk\ChunkIndex * #BakaShrot_AttachmentChunkSize <> Attachment\Received Or *Chunk\DataSize <> BakaShrot_AttachmentChunkBytes(Attachment\Size, *Chunk\ChunkIndex)
|
||||||
|
BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk)
|
||||||
|
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Expected part " + Str(Attachment\Received / #BakaShrot_AttachmentChunkSize))
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
BlobId = Attachment\BlobId
|
||||||
|
If Not BlobId
|
||||||
|
BlobId = StartReplicatedAttachment(TopicId, NodeId, MessageId, @StoreError)
|
||||||
|
EndIf
|
||||||
|
If BlobId
|
||||||
|
Received = StoreStorageBlobChunk(BlobId, *Chunk\ChunkIndex, *Chunk\Data, *Chunk\DataSize, @StoreError)
|
||||||
|
Else
|
||||||
|
Received = -1
|
||||||
|
EndIf
|
||||||
|
BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk)
|
||||||
|
If Received < 0
|
||||||
|
PrintN("[Net] Failed to store an attachment's part from peer '" + *Client\PeerName + "': " + StoreError\s)
|
||||||
|
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The part couldn't be stored")
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If Received < Attachment\Size
|
||||||
|
ProcedureReturn BakaShrot_NetClient_SendChunkStored(*Client, Received, #False)
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
IsValid = HashStorageBlob(*Client\DbId, BlobId, Attachment\Size, @Attachment\Sha256[0])
|
||||||
|
If Not FinishReplicatedAttachment(TopicId, NodeId, MessageId, BlobId, IsValid)
|
||||||
|
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The attachment couldn't be stored")
|
||||||
|
EndIf
|
||||||
|
If Not IsValid
|
||||||
|
PrintN("[Net] The attachment of " + TopicRef + ":" + NodeRef + "#" + Str(MessageId) + " from peer '" + *Client\PeerName + "' doesn't match its SHA-256, dropped")
|
||||||
|
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The attachment doesn't match its SHA-256, send it again")
|
||||||
|
EndIf
|
||||||
|
ProcedureReturn BakaShrot_NetClient_SendChunkStored(*Client, Received, #True)
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
|
||||||
; Handles one request from an authenticated client.
|
; Handles one request from an authenticated client.
|
||||||
; Returns #False if the client must be aborted.
|
; Returns #False if the client must be aborted.
|
||||||
@@ -1024,6 +1397,21 @@ Procedure.i BakaShrot_NetClient_HandleRequest(*Client.BakaShrot_NetClient, *Pack
|
|||||||
|
|
||||||
Case #BakaShrot_PacketType_ReplicateMessages
|
Case #BakaShrot_PacketType_ReplicateMessages
|
||||||
ProcedureReturn BakaShrot_NetClient_HandleReplicateMessages(*Client, *Packet, PacketSize)
|
ProcedureReturn BakaShrot_NetClient_HandleReplicateMessages(*Client, *Packet, PacketSize)
|
||||||
|
|
||||||
|
Case #BakaShrot_PacketType_UploadStart
|
||||||
|
ProcedureReturn BakaShrot_NetClient_HandleUploadStart(*Client, *Packet, PacketSize)
|
||||||
|
|
||||||
|
Case #BakaShrot_PacketType_UploadChunk
|
||||||
|
ProcedureReturn BakaShrot_NetClient_HandleUploadChunk(*Client, *Packet, PacketSize)
|
||||||
|
|
||||||
|
Case #BakaShrot_PacketType_GetAttachment
|
||||||
|
ProcedureReturn BakaShrot_NetClient_HandleGetAttachment(*Client, *Packet, PacketSize)
|
||||||
|
|
||||||
|
Case #BakaShrot_PacketType_MissingAttachmentsRequest
|
||||||
|
ProcedureReturn BakaShrot_NetClient_HandleMissingAttachmentsRequest(*Client, *Packet, PacketSize)
|
||||||
|
|
||||||
|
Case #BakaShrot_PacketType_ReplicateAttachmentChunk
|
||||||
|
ProcedureReturn BakaShrot_NetClient_HandleReplicateAttachmentChunk(*Client, *Packet, PacketSize)
|
||||||
EndSelect
|
EndSelect
|
||||||
|
|
||||||
PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an unexpected packet")
|
PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an unexpected packet")
|
||||||
|
|||||||
+148
-1
@@ -27,6 +27,10 @@
|
|||||||
; bigger message goes alone, see ReplicateMessagesPacket.pbi), each
|
; bigger message goes alone, see ReplicateMessagesPacket.pbi), each
|
||||||
; batch stored in one transaction and answered before the next. The
|
; batch stored in one transaction and answered before the next. The
|
||||||
; batches carry the names, the peer stores them under its own ids.
|
; batches carry the names, the peer stores them under its own ids.
|
||||||
|
; A message's attachment only has its size and SHA-256 in the batch.
|
||||||
|
; 4. Once the messages are caught up, asks the peer which attachments it's
|
||||||
|
; missing (MissingAttachmentsRequest) and sends those it has, a part
|
||||||
|
; (1 MB) per request, from where the peer stopped (Design/Attachments.md).
|
||||||
; The peer does the same over its own link to this server, which covers the
|
; The peer does the same over its own link to this server, which covers the
|
||||||
; other direction. Any packet from the peer outside of a check-in drops the
|
; other direction. Any packet from the peer outside of a check-in drops the
|
||||||
; link as unexpected.
|
; link as unexpected.
|
||||||
@@ -143,6 +147,144 @@ Procedure.i BakaShrot_PeerLink_LogRefusal(*Link.BakaShrot_PeerLink, *Answer, Ans
|
|||||||
EndProcedure
|
EndProcedure
|
||||||
|
|
||||||
|
|
||||||
|
; Sends the peer the attachment it's missing, *Missing, from the part it
|
||||||
|
; asked for on, if this server has all of it and sends that topic/node to it.
|
||||||
|
; Returns 1 once the peer has it, 0 if it's skipped (not here, not sent to
|
||||||
|
; that peer, refused: logged), -1 if the link must be dropped.
|
||||||
|
Procedure.i BakaShrot_PeerLink_SendAttachment(*Link.BakaShrot_PeerLink, *Missing.BakaShrot_MissingAttachment)
|
||||||
|
Protected *Links.BakaShrot_PeerLinks = *Link\Links
|
||||||
|
Protected Attachment.BakaShrot_StorageAttachment, Chunk.BakaShrot_ReplicateAttachmentChunk
|
||||||
|
Protected *Stored.BakaShrot_ChunkStored
|
||||||
|
Protected TopicId.i, NodeId.i, Index.q, Count.q, DataSize.Integer, Complete.i
|
||||||
|
Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer, *View.MsgPackData, IsRefusal.i
|
||||||
|
|
||||||
|
TopicId = BakaShrot_Names_TopicByName(*Missing\Topic)
|
||||||
|
NodeId = BakaShrot_Names_NodeByName(*Missing\Node)
|
||||||
|
If TopicId < 0 Or NodeId < 0
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
If Not NameSetHas(@*Link\SendTopics, TopicId, *Missing\Topic) Or Not NameSetHas(@*Link\SendNodes, NodeId, *Missing\Node)
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
; Not here either (yet, or not kept): another server may have it.
|
||||||
|
If Not GetStorageAttachment(*Link\DbId, TopicId, NodeId, *Missing\MessageId, @Attachment) Or Attachment\State <> #BakaShrot_Attachment_Ready
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
Count = BakaShrot_AttachmentChunkCount(Attachment\Size)
|
||||||
|
Chunk\Topic = *Missing\Topic
|
||||||
|
Chunk\Node = *Missing\Node
|
||||||
|
Chunk\MessageId = *Missing\MessageId
|
||||||
|
For Index = *Missing\NextChunk To Count - 1
|
||||||
|
If *Links\StopRequested
|
||||||
|
ProcedureReturn -1
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
Chunk\ChunkIndex = Index
|
||||||
|
Chunk\Data = ReadStorageBlobChunk(*Link\DbId, Attachment\BlobId, Index, @DataSize)
|
||||||
|
If Not Chunk\Data
|
||||||
|
PrintN("[Peer] Can't read part " + Str(Index) + " of the attachment of " + *Missing\Topic + ":" + *Missing\Node + "#" + Str(*Missing\MessageId) + " for '" + *Link\Name + "'")
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
Chunk\DataSize = DataSize\i
|
||||||
|
*Packet = BakaShrot_ReplicateAttachmentChunkPacket_Encode(@Chunk, @PacketSize)
|
||||||
|
FreeMemory(Chunk\Data)
|
||||||
|
Chunk\Data = 0
|
||||||
|
If Not *Packet
|
||||||
|
ProcedureReturn -1
|
||||||
|
EndIf
|
||||||
|
*Answer = BakaShrot_PeerLink_Request(*Link, *Packet, PacketSize\i, @AnswerSize)
|
||||||
|
FreeMemory(*Packet)
|
||||||
|
If Not *Answer
|
||||||
|
ProcedureReturn -1
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If BakaShrot_GetPacketType(*Answer, AnswerSize\i) = #BakaShrot_PacketType_RequestRefused
|
||||||
|
IsRefusal = BakaShrot_PeerLink_LogRefusal(*Link, *Answer, AnswerSize\i)
|
||||||
|
FreeMemory(*Answer)
|
||||||
|
If Not IsRefusal
|
||||||
|
ProcedureReturn -1
|
||||||
|
EndIf
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
*Stored = 0
|
||||||
|
*View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i)
|
||||||
|
If *View
|
||||||
|
*Stored = BakaShrot_ChunkStoredPacket_Decode(*View)
|
||||||
|
MsgPackFree(*View, #False)
|
||||||
|
EndIf
|
||||||
|
FreeMemory(*Answer)
|
||||||
|
If Not *Stored
|
||||||
|
PrintN("[Peer] '" + *Link\Name + "' sent an invalid answer to an attachment's part")
|
||||||
|
ProcedureReturn -1
|
||||||
|
EndIf
|
||||||
|
Complete = *Stored\Complete
|
||||||
|
FreeStructure(*Stored)
|
||||||
|
If Complete
|
||||||
|
ProcedureReturn 1
|
||||||
|
EndIf
|
||||||
|
Next
|
||||||
|
|
||||||
|
; All sent, and the peer didn't say it's complete: it'll ask again.
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
|
||||||
|
; Once the messages are caught up: asks the peer which attachments it's
|
||||||
|
; missing, and sends those this server has, one after the other.
|
||||||
|
; Returns #False if the link must be dropped.
|
||||||
|
Procedure.i BakaShrot_PeerLink_SendAttachments(*Link.BakaShrot_PeerLink)
|
||||||
|
Protected Request.BakaShrot_MissingAttachmentsRequest, *Missing.BakaShrot_MissingAttachments
|
||||||
|
Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer, *View.MsgPackData, IsRefusal.i
|
||||||
|
Protected Result.i, StartTime.i, Attachment.BakaShrot_StorageAttachment, Key.s
|
||||||
|
|
||||||
|
*Packet = BakaShrot_MissingAttachmentsRequestPacket_Encode(@Request, @PacketSize)
|
||||||
|
If Not *Packet
|
||||||
|
ProcedureReturn #False
|
||||||
|
EndIf
|
||||||
|
*Answer = BakaShrot_PeerLink_Request(*Link, *Packet, PacketSize\i, @AnswerSize)
|
||||||
|
FreeMemory(*Packet)
|
||||||
|
If Not *Answer
|
||||||
|
PrintN("[Peer] '" + *Link\Name + "' didn't answer which attachments it's missing")
|
||||||
|
ProcedureReturn #False
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If BakaShrot_GetPacketType(*Answer, AnswerSize\i) = #BakaShrot_PacketType_RequestRefused
|
||||||
|
IsRefusal = BakaShrot_PeerLink_LogRefusal(*Link, *Answer, AnswerSize\i)
|
||||||
|
FreeMemory(*Answer)
|
||||||
|
ProcedureReturn IsRefusal
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
*Missing = 0
|
||||||
|
*View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i)
|
||||||
|
If *View
|
||||||
|
*Missing = BakaShrot_MissingAttachmentsPacket_Decode(*View)
|
||||||
|
MsgPackFree(*View, #False)
|
||||||
|
EndIf
|
||||||
|
FreeMemory(*Answer)
|
||||||
|
If Not *Missing
|
||||||
|
PrintN("[Peer] '" + *Link\Name + "' sent an invalid list of missing attachments")
|
||||||
|
ProcedureReturn #False
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
ForEach *Missing\Attachments()
|
||||||
|
StartTime = ElapsedMilliseconds()
|
||||||
|
Result = BakaShrot_PeerLink_SendAttachment(*Link, @*Missing\Attachments())
|
||||||
|
If Result < 0
|
||||||
|
FreeStructure(*Missing)
|
||||||
|
ProcedureReturn #False
|
||||||
|
EndIf
|
||||||
|
If Result > 0
|
||||||
|
Key = *Missing\Attachments()\Topic + ":" + *Missing\Attachments()\Node + "#" + Str(*Missing\Attachments()\MessageId)
|
||||||
|
PrintN("[Peer] Sent the attachment of " + Key + " to '" + *Link\Name + "' in " + Str(ElapsedMilliseconds() - StartTime) + " ms, from part " + Str(*Missing\Attachments()\NextChunk))
|
||||||
|
EndIf
|
||||||
|
Next
|
||||||
|
FreeStructure(*Missing)
|
||||||
|
ProcedureReturn #True
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
|
||||||
; Sends a batch of messages the peer is missing and checks its answer.
|
; Sends a batch of messages the peer is missing and checks its answer.
|
||||||
; Returns 1 once stored, 0 if the peer refused it (logged), or -1 if the
|
; Returns 1 once stored, 0 if the peer refused it (logged), or -1 if the
|
||||||
; link must be dropped.
|
; link must be dropped.
|
||||||
@@ -242,6 +384,10 @@ Procedure.i BakaShrot_PeerLink_SendMissing(*Link.BakaShrot_PeerLink, TopicId.i,
|
|||||||
; As stored: when it was pushed to its origin, whichever server that was.
|
; As stored: when it was pushed to its origin, whichever server that was.
|
||||||
Batch\Messages()\PushedAt = Messages()\PushedAt
|
Batch\Messages()\PushedAt = Messages()\PushedAt
|
||||||
Batch\Messages()\JsonData = Messages()\JsonData
|
Batch\Messages()\JsonData = Messages()\JsonData
|
||||||
|
; Its attachment's size and SHA-256 only: the data goes once the
|
||||||
|
; messages are caught up (BakaShrot_PeerLink_SendAttachments()).
|
||||||
|
Batch\Messages()\AttachmentSize = Messages()\AttachmentSize
|
||||||
|
CopyMemory(@Messages()\AttachmentSha256[0], @Batch\Messages()\AttachmentSha256[0], #BakaShrot_Sha256Size)
|
||||||
Next
|
Next
|
||||||
|
|
||||||
If ListSize(Batch\Messages()) = 0
|
If ListSize(Batch\Messages()) = 0
|
||||||
@@ -394,7 +540,8 @@ Procedure.i BakaShrot_PeerLink_CheckIn(*Link.BakaShrot_PeerLink)
|
|||||||
EndIf
|
EndIf
|
||||||
Next
|
Next
|
||||||
|
|
||||||
ProcedureReturn #True
|
; 4. Then the attachments: only for messages the peer has now.
|
||||||
|
ProcedureReturn BakaShrot_PeerLink_SendAttachments(*Link)
|
||||||
EndProcedure
|
EndProcedure
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,450 @@
|
|||||||
|
; ============================================================================
|
||||||
|
; BakaShrot Storage Attachments
|
||||||
|
;
|
||||||
|
; A message has at most one attachment, of any size up to the server's
|
||||||
|
; MaxAttachmentSize, stored in parts (Design/Attachments.md):
|
||||||
|
; blobs the data of one attachment, being received or stored
|
||||||
|
; blob_chunks its parts, #BakaShrot_AttachmentChunkSize bytes each, the
|
||||||
|
; last one what's left
|
||||||
|
; attachments a message's: its size and SHA-256, and its blob once any
|
||||||
|
; of it is here
|
||||||
|
; See SetupStorageDatabase() in Storage.pbi for the columns and states.
|
||||||
|
;
|
||||||
|
; Pushed with a message:
|
||||||
|
; CreateStorageBlob() an upload starts (state 0), owned by the
|
||||||
|
; client's topic and node
|
||||||
|
; StoreStorageBlobChunk() each part, in order
|
||||||
|
; HashStorageBlob() once all of it is here, checked against the
|
||||||
|
; SHA-256 given at the start: complete (1), or
|
||||||
|
; dropped (3)
|
||||||
|
; then InsertNextMessage() (Writer.pbi) with its blob id attaches it to
|
||||||
|
; the message, in the same transaction (2).
|
||||||
|
; Replicated: the message comes first (ReplicateMessages), its attachments
|
||||||
|
; row in state 0, then once the messages are caught up:
|
||||||
|
; GetMissingStorageAttachments() what's missing, or started
|
||||||
|
; StartReplicatedAttachment() the first part makes its blob
|
||||||
|
; StoreStorageBlobChunk() each part, resuming where it stopped
|
||||||
|
; FinishReplicatedAttachment() ready (2), or back to missing if its
|
||||||
|
; SHA-256 doesn't match
|
||||||
|
; Deleting a message (the retention) deletes its attachments row (trigger),
|
||||||
|
; which marks its blob (3); CleanUpStorageBlobs() deletes it a part at a
|
||||||
|
; time, along with uploads never completed or never attached.
|
||||||
|
;
|
||||||
|
; Writes go through the writer (Writer.pbi), under its mutex; reads take
|
||||||
|
; the caller's own connection.
|
||||||
|
; ============================================================================
|
||||||
|
|
||||||
|
; SHA-256 (BakaShrot_Sha256_*).
|
||||||
|
XIncludeFile "../../Commons/Cryptography/Libsodium.pbi"
|
||||||
|
|
||||||
|
|
||||||
|
Structure BakaShrot_StorageBlob
|
||||||
|
BlobId.q
|
||||||
|
TopicId.i
|
||||||
|
NodeId.i
|
||||||
|
Size.q
|
||||||
|
Sha256.a[#BakaShrot_Sha256Size]
|
||||||
|
Received.q
|
||||||
|
State.i
|
||||||
|
EndStructure
|
||||||
|
|
||||||
|
Structure BakaShrot_StorageAttachment
|
||||||
|
Size.q
|
||||||
|
Sha256.a[#BakaShrot_Sha256Size]
|
||||||
|
; 0 while none of it is here.
|
||||||
|
BlobId.q
|
||||||
|
; 0 missing, 1 receiving, 2 ready, 3 not kept here.
|
||||||
|
State.i
|
||||||
|
; Of its blob, 0 without one.
|
||||||
|
Received.q
|
||||||
|
EndStructure
|
||||||
|
|
||||||
|
Structure BakaShrot_StorageMissingAttachment
|
||||||
|
TopicId.i
|
||||||
|
NodeId.i
|
||||||
|
Topic.s
|
||||||
|
Node.s
|
||||||
|
MessageId.q
|
||||||
|
Received.q
|
||||||
|
EndStructure
|
||||||
|
|
||||||
|
#BakaShrot_Blob_Receiving = 0
|
||||||
|
#BakaShrot_Blob_Complete = 1
|
||||||
|
#BakaShrot_Blob_Attached = 2
|
||||||
|
#BakaShrot_Blob_Deleted = 3
|
||||||
|
|
||||||
|
#BakaShrot_Attachment_Missing = 0
|
||||||
|
#BakaShrot_Attachment_Receiving = 1
|
||||||
|
#BakaShrot_Attachment_Ready = 2
|
||||||
|
#BakaShrot_Attachment_NotKept = 3
|
||||||
|
|
||||||
|
|
||||||
|
; --- Reads, on the caller's connection -----------------------------------------
|
||||||
|
|
||||||
|
; Fills *Blob with blob BlobId. Returns #False if there's none.
|
||||||
|
Procedure.i GetStorageBlob(DbId.i, BlobId.q, *Blob.BakaShrot_StorageBlob)
|
||||||
|
Protected Found.i
|
||||||
|
|
||||||
|
SetDatabaseQuad(DbId, 0, BlobId)
|
||||||
|
If Not DatabaseQuery(DbId, "SELECT topic_id, node_id, size, sha256, received, state FROM blobs WHERE blob_id = ?")
|
||||||
|
ProcedureReturn #False
|
||||||
|
EndIf
|
||||||
|
Found = NextDatabaseRow(DbId)
|
||||||
|
If Found
|
||||||
|
*Blob\BlobId = BlobId
|
||||||
|
*Blob\TopicId = GetDatabaseLong(DbId, 0)
|
||||||
|
*Blob\NodeId = GetDatabaseLong(DbId, 1)
|
||||||
|
*Blob\Size = GetDatabaseQuad(DbId, 2)
|
||||||
|
FillMemory(@*Blob\Sha256[0], #BakaShrot_Sha256Size, 0)
|
||||||
|
If DatabaseColumnSize(DbId, 3) = #BakaShrot_Sha256Size
|
||||||
|
GetDatabaseBlob(DbId, 3, @*Blob\Sha256[0], #BakaShrot_Sha256Size)
|
||||||
|
EndIf
|
||||||
|
*Blob\Received = GetDatabaseQuad(DbId, 4)
|
||||||
|
*Blob\State = GetDatabaseLong(DbId, 5)
|
||||||
|
EndIf
|
||||||
|
FinishDatabaseQuery(DbId)
|
||||||
|
ProcedureReturn Found
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
|
||||||
|
; Fills *Attachment with the attachment of TopicId:NodeId#MessageId.
|
||||||
|
; Returns #False if that message has none (or doesn't exist).
|
||||||
|
Procedure.i GetStorageAttachment(DbId.i, TopicId.i, NodeId.i, MessageId.q, *Attachment.BakaShrot_StorageAttachment)
|
||||||
|
Protected Found.i
|
||||||
|
|
||||||
|
SetDatabaseLong(DbId, 0, TopicId)
|
||||||
|
SetDatabaseLong(DbId, 1, NodeId)
|
||||||
|
SetDatabaseQuad(DbId, 2, MessageId)
|
||||||
|
If Not DatabaseQuery(DbId, "SELECT a.size, a.sha256, COALESCE(a.blob_id, 0), a.state, COALESCE(b.received, 0) " +
|
||||||
|
"FROM attachments a LEFT JOIN blobs b ON b.blob_id = a.blob_id " +
|
||||||
|
"WHERE a.topic_id = ? AND a.node_id = ? AND a.message_id = ?")
|
||||||
|
ProcedureReturn #False
|
||||||
|
EndIf
|
||||||
|
Found = NextDatabaseRow(DbId)
|
||||||
|
If Found
|
||||||
|
*Attachment\Size = GetDatabaseQuad(DbId, 0)
|
||||||
|
FillMemory(@*Attachment\Sha256[0], #BakaShrot_Sha256Size, 0)
|
||||||
|
If DatabaseColumnSize(DbId, 1) = #BakaShrot_Sha256Size
|
||||||
|
GetDatabaseBlob(DbId, 1, @*Attachment\Sha256[0], #BakaShrot_Sha256Size)
|
||||||
|
EndIf
|
||||||
|
*Attachment\BlobId = GetDatabaseQuad(DbId, 2)
|
||||||
|
*Attachment\State = GetDatabaseLong(DbId, 3)
|
||||||
|
*Attachment\Received = GetDatabaseQuad(DbId, 4)
|
||||||
|
EndIf
|
||||||
|
FinishDatabaseQuery(DbId)
|
||||||
|
ProcedureReturn Found
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
|
||||||
|
; Part Index of blob BlobId, in a freshly allocated buffer, its size in
|
||||||
|
; *OutSize\i. Returns 0 if it isn't stored. The caller frees it.
|
||||||
|
Procedure.i ReadStorageBlobChunk(DbId.i, BlobId.q, Index.q, *OutSize.Integer)
|
||||||
|
Protected *Data, Size.i
|
||||||
|
|
||||||
|
SetDatabaseQuad(DbId, 0, BlobId)
|
||||||
|
SetDatabaseQuad(DbId, 1, Index)
|
||||||
|
If Not DatabaseQuery(DbId, "SELECT chunk_data FROM blob_chunks WHERE blob_id = ? AND chunk_index = ?")
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
If NextDatabaseRow(DbId)
|
||||||
|
Size = DatabaseColumnSize(DbId, 0)
|
||||||
|
If Size > 0
|
||||||
|
*Data = AllocateMemory(Size, #PB_Memory_NoClear)
|
||||||
|
If *Data
|
||||||
|
GetDatabaseBlob(DbId, 0, *Data, Size)
|
||||||
|
*OutSize\i = Size
|
||||||
|
EndIf
|
||||||
|
EndIf
|
||||||
|
EndIf
|
||||||
|
FinishDatabaseQuery(DbId)
|
||||||
|
ProcedureReturn *Data
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
|
||||||
|
; Reads all of blob BlobId back (Size bytes, in parts) and checks its SHA-256
|
||||||
|
; is *Sha256. Returns #False if it isn't, or a part is missing or the wrong
|
||||||
|
; size. ~3 s per GB.
|
||||||
|
Procedure.i HashStorageBlob(DbId.i, BlobId.q, Size.q, *Sha256)
|
||||||
|
Protected Hash.BakaShrot_Sha256, Index.q, Count.q, *Data, DataSize.Integer
|
||||||
|
Protected Dim Result.a(#BakaShrot_Sha256Size - 1)
|
||||||
|
|
||||||
|
If Not BakaShrot_Sha256_Start(@Hash)
|
||||||
|
ProcedureReturn #False
|
||||||
|
EndIf
|
||||||
|
Count = BakaShrot_AttachmentChunkCount(Size)
|
||||||
|
For Index = 0 To Count - 1
|
||||||
|
*Data = ReadStorageBlobChunk(DbId, BlobId, Index, @DataSize)
|
||||||
|
If Not *Data
|
||||||
|
ProcedureReturn #False
|
||||||
|
EndIf
|
||||||
|
If DataSize\i <> BakaShrot_AttachmentChunkBytes(Size, Index)
|
||||||
|
FreeMemory(*Data)
|
||||||
|
ProcedureReturn #False
|
||||||
|
EndIf
|
||||||
|
BakaShrot_Sha256_Add(@Hash, *Data, DataSize\i)
|
||||||
|
FreeMemory(*Data)
|
||||||
|
Next
|
||||||
|
BakaShrot_Sha256_Finish(@Hash, @Result(0))
|
||||||
|
ProcedureReturn CompareMemory(@Result(0), *Sha256, #BakaShrot_Sha256Size)
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
|
||||||
|
; Fills Missing() with attachments of messages here that aren't all here
|
||||||
|
; yet (missing or receiving), with their topic and node names, up to Limit.
|
||||||
|
; Unnamed topics or nodes are left out: replication goes by name.
|
||||||
|
; Returns #False if the query failed.
|
||||||
|
Procedure.i GetMissingStorageAttachments(DbId.i, Limit.i, List Missing.BakaShrot_StorageMissingAttachment())
|
||||||
|
ClearList(Missing())
|
||||||
|
SetDatabaseLong(DbId, 0, Limit)
|
||||||
|
If Not DatabaseQuery(DbId, "SELECT a.topic_id, a.node_id, t.name, n.name, a.message_id, COALESCE(b.received, 0) " +
|
||||||
|
"FROM attachments a JOIN topics t ON t.topic_id = a.topic_id JOIN nodes n ON n.node_id = a.node_id " +
|
||||||
|
"LEFT JOIN blobs b ON b.blob_id = a.blob_id " +
|
||||||
|
"WHERE a.state IN (0, 1) ORDER BY a.topic_id, a.node_id, a.message_id LIMIT ?")
|
||||||
|
ProcedureReturn #False
|
||||||
|
EndIf
|
||||||
|
While NextDatabaseRow(DbId)
|
||||||
|
AddElement(Missing())
|
||||||
|
Missing()\TopicId = GetDatabaseLong(DbId, 0)
|
||||||
|
Missing()\NodeId = GetDatabaseLong(DbId, 1)
|
||||||
|
Missing()\Topic = GetDatabaseString(DbId, 2)
|
||||||
|
Missing()\Node = GetDatabaseString(DbId, 3)
|
||||||
|
Missing()\MessageId = GetDatabaseQuad(DbId, 4)
|
||||||
|
Missing()\Received = GetDatabaseQuad(DbId, 5)
|
||||||
|
Wend
|
||||||
|
FinishDatabaseQuery(DbId)
|
||||||
|
ProcedureReturn #True
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
|
||||||
|
; --- Writes, through the writer ------------------------------------------------
|
||||||
|
|
||||||
|
; Starts an upload for TopicId/NodeId: Size bytes whose SHA-256 is *Sha256.
|
||||||
|
; Returns its blob id, 0 with the reason in *Error\s.
|
||||||
|
Procedure.q CreateStorageBlob(TopicId.i, NodeId.i, Size.q, *Sha256, *Error.String)
|
||||||
|
Protected DbId.i, BlobId.q
|
||||||
|
|
||||||
|
LockMutex(BakaShrot_Storage_WriteMutex)
|
||||||
|
DbId = BakaShrot_Storage_Writer\DbId
|
||||||
|
If Not DbId
|
||||||
|
UnlockMutex(BakaShrot_Storage_WriteMutex)
|
||||||
|
*Error\s = "the storage writer isn't open"
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
SetDatabaseLong(DbId, 0, TopicId)
|
||||||
|
SetDatabaseLong(DbId, 1, NodeId)
|
||||||
|
SetDatabaseQuad(DbId, 2, Size)
|
||||||
|
SetDatabaseBlob(DbId, 3, *Sha256, #BakaShrot_Sha256Size)
|
||||||
|
SetDatabaseQuad(DbId, 4, BakaShrot_NowUtcMs())
|
||||||
|
If DatabaseUpdate(DbId, "INSERT INTO blobs (topic_id, node_id, size, sha256, received, state, created_at) VALUES (?, ?, ?, ?, 0, 0, ?)")
|
||||||
|
If DatabaseQuery(DbId, "SELECT last_insert_rowid()")
|
||||||
|
If NextDatabaseRow(DbId)
|
||||||
|
BlobId = GetDatabaseQuad(DbId, 0)
|
||||||
|
EndIf
|
||||||
|
FinishDatabaseQuery(DbId)
|
||||||
|
EndIf
|
||||||
|
EndIf
|
||||||
|
If Not BlobId
|
||||||
|
*Error\s = DatabaseError()
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
UnlockMutex(BakaShrot_Storage_WriteMutex)
|
||||||
|
ProcedureReturn BlobId
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
|
||||||
|
; Stores part Index (DataSize bytes at *Data) of blob BlobId, which must be
|
||||||
|
; the next one: Index * #BakaShrot_AttachmentChunkSize bytes received so far.
|
||||||
|
; Returns how many are received now, -1 with the reason in *Error\s (nothing
|
||||||
|
; stored then).
|
||||||
|
Procedure.q StoreStorageBlobChunk(BlobId.q, Index.q, *Data, DataSize.i, *Error.String)
|
||||||
|
Protected DbId.i, Received.q = -1, Ok.i
|
||||||
|
|
||||||
|
LockMutex(BakaShrot_Storage_WriteMutex)
|
||||||
|
DbId = BakaShrot_Storage_Writer\DbId
|
||||||
|
If Not DbId
|
||||||
|
UnlockMutex(BakaShrot_Storage_WriteMutex)
|
||||||
|
*Error\s = "the storage writer isn't open"
|
||||||
|
ProcedureReturn -1
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If DatabaseUpdate(DbId, "BEGIN IMMEDIATE")
|
||||||
|
; Only if it's the next one, and the blob is still being received.
|
||||||
|
SetDatabaseQuad(DbId, 0, DataSize)
|
||||||
|
SetDatabaseQuad(DbId, 1, BlobId)
|
||||||
|
SetDatabaseQuad(DbId, 2, Index * #BakaShrot_AttachmentChunkSize)
|
||||||
|
Ok = DatabaseUpdate(DbId, "UPDATE blobs SET received = received + ? WHERE blob_id = ? AND received = ? AND state = 0")
|
||||||
|
If Ok And AffectedDatabaseRows(DbId) <> 1
|
||||||
|
Ok = #False
|
||||||
|
*Error\s = "not the next part, or not being received"
|
||||||
|
ElseIf Not Ok
|
||||||
|
*Error\s = DatabaseError()
|
||||||
|
EndIf
|
||||||
|
If Ok
|
||||||
|
SetDatabaseQuad(DbId, 0, BlobId)
|
||||||
|
SetDatabaseQuad(DbId, 1, Index)
|
||||||
|
SetDatabaseBlob(DbId, 2, *Data, DataSize)
|
||||||
|
Ok = DatabaseUpdate(DbId, "INSERT INTO blob_chunks (blob_id, chunk_index, chunk_data) VALUES (?, ?, ?)")
|
||||||
|
If Not Ok
|
||||||
|
*Error\s = DatabaseError()
|
||||||
|
EndIf
|
||||||
|
EndIf
|
||||||
|
If Ok And DatabaseUpdate(DbId, "COMMIT")
|
||||||
|
Received = Index * #BakaShrot_AttachmentChunkSize + DataSize
|
||||||
|
Else
|
||||||
|
If Ok
|
||||||
|
*Error\s = DatabaseError()
|
||||||
|
EndIf
|
||||||
|
DatabaseUpdate(DbId, "ROLLBACK")
|
||||||
|
EndIf
|
||||||
|
Else
|
||||||
|
*Error\s = DatabaseError()
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
UnlockMutex(BakaShrot_Storage_WriteMutex)
|
||||||
|
ProcedureReturn Received
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
|
||||||
|
; Sets blob BlobId's state (#BakaShrot_Blob_*). Returns #False if it failed.
|
||||||
|
Procedure.i SetStorageBlobState(BlobId.q, State.i)
|
||||||
|
Protected DbId.i, Ok.i
|
||||||
|
|
||||||
|
LockMutex(BakaShrot_Storage_WriteMutex)
|
||||||
|
DbId = BakaShrot_Storage_Writer\DbId
|
||||||
|
If DbId
|
||||||
|
SetDatabaseLong(DbId, 0, State)
|
||||||
|
SetDatabaseQuad(DbId, 1, BlobId)
|
||||||
|
Ok = DatabaseUpdate(DbId, "UPDATE blobs SET state = ? WHERE blob_id = ?")
|
||||||
|
EndIf
|
||||||
|
UnlockMutex(BakaShrot_Storage_WriteMutex)
|
||||||
|
ProcedureReturn Ok
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
|
||||||
|
; Makes the blob of a replicated attachment that's still missing (state 0),
|
||||||
|
; from its row's size and SHA-256, and links it: receiving (1).
|
||||||
|
; Returns its blob id, 0 with the reason in *Error\s.
|
||||||
|
Procedure.q StartReplicatedAttachment(TopicId.i, NodeId.i, MessageId.q, *Error.String)
|
||||||
|
Protected DbId.i, BlobId.q, Ok.i
|
||||||
|
|
||||||
|
LockMutex(BakaShrot_Storage_WriteMutex)
|
||||||
|
DbId = BakaShrot_Storage_Writer\DbId
|
||||||
|
If Not DbId
|
||||||
|
UnlockMutex(BakaShrot_Storage_WriteMutex)
|
||||||
|
*Error\s = "the storage writer isn't open"
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If DatabaseUpdate(DbId, "BEGIN IMMEDIATE")
|
||||||
|
SetDatabaseLong(DbId, 0, TopicId)
|
||||||
|
SetDatabaseLong(DbId, 1, NodeId)
|
||||||
|
SetDatabaseQuad(DbId, 2, BakaShrot_NowUtcMs())
|
||||||
|
SetDatabaseLong(DbId, 3, TopicId)
|
||||||
|
SetDatabaseLong(DbId, 4, NodeId)
|
||||||
|
SetDatabaseQuad(DbId, 5, MessageId)
|
||||||
|
Ok = DatabaseUpdate(DbId, "INSERT INTO blobs (topic_id, node_id, size, sha256, received, state, created_at) " +
|
||||||
|
"SELECT ?, ?, size, sha256, 0, 0, ? FROM attachments WHERE topic_id = ? AND node_id = ? AND message_id = ? AND state = 0 AND blob_id IS NULL")
|
||||||
|
If Ok And AffectedDatabaseRows(DbId) = 1 And DatabaseQuery(DbId, "SELECT last_insert_rowid()")
|
||||||
|
If NextDatabaseRow(DbId)
|
||||||
|
BlobId = GetDatabaseQuad(DbId, 0)
|
||||||
|
EndIf
|
||||||
|
FinishDatabaseQuery(DbId)
|
||||||
|
EndIf
|
||||||
|
If BlobId
|
||||||
|
SetDatabaseQuad(DbId, 0, BlobId)
|
||||||
|
SetDatabaseLong(DbId, 1, TopicId)
|
||||||
|
SetDatabaseLong(DbId, 2, NodeId)
|
||||||
|
SetDatabaseQuad(DbId, 3, MessageId)
|
||||||
|
Ok = DatabaseUpdate(DbId, "UPDATE attachments SET blob_id = ?, state = 1 WHERE topic_id = ? AND node_id = ? AND message_id = ?")
|
||||||
|
EndIf
|
||||||
|
If BlobId And Ok And DatabaseUpdate(DbId, "COMMIT")
|
||||||
|
; Done.
|
||||||
|
Else
|
||||||
|
*Error\s = DatabaseError()
|
||||||
|
If *Error\s = ""
|
||||||
|
*Error\s = "the attachment isn't missing"
|
||||||
|
EndIf
|
||||||
|
DatabaseUpdate(DbId, "ROLLBACK")
|
||||||
|
BlobId = 0
|
||||||
|
EndIf
|
||||||
|
Else
|
||||||
|
*Error\s = DatabaseError()
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
UnlockMutex(BakaShrot_Storage_WriteMutex)
|
||||||
|
ProcedureReturn BlobId
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
|
||||||
|
; A replicated attachment is all here: ready (2) if its SHA-256 checked out
|
||||||
|
; (IsValid), else its blob is dropped and it's missing again (0), to be sent
|
||||||
|
; again from the start. Returns #False if it failed.
|
||||||
|
Procedure.i FinishReplicatedAttachment(TopicId.i, NodeId.i, MessageId.q, BlobId.q, IsValid.i)
|
||||||
|
Protected DbId.i, Ok.i
|
||||||
|
|
||||||
|
LockMutex(BakaShrot_Storage_WriteMutex)
|
||||||
|
DbId = BakaShrot_Storage_Writer\DbId
|
||||||
|
If DbId And DatabaseUpdate(DbId, "BEGIN IMMEDIATE")
|
||||||
|
SetDatabaseQuad(DbId, 0, BlobId)
|
||||||
|
If IsValid
|
||||||
|
Ok = DatabaseUpdate(DbId, "UPDATE blobs SET state = 2 WHERE blob_id = ?")
|
||||||
|
Else
|
||||||
|
Ok = DatabaseUpdate(DbId, "UPDATE blobs SET state = 3 WHERE blob_id = ?")
|
||||||
|
EndIf
|
||||||
|
If Ok
|
||||||
|
SetDatabaseLong(DbId, 0, TopicId)
|
||||||
|
SetDatabaseLong(DbId, 1, NodeId)
|
||||||
|
SetDatabaseQuad(DbId, 2, MessageId)
|
||||||
|
If IsValid
|
||||||
|
Ok = DatabaseUpdate(DbId, "UPDATE attachments SET state = 2 WHERE topic_id = ? AND node_id = ? AND message_id = ?")
|
||||||
|
Else
|
||||||
|
Ok = DatabaseUpdate(DbId, "UPDATE attachments SET state = 0, blob_id = NULL WHERE topic_id = ? AND node_id = ? AND message_id = ?")
|
||||||
|
EndIf
|
||||||
|
EndIf
|
||||||
|
If Ok
|
||||||
|
Ok = DatabaseUpdate(DbId, "COMMIT")
|
||||||
|
EndIf
|
||||||
|
If Not Ok
|
||||||
|
DatabaseUpdate(DbId, "ROLLBACK")
|
||||||
|
EndIf
|
||||||
|
EndIf
|
||||||
|
UnlockMutex(BakaShrot_Storage_WriteMutex)
|
||||||
|
ProcedureReturn Ok
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
|
||||||
|
; Marks uploads never completed nor attached, started before BeforeMs (ms
|
||||||
|
; since 1970 UTC), to delete, then deletes up to Limit parts of what's to
|
||||||
|
; delete, and the blobs left with none. Call it again while it returns
|
||||||
|
; Limit. Returns how many parts were deleted, -1 with the reason in *Error\s.
|
||||||
|
Procedure.i CleanUpStorageBlobs(BeforeMs.q, Limit.i, *Error.String)
|
||||||
|
Protected DbId.i, Deleted.i = -1
|
||||||
|
|
||||||
|
LockMutex(BakaShrot_Storage_WriteMutex)
|
||||||
|
DbId = BakaShrot_Storage_Writer\DbId
|
||||||
|
If Not DbId
|
||||||
|
UnlockMutex(BakaShrot_Storage_WriteMutex)
|
||||||
|
*Error\s = "the storage writer isn't open"
|
||||||
|
ProcedureReturn -1
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; Uploads (no attachments row points to them) left behind.
|
||||||
|
SetDatabaseQuad(DbId, 0, BeforeMs)
|
||||||
|
If DatabaseUpdate(DbId, "UPDATE blobs SET state = 3 WHERE state IN (0, 1) AND created_at < ? " +
|
||||||
|
"AND NOT EXISTS (SELECT 1 FROM attachments a WHERE a.blob_id = blobs.blob_id)")
|
||||||
|
SetDatabaseLong(DbId, 0, Limit)
|
||||||
|
If DatabaseUpdate(DbId, "DELETE FROM blob_chunks WHERE rowid IN (SELECT c.rowid FROM blob_chunks c JOIN blobs b ON b.blob_id = c.blob_id WHERE b.state = 3 LIMIT ?)")
|
||||||
|
Deleted = AffectedDatabaseRows(DbId)
|
||||||
|
If Deleted < Limit
|
||||||
|
DatabaseUpdate(DbId, "DELETE FROM blobs WHERE state = 3 AND NOT EXISTS (SELECT 1 FROM blob_chunks c WHERE c.blob_id = blobs.blob_id)")
|
||||||
|
EndIf
|
||||||
|
EndIf
|
||||||
|
EndIf
|
||||||
|
If Deleted < 0
|
||||||
|
*Error\s = DatabaseError()
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
UnlockMutex(BakaShrot_Storage_WriteMutex)
|
||||||
|
ProcedureReturn Deleted
|
||||||
|
EndProcedure
|
||||||
@@ -13,7 +13,12 @@
|
|||||||
; - deletes its messages pushed (pushed_at) before now minus that age,
|
; - deletes its messages pushed (pushed_at) before now minus that age,
|
||||||
; #BakaShrot_Retention_BatchSize at a time through the writer
|
; #BakaShrot_Retention_BatchSize at a time through the writer
|
||||||
; (DeleteStorageMessagesBefore(), Writer.pbi), so pushes go on between
|
; (DeleteStorageMessagesBefore(), Writer.pbi), so pushes go on between
|
||||||
; the batches.
|
; the batches;
|
||||||
|
; - then the attachments' leftovers (CleanUpStorageBlobs(),
|
||||||
|
; Attachments.pbi): those of the deleted messages, and uploads not
|
||||||
|
; pushed with a message within [BakaShrot.Server] UploadTimeout,
|
||||||
|
; #BakaShrot_Retention_ChunkBatchSize parts at a time.
|
||||||
|
; It runs without any [BakaShrot.Retention] too, for the leftovers.
|
||||||
;
|
;
|
||||||
; Messages "may be" deleted past their max age: up to RetentionInterval
|
; Messages "may be" deleted past their max age: up to RetentionInterval
|
||||||
; later. Those a peer replicates here already past it aren't stored at all
|
; later. Those a peer replicates here already past it aren't stored at all
|
||||||
@@ -33,6 +38,9 @@
|
|||||||
; Most messages deleted in one statement, under the write mutex: a few ms.
|
; Most messages deleted in one statement, under the write mutex: a few ms.
|
||||||
#BakaShrot_Retention_BatchSize = 5000
|
#BakaShrot_Retention_BatchSize = 5000
|
||||||
|
|
||||||
|
; Most attachment parts (1 MB each) deleted in one statement.
|
||||||
|
#BakaShrot_Retention_ChunkBatchSize = 32
|
||||||
|
|
||||||
|
|
||||||
Structure BakaShrot_RetentionTopic
|
Structure BakaShrot_RetentionTopic
|
||||||
TopicId.i
|
TopicId.i
|
||||||
@@ -43,6 +51,7 @@ Structure BakaShrot_RetentionState
|
|||||||
ThreadId.i
|
ThreadId.i
|
||||||
StopRequested.i
|
StopRequested.i
|
||||||
IntervalMs.i
|
IntervalMs.i
|
||||||
|
UploadTimeoutMs.q
|
||||||
DatabasePath.s
|
DatabasePath.s
|
||||||
List Rules.BakaShrot_RetentionRule()
|
List Rules.BakaShrot_RetentionRule()
|
||||||
EndStructure
|
EndStructure
|
||||||
@@ -56,6 +65,25 @@ Procedure.s BakaShrot_Retention_FormatUtc(Ms.q)
|
|||||||
EndProcedure
|
EndProcedure
|
||||||
|
|
||||||
|
|
||||||
|
; Deletes the attachments' leftovers, a few parts at a time.
|
||||||
|
Procedure BakaShrot_Retention_CleanUp()
|
||||||
|
Protected Deleted.i, Total.q, Error.String
|
||||||
|
|
||||||
|
Repeat
|
||||||
|
Deleted = CleanUpStorageBlobs(BakaShrot_NowUtcMs() - BakaShrot_Retention\UploadTimeoutMs, #BakaShrot_Retention_ChunkBatchSize, @Error)
|
||||||
|
If Deleted < 0
|
||||||
|
PrintN("[Storage] Retention: failed to delete the attachments' leftovers: " + Error\s)
|
||||||
|
Break
|
||||||
|
EndIf
|
||||||
|
Total + Deleted
|
||||||
|
Until Deleted < #BakaShrot_Retention_ChunkBatchSize Or BakaShrot_Retention\StopRequested
|
||||||
|
|
||||||
|
If Total > 0
|
||||||
|
PrintN("[Storage] Retention: deleted " + Str(Total) + " attachment parts (of deleted messages, or uploads never pushed)")
|
||||||
|
EndIf
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
|
||||||
; Deletes what's past its max age in every topic. DbId is the thread's own
|
; Deletes what's past its max age in every topic. DbId is the thread's own
|
||||||
; connection, only read from (the deletes go through the writer).
|
; connection, only read from (the deletes go through the writer).
|
||||||
; Returns how many messages were deleted.
|
; Returns how many messages were deleted.
|
||||||
@@ -105,6 +133,7 @@ Procedure.q BakaShrot_Retention_Pass(DbId.i)
|
|||||||
EndIf
|
EndIf
|
||||||
Next
|
Next
|
||||||
|
|
||||||
|
BakaShrot_Retention_CleanUp()
|
||||||
ProcedureReturn Total
|
ProcedureReturn Total
|
||||||
EndProcedure
|
EndProcedure
|
||||||
|
|
||||||
@@ -132,27 +161,22 @@ Procedure BakaShrot_Retention_Thread(Unused.i)
|
|||||||
EndProcedure
|
EndProcedure
|
||||||
|
|
||||||
|
|
||||||
; Starts deleting what's past *Config's [BakaShrot.Retention] max ages, once
|
; Starts deleting what's past *Config's [BakaShrot.Retention] max ages, and
|
||||||
; the writer is open. Nothing to do (no thread) if every topic is kept
|
; the attachments' leftovers, once the writer is open.
|
||||||
; forever. Returns #False if the thread can't start.
|
; Returns #False if the thread can't start.
|
||||||
Procedure.i StartStorageRetention(*Config.BakaShrot_CoreConfig)
|
Procedure.i StartStorageRetention(*Config.BakaShrot_CoreConfig)
|
||||||
Protected Deletes.i
|
|
||||||
|
|
||||||
With BakaShrot_Retention
|
With BakaShrot_Retention
|
||||||
ClearList(\Rules())
|
ClearList(\Rules())
|
||||||
CopyList(*Config\Retention(), \Rules())
|
CopyList(*Config\Retention(), \Rules())
|
||||||
ForEach \Rules()
|
ForEach \Rules()
|
||||||
If \Rules()\MaxAgeMs > 0
|
If \Rules()\MaxAgeMs > 0
|
||||||
Deletes = #True
|
|
||||||
PrintN("[Storage] Retention: " + \Rules()\Ref + " = " + \Rules()\AgeText + ", checked every " + Str(*Config\Server\RetentionInterval) + " s")
|
PrintN("[Storage] Retention: " + \Rules()\Ref + " = " + \Rules()\AgeText + ", checked every " + Str(*Config\Server\RetentionInterval) + " s")
|
||||||
EndIf
|
EndIf
|
||||||
Next
|
Next
|
||||||
If Not Deletes
|
|
||||||
ProcedureReturn #True
|
|
||||||
EndIf
|
|
||||||
|
|
||||||
\DatabasePath = *Config\Server\DatabasePath
|
\DatabasePath = *Config\Server\DatabasePath
|
||||||
\IntervalMs = *Config\Server\RetentionInterval * 1000
|
\IntervalMs = *Config\Server\RetentionInterval * 1000
|
||||||
|
\UploadTimeoutMs = *Config\Server\UploadTimeout * 1000
|
||||||
\StopRequested = #False
|
\StopRequested = #False
|
||||||
\ThreadId = CreateThread(@BakaShrot_Retention_Thread(), 0)
|
\ThreadId = CreateThread(@BakaShrot_Retention_Thread(), 0)
|
||||||
ProcedureReturn Bool(\ThreadId)
|
ProcedureReturn Bool(\ThreadId)
|
||||||
|
|||||||
+82
-13
@@ -3,7 +3,8 @@
|
|||||||
;
|
;
|
||||||
; Opens the SQLite database file that backs the node's local storage, and
|
; Opens the SQLite database file that backs the node's local storage, and
|
||||||
; provides the basic read/write operations on top of it.
|
; provides the basic read/write operations on top of it.
|
||||||
; Schema: see db_schema_v6.dbml in this same folder.
|
; Schema: see db_schema_v7.dbml in this same folder. Attachments: see
|
||||||
|
; Attachments.pbi and Design/Attachments.md.
|
||||||
;
|
;
|
||||||
; Needs SQLite 3.38+ with its JSON functions (json_valid, ->>), which the one
|
; Needs SQLite 3.38+ with its JSON functions (json_valid, ->>), which the one
|
||||||
; bundled with PureBasic 5.73 (3.33.0) doesn't have. On Windows, the official
|
; bundled with PureBasic 5.73 (3.33.0) doesn't have. On Windows, the official
|
||||||
@@ -36,12 +37,18 @@ CompilerElse
|
|||||||
CompilerEndIf
|
CompilerEndIf
|
||||||
|
|
||||||
|
|
||||||
; One row of the "data" table (see db_schema_v6.dbml).
|
; One row of the "data" table (see db_schema_v7.dbml).
|
||||||
; PushedAt: when it was pushed, ms since 1970 UTC (Packets.pbi).
|
; PushedAt: when it was pushed, ms since 1970 UTC (Packets.pbi).
|
||||||
|
; AttachmentSize: its attachment's size, 0 for none (the "attachments"
|
||||||
|
; table), AttachmentReady #True once all of it is here, AttachmentSha256 its
|
||||||
|
; SHA-256.
|
||||||
Structure BakaShrot_Message
|
Structure BakaShrot_Message
|
||||||
MessageId.q
|
MessageId.q
|
||||||
PushedAt.q
|
PushedAt.q
|
||||||
JsonData.s
|
JsonData.s
|
||||||
|
AttachmentSize.q
|
||||||
|
AttachmentReady.i
|
||||||
|
AttachmentSha256.a[#BakaShrot_Sha256Size]
|
||||||
EndStructure
|
EndStructure
|
||||||
|
|
||||||
|
|
||||||
@@ -225,7 +232,7 @@ Procedure.i MigrateStoragePushedAt(DbId.i)
|
|||||||
EndProcedure
|
EndProcedure
|
||||||
|
|
||||||
|
|
||||||
; Creates the tables and indexes described by db_schema_v6.dbml, if they
|
; Creates the tables and indexes described by db_schema_v7.dbml, if they
|
||||||
; don't exist yet. Plain "CREATE IF NOT EXISTS" for now - a real versioned
|
; don't exist yet. Plain "CREATE IF NOT EXISTS" for now - a real versioned
|
||||||
; upgrade mechanism (DbUpdater) will replace this later.
|
; upgrade mechanism (DbUpdater) will replace this later.
|
||||||
; Fails on a database made with an older schema, since it would be left as is.
|
; Fails on a database made with an older schema, since it would be left as is.
|
||||||
@@ -293,19 +300,60 @@ Procedure.i SetupStorageDatabase(DbId.i)
|
|||||||
ProcedureReturn #False
|
ProcedureReturn #False
|
||||||
EndIf
|
EndIf
|
||||||
|
|
||||||
; Not used yet, but created now so the on-disk schema already matches
|
; The first schemas' placeholder, never used (and misspelled), replaced
|
||||||
; db_schema_v1.dbml.
|
; by the three tables below. Its indexes go with it.
|
||||||
If Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS attachements (" +
|
If Not DatabaseUpdate(DbId, "DROP TABLE IF EXISTS attachements")
|
||||||
|
ProcedureReturn #False
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; Attachments, see Attachments.pbi and Design/Attachments.md.
|
||||||
|
; blobs: an attachment's data, being uploaded or replicated, or stored.
|
||||||
|
; topic_id, node_id: an upload's, who may attach it (or the message's).
|
||||||
|
; received: bytes stored so far, in blob_chunks.
|
||||||
|
; state: 0 receiving, 1 complete (an upload waiting for its message),
|
||||||
|
; 2 attached to its message, 3 to delete (Retention.pbi deletes it).
|
||||||
|
; created_at: ms since 1970 UTC, uploads left incomplete expire.
|
||||||
|
; blob_chunks: its parts, #BakaShrot_AttachmentChunkSize bytes each.
|
||||||
|
; attachments: a message's (one at most), with its size and SHA-256
|
||||||
|
; from the start, its data in blob_id once any is here.
|
||||||
|
; state: 0 missing (a replicated message, none of it here yet),
|
||||||
|
; 1 receiving, 2 ready, 3 not kept (bigger than this server takes).
|
||||||
|
If Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS blobs (" +
|
||||||
|
"blob_id INTEGER PRIMARY KEY, " +
|
||||||
|
"topic_id INTEGER NOT NULL, " +
|
||||||
|
"node_id INTEGER NOT NULL, " +
|
||||||
|
"size INTEGER NOT NULL, " +
|
||||||
|
"sha256 BLOB NOT NULL, " +
|
||||||
|
"received INTEGER NOT NULL DEFAULT 0, " +
|
||||||
|
"state INTEGER NOT NULL, " +
|
||||||
|
"created_at INTEGER NOT NULL)") Or
|
||||||
|
Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS blob_chunks (" +
|
||||||
|
"blob_id INTEGER NOT NULL, " +
|
||||||
|
"chunk_index INTEGER NOT NULL, " +
|
||||||
|
"chunk_data BLOB NOT NULL, " +
|
||||||
|
"PRIMARY KEY (blob_id, chunk_index))") Or
|
||||||
|
Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS attachments (" +
|
||||||
"topic_id INTEGER NOT NULL, " +
|
"topic_id INTEGER NOT NULL, " +
|
||||||
"node_id INTEGER NOT NULL, " +
|
"node_id INTEGER NOT NULL, " +
|
||||||
"message_id INTEGER NOT NULL, " +
|
"message_id INTEGER NOT NULL, " +
|
||||||
"attachement_data BLOB NOT NULL)")
|
"size INTEGER NOT NULL, " +
|
||||||
|
"sha256 BLOB NOT NULL, " +
|
||||||
|
"blob_id INTEGER, " +
|
||||||
|
"state INTEGER NOT NULL, " +
|
||||||
|
"PRIMARY KEY (topic_id, node_id, message_id)) WITHOUT ROWID") Or
|
||||||
|
Not DatabaseUpdate(DbId, "CREATE INDEX IF NOT EXISTS idx_blobs_state ON blobs (state)") Or
|
||||||
|
Not DatabaseUpdate(DbId, "CREATE INDEX IF NOT EXISTS idx_attachments_state ON attachments (state)")
|
||||||
ProcedureReturn #False
|
ProcedureReturn #False
|
||||||
EndIf
|
EndIf
|
||||||
If Not DatabaseUpdate(DbId, "CREATE INDEX IF NOT EXISTS idx_attachements_topic_node ON attachements (topic_id, node_id)")
|
|
||||||
ProcedureReturn #False
|
; A message deleted (the retention) takes its attachment with it, and an
|
||||||
EndIf
|
; attachment its data: marked, Retention.pbi deletes it a bit at a time.
|
||||||
If Not DatabaseUpdate(DbId, "CREATE INDEX IF NOT EXISTS idx_attachements_message_id ON attachements (message_id)")
|
If Not DatabaseUpdate(DbId, "CREATE TRIGGER IF NOT EXISTS trg_data_attachments AFTER DELETE ON data BEGIN " +
|
||||||
|
"DELETE FROM attachments WHERE topic_id = OLD.topic_id AND node_id = OLD.node_id AND message_id = OLD.message_id; " +
|
||||||
|
"END") Or
|
||||||
|
Not DatabaseUpdate(DbId, "CREATE TRIGGER IF NOT EXISTS trg_attachments_blobs AFTER DELETE ON attachments WHEN OLD.blob_id IS NOT NULL BEGIN " +
|
||||||
|
"UPDATE blobs SET state = 3 WHERE blob_id = OLD.blob_id; " +
|
||||||
|
"END")
|
||||||
ProcedureReturn #False
|
ProcedureReturn #False
|
||||||
EndIf
|
EndIf
|
||||||
|
|
||||||
@@ -487,6 +535,18 @@ EndProcedure
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
; Reads the attachment's size, state and SHA-256 (COALESCE(a.size, 0),
|
||||||
|
; COALESCE(a.state, 0), a.sha256) from Column on into *Message.
|
||||||
|
Procedure BakaShrot_ReadAttachmentColumns(DbId.i, Column.i, *Message.BakaShrot_Message)
|
||||||
|
*Message\AttachmentSize = GetDatabaseQuad(DbId, Column)
|
||||||
|
*Message\AttachmentReady = Bool(*Message\AttachmentSize > 0 And GetDatabaseLong(DbId, Column + 1) = 2)
|
||||||
|
FillMemory(@*Message\AttachmentSha256[0], #BakaShrot_Sha256Size, 0)
|
||||||
|
If *Message\AttachmentSize > 0 And DatabaseColumnSize(DbId, Column + 2) = #BakaShrot_Sha256Size
|
||||||
|
GetDatabaseBlob(DbId, Column + 2, @*Message\AttachmentSha256[0], #BakaShrot_Sha256Size)
|
||||||
|
EndIf
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
|
||||||
; Fills *Message with the message that has the highest message_id for a
|
; Fills *Message with the message that has the highest message_id for a
|
||||||
; topic_id/node_id pair.
|
; topic_id/node_id pair.
|
||||||
; Returns #False if there's none, or if the query failed.
|
; Returns #False if there's none, or if the query failed.
|
||||||
@@ -495,7 +555,9 @@ Procedure.i GetLatestMessage(DbId.i, TopicId.i, NodeId.i, *Message.BakaShrot_Mes
|
|||||||
|
|
||||||
SetDatabaseLong(DbId, 0, TopicId)
|
SetDatabaseLong(DbId, 0, TopicId)
|
||||||
SetDatabaseLong(DbId, 1, NodeId)
|
SetDatabaseLong(DbId, 1, NodeId)
|
||||||
If Not DatabaseQuery(DbId, "SELECT message_id, message_data, pushed_at FROM data WHERE topic_id = ? AND node_id = ? ORDER BY message_id DESC LIMIT 1")
|
If Not DatabaseQuery(DbId, "SELECT d.message_id, d.message_data, d.pushed_at, COALESCE(a.size, 0), COALESCE(a.state, 0), a.sha256 " +
|
||||||
|
"FROM data d LEFT JOIN attachments a ON a.topic_id = d.topic_id AND a.node_id = d.node_id AND a.message_id = d.message_id " +
|
||||||
|
"WHERE d.topic_id = ? AND d.node_id = ? ORDER BY d.message_id DESC LIMIT 1")
|
||||||
ProcedureReturn #False
|
ProcedureReturn #False
|
||||||
EndIf
|
EndIf
|
||||||
|
|
||||||
@@ -504,6 +566,7 @@ Procedure.i GetLatestMessage(DbId.i, TopicId.i, NodeId.i, *Message.BakaShrot_Mes
|
|||||||
*Message\MessageId = GetDatabaseQuad(DbId, 0)
|
*Message\MessageId = GetDatabaseQuad(DbId, 0)
|
||||||
*Message\JsonData = GetDatabaseString(DbId, 1)
|
*Message\JsonData = GetDatabaseString(DbId, 1)
|
||||||
*Message\PushedAt = GetDatabaseQuad(DbId, 2)
|
*Message\PushedAt = GetDatabaseQuad(DbId, 2)
|
||||||
|
BakaShrot_ReadAttachmentColumns(DbId, 3, *Message)
|
||||||
EndIf
|
EndIf
|
||||||
FinishDatabaseQuery(DbId)
|
FinishDatabaseQuery(DbId)
|
||||||
|
|
||||||
@@ -755,7 +818,9 @@ Procedure.i GetMessagesAfter(DbId.i, TopicId.i, NodeId.i, AfterMessageId.q, Limi
|
|||||||
SetDatabaseLong(DbId, 1, NodeId)
|
SetDatabaseLong(DbId, 1, NodeId)
|
||||||
SetDatabaseQuad(DbId, 2, AfterMessageId)
|
SetDatabaseQuad(DbId, 2, AfterMessageId)
|
||||||
SetDatabaseLong(DbId, 3, Limit + 1)
|
SetDatabaseLong(DbId, 3, Limit + 1)
|
||||||
If Not DatabaseQuery(DbId, "SELECT message_id, message_data, pushed_at FROM data WHERE topic_id = ? AND node_id = ? AND message_id > ? ORDER BY message_id LIMIT ?")
|
If Not DatabaseQuery(DbId, "SELECT d.message_id, d.message_data, d.pushed_at, COALESCE(a.size, 0), COALESCE(a.state, 0), a.sha256 " +
|
||||||
|
"FROM data d LEFT JOIN attachments a ON a.topic_id = d.topic_id AND a.node_id = d.node_id AND a.message_id = d.message_id " +
|
||||||
|
"WHERE d.topic_id = ? AND d.node_id = ? AND d.message_id > ? ORDER BY d.message_id LIMIT ?")
|
||||||
ProcedureReturn #False
|
ProcedureReturn #False
|
||||||
EndIf
|
EndIf
|
||||||
|
|
||||||
@@ -768,6 +833,7 @@ Procedure.i GetMessagesAfter(DbId.i, TopicId.i, NodeId.i, AfterMessageId.q, Limi
|
|||||||
Messages()\MessageId = GetDatabaseQuad(DbId, 0)
|
Messages()\MessageId = GetDatabaseQuad(DbId, 0)
|
||||||
Messages()\JsonData = GetDatabaseString(DbId, 1)
|
Messages()\JsonData = GetDatabaseString(DbId, 1)
|
||||||
Messages()\PushedAt = GetDatabaseQuad(DbId, 2)
|
Messages()\PushedAt = GetDatabaseQuad(DbId, 2)
|
||||||
|
BakaShrot_ReadAttachmentColumns(DbId, 3, @Messages())
|
||||||
Chars + Len(Messages()\JsonData)
|
Chars + Len(Messages()\JsonData)
|
||||||
Wend
|
Wend
|
||||||
FinishDatabaseQuery(DbId)
|
FinishDatabaseQuery(DbId)
|
||||||
@@ -800,6 +866,9 @@ EndProcedure
|
|||||||
; Every write: pushes (group commit), replicated batches, the WAL checkpoints.
|
; Every write: pushes (group commit), replicated batches, the WAL checkpoints.
|
||||||
XIncludeFile "Writer.pbi"
|
XIncludeFile "Writer.pbi"
|
||||||
|
|
||||||
|
; Attachments: uploads, parts, reading them back, the replicated ones.
|
||||||
|
XIncludeFile "Attachments.pbi"
|
||||||
|
|
||||||
|
|
||||||
; Usage example. Only compiled when this file is run directly (F5 in the
|
; Usage example. Only compiled when this file is run directly (F5 in the
|
||||||
; IDE), not when it's included as a module by the rest of the project.
|
; IDE), not when it's included as a module by the rest of the project.
|
||||||
|
|||||||
+106
-7
@@ -110,6 +110,8 @@ Structure BakaShrot_PushJob
|
|||||||
JsonData.s
|
JsonData.s
|
||||||
; When it arrived, ms since 1970 UTC.
|
; When it arrived, ms since 1970 UTC.
|
||||||
PushedAt.q
|
PushedAt.q
|
||||||
|
; Its attachment, a complete upload (blobs), 0 for none.
|
||||||
|
BlobId.q
|
||||||
|
|
||||||
; Filled in by whoever writes it, under the write mutex.
|
; Filled in by whoever writes it, under the write mutex.
|
||||||
MessageId.q
|
MessageId.q
|
||||||
@@ -641,6 +643,77 @@ Procedure BakaShrot_Writer_LogStats()
|
|||||||
EndProcedure
|
EndProcedure
|
||||||
|
|
||||||
|
|
||||||
|
; Claims a complete upload (blobs state 1) of TopicId/NodeId for a message:
|
||||||
|
; state 2. Returns #False if it isn't one, someone else's, or attached already.
|
||||||
|
Procedure.i BakaShrot_Writer_ClaimBlob(BlobId.q, TopicId.i, NodeId.i)
|
||||||
|
Protected DbId.i = BakaShrot_Storage_Writer\DbId
|
||||||
|
SetDatabaseQuad(DbId, 0, BlobId)
|
||||||
|
SetDatabaseLong(DbId, 1, TopicId)
|
||||||
|
SetDatabaseLong(DbId, 2, NodeId)
|
||||||
|
If Not DatabaseUpdate(DbId, "UPDATE blobs SET state = 2 WHERE blob_id = ? AND topic_id = ? AND node_id = ? AND state = 1")
|
||||||
|
BakaShrot_Storage_Writer\LastError = DatabaseError()
|
||||||
|
ProcedureReturn #False
|
||||||
|
EndIf
|
||||||
|
If AffectedDatabaseRows(DbId) <> 1
|
||||||
|
BakaShrot_Storage_Writer\LastError = "the upload isn't complete, or isn't this client's for that topic"
|
||||||
|
ProcedureReturn #False
|
||||||
|
EndIf
|
||||||
|
ProcedureReturn #True
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
; Gives a claimed upload back (state 1), its message couldn't be stored.
|
||||||
|
Procedure BakaShrot_Writer_UnclaimBlob(BlobId.q)
|
||||||
|
Protected DbId.i = BakaShrot_Storage_Writer\DbId
|
||||||
|
SetDatabaseQuad(DbId, 0, BlobId)
|
||||||
|
DatabaseUpdate(DbId, "UPDATE blobs SET state = 1 WHERE blob_id = ?")
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
; The attachments row of a pushed message, from its claimed upload.
|
||||||
|
Procedure.i BakaShrot_Writer_LinkBlob(TopicId.i, NodeId.i, MessageId.q, BlobId.q)
|
||||||
|
Protected DbId.i = BakaShrot_Storage_Writer\DbId
|
||||||
|
SetDatabaseLong(DbId, 0, TopicId)
|
||||||
|
SetDatabaseLong(DbId, 1, NodeId)
|
||||||
|
SetDatabaseQuad(DbId, 2, MessageId)
|
||||||
|
SetDatabaseQuad(DbId, 3, BlobId)
|
||||||
|
If Not DatabaseUpdate(DbId, "INSERT INTO attachments (topic_id, node_id, message_id, size, sha256, blob_id, state) " +
|
||||||
|
"SELECT ?, ?, ?, size, sha256, blob_id, 2 FROM blobs WHERE blob_id = ?") Or AffectedDatabaseRows(DbId) <> 1
|
||||||
|
BakaShrot_Storage_Writer\LastError = "can't attach the upload: " + DatabaseError()
|
||||||
|
ProcedureReturn #False
|
||||||
|
EndIf
|
||||||
|
ProcedureReturn #True
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
; Deletes a message just inserted in this transaction, its attachment failed.
|
||||||
|
Procedure BakaShrot_Writer_DropMessage(TopicId.i, NodeId.i, MessageId.q)
|
||||||
|
Protected DbId.i = BakaShrot_Storage_Writer\DbId
|
||||||
|
SetDatabaseLong(DbId, 0, TopicId)
|
||||||
|
SetDatabaseLong(DbId, 1, NodeId)
|
||||||
|
SetDatabaseQuad(DbId, 2, MessageId)
|
||||||
|
DatabaseUpdate(DbId, "DELETE FROM data WHERE topic_id = ? AND node_id = ? AND message_id = ?")
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
; The attachments row of a replicated message: its data comes later
|
||||||
|
; (Attachments.pbi), state 0 (missing), or 3 (not kept here) past MaxSize.
|
||||||
|
Procedure.i BakaShrot_Writer_AddReplicatedAttachment(TopicId.i, NodeId.i, *Message.BakaShrot_ReplicatedMessage, MaxSize.q)
|
||||||
|
Protected DbId.i = BakaShrot_Storage_Writer\DbId
|
||||||
|
SetDatabaseLong(DbId, 0, TopicId)
|
||||||
|
SetDatabaseLong(DbId, 1, NodeId)
|
||||||
|
SetDatabaseQuad(DbId, 2, *Message\MessageId)
|
||||||
|
SetDatabaseQuad(DbId, 3, *Message\AttachmentSize)
|
||||||
|
SetDatabaseBlob(DbId, 4, @*Message\AttachmentSha256[0], #BakaShrot_Sha256Size)
|
||||||
|
If *Message\AttachmentSize > MaxSize
|
||||||
|
SetDatabaseLong(DbId, 5, 3)
|
||||||
|
Else
|
||||||
|
SetDatabaseLong(DbId, 5, 0)
|
||||||
|
EndIf
|
||||||
|
If Not DatabaseUpdate(DbId, "INSERT OR IGNORE INTO attachments (topic_id, node_id, message_id, size, sha256, blob_id, state) VALUES (?, ?, ?, ?, ?, NULL, ?)")
|
||||||
|
BakaShrot_Storage_Writer\LastError = DatabaseError()
|
||||||
|
ProcedureReturn #False
|
||||||
|
EndIf
|
||||||
|
ProcedureReturn #True
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
|
||||||
; Writes queued pushes in one transaction, filling in their MessageId (-1 and
|
; Writes queued pushes in one transaction, filling in their MessageId (-1 and
|
||||||
; Error if that one failed) and setting Done. Holding the write mutex.
|
; Error if that one failed) and setting Done. Holding the write mutex.
|
||||||
Procedure BakaShrot_Writer_WriteJobs(List Jobs.i())
|
Procedure BakaShrot_Writer_WriteJobs(List Jobs.i())
|
||||||
@@ -656,12 +729,28 @@ Procedure BakaShrot_Writer_WriteJobs(List Jobs.i())
|
|||||||
Key = Str(*Job\TopicId) + ":" + Str(*Job\NodeId)
|
Key = Str(*Job\TopicId) + ":" + Str(*Job\NodeId)
|
||||||
MessageId = BakaShrot_Writer_NextId(Key, *Job\TopicId, *Job\NodeId)
|
MessageId = BakaShrot_Writer_NextId(Key, *Job\TopicId, *Job\NodeId)
|
||||||
JsonData = *Job\JsonData
|
JsonData = *Job\JsonData
|
||||||
|
*Job\MessageId = -1
|
||||||
|
|
||||||
|
; Its upload first: nothing is stored if it can't be claimed.
|
||||||
|
If MessageId > 0 And *Job\BlobId And Not BakaShrot_Writer_ClaimBlob(*Job\BlobId, *Job\TopicId, *Job\NodeId)
|
||||||
|
MessageId = -1
|
||||||
|
EndIf
|
||||||
|
|
||||||
If MessageId > 0 And BakaShrot_Writer_InsertRow(BakaShrot_Storage_Writer\Insert, *Job\TopicId, *Job\NodeId, MessageId, JsonData, *Job\PushedAt) = 1
|
If MessageId > 0 And BakaShrot_Writer_InsertRow(BakaShrot_Storage_Writer\Insert, *Job\TopicId, *Job\NodeId, MessageId, JsonData, *Job\PushedAt) = 1
|
||||||
*Job\MessageId = MessageId
|
If *Job\BlobId And Not BakaShrot_Writer_LinkBlob(*Job\TopicId, *Job\NodeId, MessageId, *Job\BlobId)
|
||||||
|
BakaShrot_Writer_DropMessage(*Job\TopicId, *Job\NodeId, MessageId)
|
||||||
|
BakaShrot_Writer_UnclaimBlob(*Job\BlobId)
|
||||||
|
Else
|
||||||
|
*Job\MessageId = MessageId
|
||||||
|
EndIf
|
||||||
|
; Taken either way: node_heads went up.
|
||||||
BakaShrot_Storage_Writer\NextIds(Key) = MessageId + 1
|
BakaShrot_Storage_Writer\NextIds(Key) = MessageId + 1
|
||||||
Else
|
ElseIf MessageId > 0 And *Job\BlobId
|
||||||
*Job\MessageId = -1
|
BakaShrot_Writer_UnclaimBlob(*Job\BlobId)
|
||||||
*Job\Error = BakaShrot_Storage_Writer\LastError
|
EndIf
|
||||||
|
|
||||||
|
If *Job\MessageId < 1
|
||||||
|
*Job\Error = BakaShrot_Storage_Writer\LastError
|
||||||
EndIf
|
EndIf
|
||||||
Next
|
Next
|
||||||
|
|
||||||
@@ -685,9 +774,12 @@ EndProcedure
|
|||||||
|
|
||||||
; Inserts one JSON message for a topic_id/node_id pair, with the next
|
; Inserts one JSON message for a topic_id/node_id pair, with the next
|
||||||
; message_id for that pair, starting at 1, grouped with the other pushes
|
; message_id for that pair, starting at 1, grouped with the other pushes
|
||||||
; arriving meanwhile. Stamped with the time it got here (pushed_at). Returns the new message's id once committed, or -1 with
|
; arriving meanwhile. Stamped with the time it got here (pushed_at).
|
||||||
|
; BlobId: its attachment, a complete upload of this topic and node
|
||||||
|
; (Attachments.pbi), 0 for none: attached in the same transaction.
|
||||||
|
; Returns the new message's id once committed, or -1 with
|
||||||
; the reason in *Error\s.
|
; the reason in *Error\s.
|
||||||
Procedure.q InsertNextMessage(TopicId.i, NodeId.i, JsonData.s, *Error.String)
|
Procedure.q InsertNextMessage(TopicId.i, NodeId.i, JsonData.s, *Error.String, BlobId.q = 0)
|
||||||
Protected Job.BakaShrot_PushJob
|
Protected Job.BakaShrot_PushJob
|
||||||
Protected NewList Jobs.i()
|
Protected NewList Jobs.i()
|
||||||
Protected StartTicks.q
|
Protected StartTicks.q
|
||||||
@@ -696,6 +788,7 @@ Procedure.q InsertNextMessage(TopicId.i, NodeId.i, JsonData.s, *Error.String)
|
|||||||
Job\NodeId = NodeId
|
Job\NodeId = NodeId
|
||||||
Job\JsonData = JsonData
|
Job\JsonData = JsonData
|
||||||
Job\PushedAt = BakaShrot_NowUtcMs()
|
Job\PushedAt = BakaShrot_NowUtcMs()
|
||||||
|
Job\BlobId = BlobId
|
||||||
Job\MessageId = -1
|
Job\MessageId = -1
|
||||||
|
|
||||||
LockMutex(BakaShrot_Storage_QueueMutex)
|
LockMutex(BakaShrot_Storage_QueueMutex)
|
||||||
@@ -761,8 +854,10 @@ EndProcedure
|
|||||||
; past this server's max age for the topic already: not stored, but the
|
; past this server's max age for the topic already: not stored, but the
|
||||||
; pair's head still goes up to them, so the peer doesn't send them again.
|
; pair's head still goes up to them, so the peer doesn't send them again.
|
||||||
; *Skipped\i, if given, gets how many.
|
; *Skipped\i, if given, gets how many.
|
||||||
|
; A message's attachment gets its row, its data comes later (Attachments.pbi),
|
||||||
|
; unless it's bigger than MaxAttachmentSize: not kept here then.
|
||||||
; Returns #False with the reason in *Error\s, the transaction is rolled back.
|
; Returns #False with the reason in *Error\s, the transaction is rolled back.
|
||||||
Procedure.i InsertReplicatedMessages(TopicId.i, NodeId.i, List Messages.BakaShrot_ReplicatedMessage(), *Error.String, SkipBeforeMs.q = 0, *Skipped.Integer = 0)
|
Procedure.i InsertReplicatedMessages(TopicId.i, NodeId.i, List Messages.BakaShrot_ReplicatedMessage(), *Error.String, SkipBeforeMs.q = 0, *Skipped.Integer = 0, MaxAttachmentSize.q = #BakaShrot_MaxAttachmentSize)
|
||||||
Protected Stored.i, Inserted.i, Key.s, JsonData.s, Skipped.i, LastMessageId.q
|
Protected Stored.i, Inserted.i, Key.s, JsonData.s, Skipped.i, LastMessageId.q
|
||||||
|
|
||||||
Key = Str(TopicId) + ":" + Str(NodeId)
|
Key = Str(TopicId) + ":" + Str(NodeId)
|
||||||
@@ -790,6 +885,10 @@ Procedure.i InsertReplicatedMessages(TopicId.i, NodeId.i, List Messages.BakaShro
|
|||||||
Stored = #False
|
Stored = #False
|
||||||
Break
|
Break
|
||||||
EndIf
|
EndIf
|
||||||
|
If Inserted = 1 And Messages()\AttachmentSize > 0 And Not BakaShrot_Writer_AddReplicatedAttachment(TopicId, NodeId, @Messages(), MaxAttachmentSize)
|
||||||
|
Stored = #False
|
||||||
|
Break
|
||||||
|
EndIf
|
||||||
; A pair pushed to here too (drift): the next push goes after it.
|
; A pair pushed to here too (drift): the next push goes after it.
|
||||||
If Inserted = 1 And FindMapElement(BakaShrot_Storage_Writer\NextIds(), Key)
|
If Inserted = 1 And FindMapElement(BakaShrot_Storage_Writer\NextIds(), Key)
|
||||||
If Messages()\MessageId + 1 > BakaShrot_Storage_Writer\NextIds()
|
If Messages()\MessageId + 1 > BakaShrot_Storage_Writer\NextIds()
|
||||||
|
|||||||
@@ -0,0 +1,126 @@
|
|||||||
|
// Changes from v6 (Design/Attachments.md):
|
||||||
|
// - attachments, blobs, blob_chunks: a message's attachment (one at most),
|
||||||
|
// its data, in 1 MB parts. Replace the placeholder "attachements" table,
|
||||||
|
// dropped.
|
||||||
|
// - Triggers: deleting a message deletes its attachment row, which marks
|
||||||
|
// its blob to delete (Retention.pbi deletes the parts).
|
||||||
|
//
|
||||||
|
// Needs SQLite 3.38+ with its JSON functions (json_valid, ->>), see Storage.pbi.
|
||||||
|
// The database is in WAL mode, see Storage.pbi and Writer.pbi.
|
||||||
|
|
||||||
|
table data {
|
||||||
|
topic_id integer [not null]
|
||||||
|
node_id integer [not null]
|
||||||
|
message_id integer [not null]
|
||||||
|
message_data text [not null]
|
||||||
|
|
||||||
|
// 1 if message_data is well-formed JSON, 0 otherwise.
|
||||||
|
// Can't be written, SQLite computes it on insert and stores it.
|
||||||
|
is_json integer [not null, note: 'GENERATED ALWAYS AS (json_valid(message_data)) STORED']
|
||||||
|
|
||||||
|
// When it was pushed to its origin, ms since 1970-01-01 UTC.
|
||||||
|
pushed_at integer [not null, default: 0]
|
||||||
|
|
||||||
|
indexes {
|
||||||
|
(topic_id, node_id, message_id) [unique]
|
||||||
|
message_id
|
||||||
|
(topic_id, pushed_at)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// One row per topic/node id that has ever had messages: deleting messages
|
||||||
|
// (the retention) leaves it as is, so ids never go back.
|
||||||
|
// AFTER INSERT ON data: INSERT ... ON CONFLICT DO UPDATE SET
|
||||||
|
// max_message_id = MAX(max_message_id, excluded.max_message_id)
|
||||||
|
// Only fires for rows actually inserted (not the ones INSERT OR IGNORE drops).
|
||||||
|
table node_heads [note: 'WITHOUT ROWID'] {
|
||||||
|
topic_id integer [not null]
|
||||||
|
node_id integer [not null]
|
||||||
|
max_message_id integer [not null]
|
||||||
|
|
||||||
|
indexes {
|
||||||
|
(topic_id, node_id) [pk]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A message's attachment (Design/Attachments.md). Its size and SHA-256 come
|
||||||
|
// with it (pushed, or replicated), its data in blob_id once any is here.
|
||||||
|
// state: 0 missing (replicated, none here yet), 1 receiving, 2 ready,
|
||||||
|
// 3 not kept (bigger than this server's MaxAttachmentSize).
|
||||||
|
// AFTER DELETE ON data deletes it, AFTER DELETE ON attachments marks its
|
||||||
|
// blob to delete (state 3).
|
||||||
|
table attachments [note: 'WITHOUT ROWID'] {
|
||||||
|
topic_id integer [not null]
|
||||||
|
node_id integer [not null]
|
||||||
|
message_id integer [not null]
|
||||||
|
size integer [not null]
|
||||||
|
sha256 blob [not null]
|
||||||
|
blob_id integer
|
||||||
|
state integer [not null]
|
||||||
|
|
||||||
|
indexes {
|
||||||
|
(topic_id, node_id, message_id) [pk]
|
||||||
|
state
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The data of one attachment, being received (an upload, or replicated) or
|
||||||
|
// stored. topic_id, node_id: an upload's owner, or the message's pair.
|
||||||
|
// received: bytes stored so far. created_at: ms since 1970 UTC, an upload
|
||||||
|
// not pushed with its message within UploadTimeout is deleted.
|
||||||
|
// state: 0 receiving, 1 complete (an upload waiting for its message),
|
||||||
|
// 2 attached, 3 to delete.
|
||||||
|
table blobs {
|
||||||
|
blob_id integer [pk]
|
||||||
|
topic_id integer [not null]
|
||||||
|
node_id integer [not null]
|
||||||
|
size integer [not null]
|
||||||
|
sha256 blob [not null]
|
||||||
|
received integer [not null, default: 0]
|
||||||
|
state integer [not null]
|
||||||
|
created_at integer [not null]
|
||||||
|
|
||||||
|
indexes {
|
||||||
|
state
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Its parts, #BakaShrot_AttachmentChunkSize (1 MB) each, the last one
|
||||||
|
// what's left.
|
||||||
|
table blob_chunks {
|
||||||
|
blob_id integer [not null]
|
||||||
|
chunk_index integer [not null]
|
||||||
|
chunk_data blob [not null]
|
||||||
|
|
||||||
|
indexes {
|
||||||
|
(blob_id, chunk_index) [pk]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// origin: "config" (named in [BakaShrot.Topics]), "id" (unnamed, name is
|
||||||
|
// the id in digits).
|
||||||
|
table topics {
|
||||||
|
topic_id integer [pk]
|
||||||
|
name text [not null, unique, note: 'COLLATE NOCASE']
|
||||||
|
origin text [not null]
|
||||||
|
}
|
||||||
|
|
||||||
|
// origin: "config" (named in [BakaShrot.Nodes]), "id" (unnamed), "peer"
|
||||||
|
// (only in databases from the short-lived version that added peer nodes).
|
||||||
|
table nodes {
|
||||||
|
node_id integer [pk]
|
||||||
|
name text [not null, unique, note: 'COLLATE NOCASE']
|
||||||
|
origin text [not null]
|
||||||
|
}
|
||||||
|
|
||||||
|
// View messages:
|
||||||
|
// SELECT t.name AS topic, n.name AS node, d.message_id, d.message_data,
|
||||||
|
// d.is_json, d.topic_id, d.node_id, d.pushed_at,
|
||||||
|
// strftime('%Y-%m-%dT%H:%M:%fZ', d.pushed_at / 1000.0, 'unixepoch') AS pushed_utc
|
||||||
|
// FROM data d JOIN topics t ON t.topic_id = d.topic_id
|
||||||
|
// JOIN nodes n ON n.node_id = d.node_id
|
||||||
|
// WHERE topic = ... AND node = ... goes through the name indexes, then
|
||||||
|
// data's (topic_id, node_id, message_id) one.
|
||||||
|
|
||||||
|
// Note, ignore it
|
||||||
|
// msg_type TEXT GENERATED ALWAYS AS (data ->> '$.messageData.MsgType') VIRTUAL
|
||||||
@@ -0,0 +1,373 @@
|
|||||||
|
; ============================================================================
|
||||||
|
; A raw protocol client for the attachment cases the DLL never produces, run
|
||||||
|
; by Tests/AttachmentEdges-Test.ps1 against a running server.
|
||||||
|
;
|
||||||
|
; Usage:
|
||||||
|
; AttachmentEdgeClient edge <KitchenIni> <GarageIni>
|
||||||
|
; Wrong SHA-256, parts out of order / of the wrong size / repeated,
|
||||||
|
; someone else's upload, the wrong topic, an upload attached twice, too
|
||||||
|
; big, a part out of range. Then starts two uploads it leaves behind
|
||||||
|
; (one half sent, one complete but never pushed) and prints
|
||||||
|
; "LEFT <PartialId> <CompleteId>".
|
||||||
|
; AttachmentEdgeClient late <KitchenIni> <PartialId> <CompleteId>
|
||||||
|
; Once they expired: both refused.
|
||||||
|
; The inis are client.ini's: PrivateKey, PublicKey, ServerPublicKey, Topic,
|
||||||
|
; Node, ServerHost, ServerPort. Kitchen may push to logs and other, garage
|
||||||
|
; to logs; the server's MaxAttachmentSize must be under 1G.
|
||||||
|
; Compile as a thread-safe console program into Build\. Exits with 0 if
|
||||||
|
; every check passed, 1 otherwise.
|
||||||
|
; ============================================================================
|
||||||
|
|
||||||
|
EnableExplicit
|
||||||
|
|
||||||
|
XIncludeFile "../Commons/Networking/Outbound.pbi"
|
||||||
|
|
||||||
|
Structure EdgeClient
|
||||||
|
Outbound.BakaShrot_Outbound
|
||||||
|
Identity.BakaShrot_OutboundIdentity
|
||||||
|
PrivateKey.a[#BakaShrot_Ed25519_PrivateKeySize]
|
||||||
|
ServerPublicKey.a[#BakaShrot_Ed25519_PublicKeySize]
|
||||||
|
EndStructure
|
||||||
|
|
||||||
|
Global Fails.i = 0
|
||||||
|
|
||||||
|
Procedure Check(What.s, Ok.i, Detail.s = "")
|
||||||
|
If Ok
|
||||||
|
PrintN("PASS " + What)
|
||||||
|
Else
|
||||||
|
PrintN("FAIL " + What)
|
||||||
|
Fails + 1
|
||||||
|
EndIf
|
||||||
|
PrintN(" -> " + Detail)
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
Procedure.i ConnectIni(*Client.EdgeClient, IniPath.s)
|
||||||
|
Protected Host.s, Port.i, Ok.i
|
||||||
|
|
||||||
|
If Not OpenPreferences(IniPath)
|
||||||
|
ProcedureReturn #False
|
||||||
|
EndIf
|
||||||
|
PreferenceGroup("BakaShrot")
|
||||||
|
Ok = DecodeKeyFromString(ReadPreferenceString("PrivateKey", ""), @*Client\PrivateKey[0], #BakaShrot_Ed25519_PrivateKeySize)
|
||||||
|
Ok = Bool(Ok And DecodeKeyFromString(ReadPreferenceString("ServerPublicKey", ""), @*Client\ServerPublicKey[0], #BakaShrot_Ed25519_PublicKeySize))
|
||||||
|
*Client\Identity\PublicKey = ReadPreferenceString("PublicKey", "")
|
||||||
|
*Client\Identity\Topic = ReadPreferenceString("Topic", "")
|
||||||
|
*Client\Identity\Node = ReadPreferenceString("Node", "")
|
||||||
|
*Client\Identity\PrivateKey = @*Client\PrivateKey[0]
|
||||||
|
Host = ReadPreferenceString("ServerHost", "127.0.0.1")
|
||||||
|
Port = ReadPreferenceLong("ServerPort", 0)
|
||||||
|
ClosePreferences()
|
||||||
|
If Not Ok
|
||||||
|
ProcedureReturn #False
|
||||||
|
EndIf
|
||||||
|
ProcedureReturn BakaShrot_Outbound_Connect(@*Client\Outbound, Host, Port, @*Client\Identity, @*Client\ServerPublicKey[0])
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
; Sends *Packet (freed), returns the answer with its type, 0 if the link failed.
|
||||||
|
Procedure.i Exchange(*Client.EdgeClient, *Packet, Size.i, *Type.Integer, *AnswerSize.Integer)
|
||||||
|
Protected *Answer
|
||||||
|
*Type\i = 0
|
||||||
|
If Not *Packet
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
If Not BakaShrot_Outbound_Send(@*Client\Outbound, *Packet, Size)
|
||||||
|
FreeMemory(*Packet)
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
FreeMemory(*Packet)
|
||||||
|
*Answer = BakaShrot_Outbound_WaitPacket(@*Client\Outbound, *AnswerSize, 20000)
|
||||||
|
If *Answer
|
||||||
|
*Type\i = BakaShrot_GetPacketType(*Answer, *AnswerSize\i)
|
||||||
|
EndIf
|
||||||
|
ProcedureReturn *Answer
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
Procedure.s Refusal(*Answer, Size.i)
|
||||||
|
Protected *View.MsgPackData, *Refused.BakaShrot_RequestRefused, Reason.s
|
||||||
|
*View = MsgPackWrapMsgBuffer(*Answer, Size)
|
||||||
|
If *View
|
||||||
|
*Refused = BakaShrot_RequestRefusedPacket_Decode(*View)
|
||||||
|
MsgPackFree(*View, #False)
|
||||||
|
If *Refused
|
||||||
|
Reason = *Refused\Reason
|
||||||
|
FreeStructure(*Refused)
|
||||||
|
EndIf
|
||||||
|
EndIf
|
||||||
|
ProcedureReturn Reason
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
; Starts an upload. Returns its id, 0 if refused (reason in *Reason\s).
|
||||||
|
Procedure.q StartUpload(*Client.EdgeClient, Topic.s, Size.q, *Sha256, *Reason.String)
|
||||||
|
Protected Start.BakaShrot_UploadStart, *Started.BakaShrot_UploadStarted
|
||||||
|
Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer, Type.Integer, *View.MsgPackData, Id.q
|
||||||
|
|
||||||
|
*Reason\s = ""
|
||||||
|
Start\Topic = Topic
|
||||||
|
Start\Size = Size
|
||||||
|
CopyMemory(*Sha256, @Start\Sha256[0], #BakaShrot_Sha256Size)
|
||||||
|
*Packet = BakaShrot_UploadStartPacket_Encode(@Start, @PacketSize)
|
||||||
|
*Answer = Exchange(*Client, *Packet, PacketSize\i, @Type, @AnswerSize)
|
||||||
|
If Not *Answer
|
||||||
|
*Reason\s = "the link failed"
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
If Type\i = #BakaShrot_PacketType_RequestRefused
|
||||||
|
*Reason\s = Refusal(*Answer, AnswerSize\i)
|
||||||
|
ElseIf Type\i = #BakaShrot_PacketType_UploadStarted
|
||||||
|
*View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i)
|
||||||
|
*Started = BakaShrot_UploadStartedPacket_Decode(*View)
|
||||||
|
MsgPackFree(*View, #False)
|
||||||
|
If *Started
|
||||||
|
Id = *Started\UploadId
|
||||||
|
FreeStructure(*Started)
|
||||||
|
EndIf
|
||||||
|
EndIf
|
||||||
|
FreeMemory(*Answer)
|
||||||
|
ProcedureReturn Id
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
; Sends a part. Returns 1 if stored (*Complete\i set), 0 if refused (reason), -1 if the link failed.
|
||||||
|
Procedure.i SendChunk(*Client.EdgeClient, UploadId.q, Index.i, *Data, Size.i, *Complete.Integer, *Reason.String)
|
||||||
|
Protected Chunk.BakaShrot_UploadChunk, *Stored.BakaShrot_ChunkStored
|
||||||
|
Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer, Type.Integer, *View.MsgPackData, Result.i = -1
|
||||||
|
|
||||||
|
*Reason\s = ""
|
||||||
|
Chunk\UploadId = UploadId
|
||||||
|
Chunk\ChunkIndex = Index
|
||||||
|
Chunk\Data = *Data
|
||||||
|
Chunk\DataSize = Size
|
||||||
|
*Packet = BakaShrot_UploadChunkPacket_Encode(@Chunk, @PacketSize)
|
||||||
|
*Answer = Exchange(*Client, *Packet, PacketSize\i, @Type, @AnswerSize)
|
||||||
|
If Not *Answer
|
||||||
|
ProcedureReturn -1
|
||||||
|
EndIf
|
||||||
|
If Type\i = #BakaShrot_PacketType_RequestRefused
|
||||||
|
*Reason\s = Refusal(*Answer, AnswerSize\i)
|
||||||
|
Result = 0
|
||||||
|
ElseIf Type\i = #BakaShrot_PacketType_ChunkStored
|
||||||
|
*View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i)
|
||||||
|
*Stored = BakaShrot_ChunkStoredPacket_Decode(*View)
|
||||||
|
MsgPackFree(*View, #False)
|
||||||
|
If *Stored
|
||||||
|
*Complete\i = *Stored\Complete
|
||||||
|
FreeStructure(*Stored)
|
||||||
|
Result = 1
|
||||||
|
EndIf
|
||||||
|
EndIf
|
||||||
|
FreeMemory(*Answer)
|
||||||
|
ProcedureReturn Result
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
; Pushes a message with UploadId. Returns its id, 0 if refused (reason).
|
||||||
|
Procedure.q Push(*Client.EdgeClient, Topic.s, Json.s, UploadId.q, *Reason.String)
|
||||||
|
Protected Push.BakaShrot_PushMessage, *Pushed.BakaShrot_MessagePushed
|
||||||
|
Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer, Type.Integer, *View.MsgPackData, Id.q
|
||||||
|
|
||||||
|
*Reason\s = ""
|
||||||
|
Push\Topic = Topic
|
||||||
|
Push\JsonData = Json
|
||||||
|
Push\UploadId = UploadId
|
||||||
|
*Packet = BakaShrot_PushMessagePacket_Encode(@Push, @PacketSize)
|
||||||
|
*Answer = Exchange(*Client, *Packet, PacketSize\i, @Type, @AnswerSize)
|
||||||
|
If Not *Answer
|
||||||
|
*Reason\s = "the link failed"
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
If Type\i = #BakaShrot_PacketType_RequestRefused
|
||||||
|
*Reason\s = Refusal(*Answer, AnswerSize\i)
|
||||||
|
ElseIf Type\i = #BakaShrot_PacketType_MessagePushed
|
||||||
|
*View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i)
|
||||||
|
*Pushed = BakaShrot_MessagePushedPacket_Decode(*View)
|
||||||
|
MsgPackFree(*View, #False)
|
||||||
|
If *Pushed
|
||||||
|
Id = *Pushed\MessageId
|
||||||
|
FreeStructure(*Pushed)
|
||||||
|
EndIf
|
||||||
|
EndIf
|
||||||
|
FreeMemory(*Answer)
|
||||||
|
ProcedureReturn Id
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
; Asks for a part. Returns it (free with _Free), 0 if refused (reason).
|
||||||
|
Procedure.i GetChunk(*Client.EdgeClient, Topic.s, Node.s, MessageId.q, Index.i, *Reason.String)
|
||||||
|
Protected Request.BakaShrot_GetAttachment, *Chunk.BakaShrot_AttachmentChunk
|
||||||
|
Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer, Type.Integer, *View.MsgPackData
|
||||||
|
|
||||||
|
*Reason\s = ""
|
||||||
|
Request\Topic = Topic
|
||||||
|
Request\Node = Node
|
||||||
|
Request\MessageId = MessageId
|
||||||
|
Request\ChunkIndex = Index
|
||||||
|
*Packet = BakaShrot_GetAttachmentPacket_Encode(@Request, @PacketSize)
|
||||||
|
*Answer = Exchange(*Client, *Packet, PacketSize\i, @Type, @AnswerSize)
|
||||||
|
If Not *Answer
|
||||||
|
*Reason\s = "the link failed"
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
If Type\i = #BakaShrot_PacketType_RequestRefused
|
||||||
|
*Reason\s = Refusal(*Answer, AnswerSize\i)
|
||||||
|
ElseIf Type\i = #BakaShrot_PacketType_AttachmentChunk
|
||||||
|
*View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i)
|
||||||
|
*Chunk = BakaShrot_AttachmentChunkPacket_Decode(*View)
|
||||||
|
MsgPackFree(*View, #False)
|
||||||
|
EndIf
|
||||||
|
FreeMemory(*Answer)
|
||||||
|
ProcedureReturn *Chunk
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
; Size random bytes.
|
||||||
|
Procedure.i RandomBytes(Size.i)
|
||||||
|
Protected *Data = AllocateMemory(Size)
|
||||||
|
RandomData(*Data, Size)
|
||||||
|
ProcedureReturn *Data
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
Procedure Sha256Of(*Data, Size.q, *Out)
|
||||||
|
Protected Hash.BakaShrot_Sha256
|
||||||
|
BakaShrot_Sha256_Start(@Hash)
|
||||||
|
BakaShrot_Sha256_Add(@Hash, *Data, Size)
|
||||||
|
BakaShrot_Sha256_Finish(@Hash, *Out)
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
; Uploads Size bytes of *Data properly. Returns the upload id, 0 on failure.
|
||||||
|
Procedure.q UploadAll(*Client.EdgeClient, Topic.s, *Data, Size.q)
|
||||||
|
Protected Dim Sha.a(31), Id.q, Index.i, Complete.Integer, Reason.String
|
||||||
|
Sha256Of(*Data, Size, @Sha(0))
|
||||||
|
Id = StartUpload(*Client, Topic, Size, @Sha(0), @Reason)
|
||||||
|
If Not Id
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
For Index = 0 To BakaShrot_AttachmentChunkCount(Size) - 1
|
||||||
|
If SendChunk(*Client, Id, Index, *Data + Index * #BakaShrot_AttachmentChunkSize, BakaShrot_AttachmentChunkBytes(Size, Index), @Complete, @Reason) <> 1
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
Next
|
||||||
|
If Not Complete\i
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
ProcedureReturn Id
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
|
||||||
|
Define Kitchen.EdgeClient, Garage.EdgeClient, Reason.String, Complete.Integer
|
||||||
|
Define Dim Sha.a(31), Dim WrongSha.a(31)
|
||||||
|
Define *Data, *Other, Id.q, Id2.q, MessageId.q, Result.i, *Chunk.BakaShrot_AttachmentChunk, Size.q
|
||||||
|
Define PartialId.q, CompleteId.q
|
||||||
|
|
||||||
|
OpenConsole()
|
||||||
|
If CountProgramParameters() < 3
|
||||||
|
PrintN("Usage: AttachmentEdgeClient edge <KitchenIni> <GarageIni> | late <KitchenIni> <PartialId> <CompleteId>")
|
||||||
|
End 1
|
||||||
|
EndIf
|
||||||
|
If Not ConnectIni(@Kitchen, ProgramParameter(1))
|
||||||
|
PrintN("FAIL can't connect with " + ProgramParameter(1))
|
||||||
|
End 1
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If LCase(ProgramParameter(0)) = "late"
|
||||||
|
PartialId = Val(ProgramParameter(2))
|
||||||
|
CompleteId = Val(ProgramParameter(3))
|
||||||
|
*Data = RandomBytes(#BakaShrot_AttachmentChunkSize)
|
||||||
|
Result = SendChunk(@Kitchen, PartialId, 1, *Data, 1000, @Complete, @Reason)
|
||||||
|
Check("An expired upload: its next part refused", Bool(Result = 0 And FindString(Reason\s, "No such upload in progress")), Reason\s)
|
||||||
|
MessageId = Push(@Kitchen, "logs", "{" + Chr(34) + "late" + Chr(34) + ":1}", CompleteId, @Reason)
|
||||||
|
Check("An expired complete upload: pushing with it refused", Bool(MessageId = 0 And (FindString(Reason\s, "No such upload") Or FindString(Reason\s, "isn't complete"))), Reason\s)
|
||||||
|
Check("Still connected after the refusals", BakaShrot_Outbound_IsConnected(@Kitchen\Outbound))
|
||||||
|
BakaShrot_Outbound_Close(@Kitchen\Outbound, #BakaShrot_ConnectionStatus_Disconnected)
|
||||||
|
PrintN("")
|
||||||
|
If Fails : PrintN(Str(Fails) + " FAILED") : End 1 : EndIf
|
||||||
|
PrintN("All passed")
|
||||||
|
End 0
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If Not ConnectIni(@Garage, ProgramParameter(2))
|
||||||
|
PrintN("FAIL can't connect with " + ProgramParameter(2))
|
||||||
|
End 1
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; --- A wrong SHA-256 --------------------------------------------------------------
|
||||||
|
Size = #BakaShrot_AttachmentChunkSize + 500000
|
||||||
|
*Data = RandomBytes(Size)
|
||||||
|
*Other = RandomBytes(Size)
|
||||||
|
Sha256Of(*Other, Size, @WrongSha(0))
|
||||||
|
Id = StartUpload(@Kitchen, "logs", Size, @WrongSha(0), @Reason)
|
||||||
|
Check("Upload with a wrong SHA-256: started", Bool(Id > 0), Reason\s)
|
||||||
|
Result = SendChunk(@Kitchen, Id, 0, *Data, #BakaShrot_AttachmentChunkSize, @Complete, @Reason)
|
||||||
|
Check(" part 0 stored, not complete", Bool(Result = 1 And Complete\i = 0), Reason\s)
|
||||||
|
Result = SendChunk(@Kitchen, Id, 1, *Data + #BakaShrot_AttachmentChunkSize, 500000, @Complete, @Reason)
|
||||||
|
Check(" the last part: refused, doesn't match", Bool(Result = 0 And FindString(Reason\s, "doesn't match its SHA-256")), Reason\s)
|
||||||
|
MessageId = Push(@Kitchen, "logs", "{" + Chr(34) + "bad" + Chr(34) + ":1}", Id, @Reason)
|
||||||
|
Check(" pushing with it: refused", Bool(MessageId = 0 And FindString(Reason\s, "isn't complete")), Reason\s)
|
||||||
|
Result = SendChunk(@Kitchen, Id, 1, *Data + #BakaShrot_AttachmentChunkSize, 500000, @Complete, @Reason)
|
||||||
|
Check(" sending the last part again: refused, it's dropped", Bool(Result = 0 And FindString(Reason\s, "No such upload in progress")), Reason\s)
|
||||||
|
|
||||||
|
; --- Parts out of order, wrong size, repeated ---------------------------------------
|
||||||
|
Size = 2 * #BakaShrot_AttachmentChunkSize + 1234
|
||||||
|
FreeMemory(*Data) : *Data = RandomBytes(Size)
|
||||||
|
Sha256Of(*Data, Size, @Sha(0))
|
||||||
|
Id = StartUpload(@Kitchen, "logs", Size, @Sha(0), @Reason)
|
||||||
|
Check("Upload of 3 parts: started", Bool(Id > 0), Reason\s)
|
||||||
|
Result = SendChunk(@Kitchen, Id, 1, *Data + #BakaShrot_AttachmentChunkSize, #BakaShrot_AttachmentChunkSize, @Complete, @Reason)
|
||||||
|
Check(" part 1 first: refused", Bool(Result = 0 And FindString(Reason\s, "Expected part 0 of 3")), Reason\s)
|
||||||
|
Result = SendChunk(@Kitchen, Id, 0, *Data, 1000, @Complete, @Reason)
|
||||||
|
Check(" part 0 too short: refused", Bool(Result = 0 And FindString(Reason\s, "1048576 bytes")), Reason\s)
|
||||||
|
Result = SendChunk(@Kitchen, Id, 0, *Data, #BakaShrot_AttachmentChunkSize, @Complete, @Reason)
|
||||||
|
Check(" part 0 right: stored, the refusals didn't drop the upload", Bool(Result = 1 And Complete\i = 0), Reason\s)
|
||||||
|
Result = SendChunk(@Kitchen, Id, 0, *Data, #BakaShrot_AttachmentChunkSize, @Complete, @Reason)
|
||||||
|
Check(" part 0 again: refused", Bool(Result = 0 And FindString(Reason\s, "Expected part 1")), Reason\s)
|
||||||
|
Result = SendChunk(@Garage, Id, 1, *Data + #BakaShrot_AttachmentChunkSize, #BakaShrot_AttachmentChunkSize, @Complete, @Reason)
|
||||||
|
Check(" part 1 from another client: refused", Bool(Result = 0 And FindString(Reason\s, "No such upload in progress")), Reason\s)
|
||||||
|
Result = SendChunk(@Kitchen, Id, 1, *Data + #BakaShrot_AttachmentChunkSize, #BakaShrot_AttachmentChunkSize, @Complete, @Reason)
|
||||||
|
Check(" part 1: stored", Bool(Result = 1 And Complete\i = 0), Reason\s)
|
||||||
|
Result = SendChunk(@Kitchen, Id, 2, *Data + 2 * #BakaShrot_AttachmentChunkSize, 1234, @Complete, @Reason)
|
||||||
|
Check(" part 2, the last: complete", Bool(Result = 1 And Complete\i = 1), Reason\s)
|
||||||
|
Result = SendChunk(@Kitchen, Id, 3, *Data, 10, @Complete, @Reason)
|
||||||
|
Check(" a part past the end: refused", Bool(Result = 0), Reason\s)
|
||||||
|
|
||||||
|
; --- Whose, which topic, how many times -------------------------------------------------
|
||||||
|
MessageId = Push(@Garage, "logs", "{" + Chr(34) + "theirs" + Chr(34) + ":1}", Id, @Reason)
|
||||||
|
Check("Another client pushing with it: refused", Bool(MessageId = 0 And FindString(Reason\s, "No such upload")), Reason\s)
|
||||||
|
MessageId = Push(@Kitchen, "other", "{" + Chr(34) + "topic" + Chr(34) + ":1}", Id, @Reason)
|
||||||
|
Check("Pushing it to another topic: refused", Bool(MessageId = 0 And FindString(Reason\s, "is for topic 'logs'")), Reason\s)
|
||||||
|
MessageId = Push(@Kitchen, "logs", "{" + Chr(34) + "edge" + Chr(34) + ":1}", Id, @Reason)
|
||||||
|
Check("Pushing it: stored", Bool(MessageId > 0), "message #" + Str(MessageId) + " " + Reason\s)
|
||||||
|
Id2 = Push(@Kitchen, "logs", "{" + Chr(34) + "edge" + Chr(34) + ":2}", Id, @Reason)
|
||||||
|
Check("Pushing it again: refused, attached already", Bool(Id2 = 0 And FindString(Reason\s, "attached already")), Reason\s)
|
||||||
|
Id2 = Push(@Kitchen, "logs", "{" + Chr(34) + "edge" + Chr(34) + ":3}", 999999, @Reason)
|
||||||
|
Check("An upload id that doesn't exist: refused", Bool(Id2 = 0 And FindString(Reason\s, "No such upload")), Reason\s)
|
||||||
|
|
||||||
|
; --- Reading it back, part by part ---------------------------------------------------------
|
||||||
|
*Chunk = GetChunk(@Kitchen, "logs", "kitchen", MessageId, 2, @Reason)
|
||||||
|
Check("GetAttachment part 2 first: the right bytes", Bool(*Chunk And *Chunk\DataSize = 1234 And *Chunk\Size = Size And CompareMemory(*Chunk\Data, *Data + 2 * #BakaShrot_AttachmentChunkSize, 1234) And CompareMemory(@*Chunk\Sha256[0], @Sha(0), 32)), Reason\s)
|
||||||
|
BakaShrot_AttachmentChunkPacket_Free(*Chunk)
|
||||||
|
*Chunk = GetChunk(@Kitchen, "logs", "kitchen", MessageId, 0, @Reason)
|
||||||
|
Check(" part 0: the right bytes", Bool(*Chunk And *Chunk\DataSize = #BakaShrot_AttachmentChunkSize And CompareMemory(*Chunk\Data, *Data, #BakaShrot_AttachmentChunkSize)), Reason\s)
|
||||||
|
BakaShrot_AttachmentChunkPacket_Free(*Chunk)
|
||||||
|
*Chunk = GetChunk(@Kitchen, "logs", "kitchen", MessageId, 3, @Reason)
|
||||||
|
Check(" part 3, past the end: refused", Bool(Not *Chunk And FindString(Reason\s, "has 3 parts")), Reason\s)
|
||||||
|
*Chunk = GetChunk(@Garage, "secret", "kitchen", MessageId, 0, @Reason)
|
||||||
|
Check(" from a topic garage may not read: refused", Bool(Not *Chunk And FindString(Reason\s, "Not allowed to read topic")), Reason\s)
|
||||||
|
|
||||||
|
; --- Limits ------------------------------------------------------------------------------------
|
||||||
|
Id = StartUpload(@Kitchen, "logs", 1024 * 1024 * 1024, @Sha(0), @Reason)
|
||||||
|
Check("Upload of 1 GB (over MaxAttachmentSize): refused", Bool(Id = 0 And FindString(Reason\s, "too big")), Reason\s)
|
||||||
|
Id = StartUpload(@Garage, "other", 1000, @Sha(0), @Reason)
|
||||||
|
Check("Upload to a topic garage may not push to: refused", Bool(Id = 0 And FindString(Reason\s, "Not allowed to push")), Reason\s)
|
||||||
|
Check("Both still connected after every refusal", Bool(BakaShrot_Outbound_IsConnected(@Kitchen\Outbound) And BakaShrot_Outbound_IsConnected(@Garage\Outbound)))
|
||||||
|
|
||||||
|
; --- Left behind, for the expiry ---------------------------------------------------------------------
|
||||||
|
Size = 2 * #BakaShrot_AttachmentChunkSize
|
||||||
|
FreeMemory(*Data) : *Data = RandomBytes(Size)
|
||||||
|
Sha256Of(*Data, Size, @Sha(0))
|
||||||
|
PartialId = StartUpload(@Kitchen, "logs", Size, @Sha(0), @Reason)
|
||||||
|
Result = SendChunk(@Kitchen, PartialId, 0, *Data, #BakaShrot_AttachmentChunkSize, @Complete, @Reason)
|
||||||
|
CompleteId = UploadAll(@Kitchen, "logs", *Data, 5000)
|
||||||
|
Check("Two uploads left behind: half sent, and complete but never pushed", Bool(PartialId > 0 And Result = 1 And CompleteId > 0), Str(PartialId) + ", " + Str(CompleteId))
|
||||||
|
|
||||||
|
BakaShrot_Outbound_Close(@Kitchen\Outbound, #BakaShrot_ConnectionStatus_Disconnected)
|
||||||
|
BakaShrot_Outbound_Close(@Garage\Outbound, #BakaShrot_ConnectionStatus_Disconnected)
|
||||||
|
PrintN("LEFT " + Str(PartialId) + " " + Str(CompleteId))
|
||||||
|
PrintN("")
|
||||||
|
If Fails : PrintN(Str(Fails) + " FAILED") : End 1 : EndIf
|
||||||
|
PrintN("All passed")
|
||||||
|
End 0
|
||||||
@@ -0,0 +1,287 @@
|
|||||||
|
# The attachment cases the regular clients never produce (Design/Attachments.md):
|
||||||
|
# 1. Through a raw client (Tests/AttachmentEdgeClient.pb): a wrong SHA-256,
|
||||||
|
# parts out of order / of the wrong size / repeated, someone else's
|
||||||
|
# upload, the wrong topic, an upload attached twice, too big, a part
|
||||||
|
# out of range.
|
||||||
|
# 2. Uploads left behind: kept within UploadTimeout, deleted past it, then
|
||||||
|
# refused.
|
||||||
|
# 3. Replication resuming: the receiving server killed in the middle of a
|
||||||
|
# 400 MB attachment, restarted, the sender goes on from where it stopped.
|
||||||
|
# 4. A corrupted attachment (bytes flipped in the sender's database): the
|
||||||
|
# client refuses it, the peer drops it and doesn't keep it.
|
||||||
|
# Two servers, A (port 12413) and B (12414). Needs Build\ (Build.ps1),
|
||||||
|
# Build\Bench\BenchServer.exe, Build\AttachmentEdgeClient.exe (compile
|
||||||
|
# Tests\AttachmentEdgeClient.pb, thread-safe console), and Python 3 for 4.
|
||||||
|
# Usage: powershell -ExecutionPolicy Bypass -File Tests\AttachmentEdges-Test.ps1 [-Python <python.exe>]
|
||||||
|
param(
|
||||||
|
[string]$Build = (Join-Path $PSScriptRoot "..\Build"),
|
||||||
|
[string]$Python = "python"
|
||||||
|
)
|
||||||
|
$ErrorActionPreference = "Stop"
|
||||||
|
$Build = (Resolve-Path $Build).Path
|
||||||
|
$Dir = Join-Path $Build "_attachedges"
|
||||||
|
Remove-Item -Recurse -Force $Dir -ErrorAction SilentlyContinue
|
||||||
|
New-Item -ItemType Directory $Dir | Out-Null
|
||||||
|
$Server = Join-Path $Build "Bench\BenchServer.exe"
|
||||||
|
$Fails = 0
|
||||||
|
|
||||||
|
function New-KeyPair {
|
||||||
|
$L = & (Join-Path $Build "KeyGen.exe")
|
||||||
|
@{ Priv = $L[0] -replace "^PrivateKey = ", ""; Pub = $L[1] -replace "^PublicKey = ", "" }
|
||||||
|
}
|
||||||
|
function Test-Port($P) {
|
||||||
|
$C = New-Object System.Net.Sockets.TcpClient
|
||||||
|
try { $A = $C.BeginConnect("127.0.0.1", $P, $null, $null); $A.AsyncWaitHandle.WaitOne(200) -and $C.Connected } catch { $false } finally { $C.Close() }
|
||||||
|
}
|
||||||
|
function Tool([string]$Name, [string[]]$A) {
|
||||||
|
$O = & (Join-Path $Build $Name) @A 2>&1
|
||||||
|
@{ Code = $LASTEXITCODE; Out = ($O -join " | "); Lines = @($O) }
|
||||||
|
}
|
||||||
|
function Check([string]$What, [bool]$Ok, [string]$Detail) {
|
||||||
|
if (-not $Ok) { $script:Fails++ }
|
||||||
|
"{0} {1}`n -> {2}" -f $(if ($Ok) { "PASS" } else { "FAIL" }), $What, $Detail
|
||||||
|
}
|
||||||
|
function Expect([string]$What, $Result, [string]$Pattern, [int]$Code = 0) {
|
||||||
|
Check $What (($Result.Code -eq $Code) -and ($Result.Out -match $Pattern)) ("[{0}] {1}" -f $Result.Code, $Result.Out)
|
||||||
|
}
|
||||||
|
function Start-Srv($Name) {
|
||||||
|
$Stop = Join-Path $Dir "$Name.stop"
|
||||||
|
Remove-Item $Stop -ErrorAction SilentlyContinue
|
||||||
|
# Each run its own log: a restart doesn't overwrite the last one's.
|
||||||
|
$script:Runs[$Name]++
|
||||||
|
$Log = Join-Path $Dir "$Name.$($script:Runs[$Name]).log"
|
||||||
|
$P = Start-Process -FilePath $Server -ArgumentList "`"$(Join-Path $Dir "$Name.ini")`"", "`"$Stop`"" -WorkingDirectory $Dir `
|
||||||
|
-RedirectStandardOutput $Log -WindowStyle Hidden -PassThru
|
||||||
|
$null = $P.Handle
|
||||||
|
@{ P = $P; Stop = $Stop; Name = $Name; Log = $Log }
|
||||||
|
}
|
||||||
|
$Runs = @{ a = 0; b = 0 }
|
||||||
|
function Stop-Srv($S) {
|
||||||
|
if (-not $S -or $S.P.HasExited) { return }
|
||||||
|
Set-Content $S.Stop "x"
|
||||||
|
if (-not $S.P.WaitForExit(30000)) { Stop-Process -Id $S.P.Id -Force }
|
||||||
|
}
|
||||||
|
function Wait-Port($Port, $S) {
|
||||||
|
$D = (Get-Date).AddSeconds(15)
|
||||||
|
while (-not (Test-Port $Port)) {
|
||||||
|
if ($S.P.HasExited) { throw "$($S.Name) exited: $(Get-Content $S.Log -Raw)" }
|
||||||
|
if ((Get-Date) -gt $D) { throw "$($S.Name) not listening" }
|
||||||
|
Start-Sleep -Milliseconds 100
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function Query($Sql, $Ini) {
|
||||||
|
$F = Join-Path $Dir "q.sql"; Set-Content $F -Encoding Ascii -Value $Sql
|
||||||
|
Tool "Query.exe" @("@$F", $Ini)
|
||||||
|
}
|
||||||
|
function Wait-Query($Sql, $Ini, $Pattern, $Seconds = 20) {
|
||||||
|
$D = (Get-Date).AddSeconds($Seconds)
|
||||||
|
do {
|
||||||
|
$R = Query $Sql $Ini
|
||||||
|
if ($R.Code -eq 0 -and $R.Out -match $Pattern) { return $R }
|
||||||
|
Start-Sleep -Milliseconds 250
|
||||||
|
} while ((Get-Date) -lt $D)
|
||||||
|
$R
|
||||||
|
}
|
||||||
|
function Push($Data, $Ini, [string]$Attach = "") {
|
||||||
|
$F = Join-Path $Dir "push.txt"
|
||||||
|
[IO.File]::WriteAllText($F, $Data, (New-Object System.Text.UTF8Encoding $false))
|
||||||
|
$A = @()
|
||||||
|
if ($Attach) { $A += @("-a", $Attach) }
|
||||||
|
Tool "PushMessage.exe" ($A + @("@$F", $Ini))
|
||||||
|
}
|
||||||
|
function New-File($Name, [int64]$Size, [int]$Seed) {
|
||||||
|
$P = Join-Path $Dir $Name
|
||||||
|
$R = New-Object System.Random $Seed
|
||||||
|
$Buf = New-Object byte[] ([math]::Min($Size, 16MB))
|
||||||
|
$F = [IO.File]::OpenWrite($P)
|
||||||
|
$Left = $Size
|
||||||
|
while ($Left -gt 0) { $R.NextBytes($Buf); $N = [math]::Min($Left, $Buf.Length); $F.Write($Buf, 0, $N); $Left -= $N }
|
||||||
|
$F.Close()
|
||||||
|
$P
|
||||||
|
}
|
||||||
|
function Hash($Path) { if (Test-Path $Path) { (Get-FileHash $Path -Algorithm SHA256).Hash } else { "no file" } }
|
||||||
|
function Num($Out) { if ($Out -match '\[\["(\d+)"\]\]') { [int64]$Matches[1] } else { -1 } }
|
||||||
|
|
||||||
|
$A = New-KeyPair; $B = New-KeyPair; $K = New-KeyPair; $G = New-KeyPair
|
||||||
|
|
||||||
|
foreach ($Name in "a", "b") {
|
||||||
|
$Me = @{ a = $A; b = $B }[$Name]; $Peer = @{ a = $B; b = $A }[$Name]
|
||||||
|
$PeerName = @{ a = "b"; b = "a" }[$Name]
|
||||||
|
$Port = @{ a = 12413; b = 12414 }[$Name]; $PeerPort = @{ a = 12414; b = 12413 }[$Name]
|
||||||
|
$Base = @{ a = 1; b = 100 }[$Name]
|
||||||
|
Set-Content (Join-Path $Dir "$Name.ini") -Encoding Ascii -Value @"
|
||||||
|
[BakaShrot]
|
||||||
|
PrivateKey = $($Me.Priv)
|
||||||
|
Topic = logs
|
||||||
|
Node = server$Name
|
||||||
|
|
||||||
|
[BakaShrot.Topics]
|
||||||
|
logs = $Base
|
||||||
|
other = $($Base + 1)
|
||||||
|
secret = $($Base + 2)
|
||||||
|
|
||||||
|
[BakaShrot.Nodes]
|
||||||
|
servera = $($Base + 10)
|
||||||
|
serverb = $($Base + 11)
|
||||||
|
kitchen = $($Base + 2)
|
||||||
|
garage = $($Base + 3)
|
||||||
|
|
||||||
|
[BakaShrot.Server]
|
||||||
|
Host = 127.0.0.1
|
||||||
|
Port = $Port
|
||||||
|
ReplicatingTopics = logs
|
||||||
|
DatabasePath = $(Join-Path $Dir "$Name.sqlite")
|
||||||
|
PeerSyncInterval = 1
|
||||||
|
PeerRetryDelay = 1
|
||||||
|
RetentionInterval = 1
|
||||||
|
MaxAttachmentSize = 512M
|
||||||
|
UploadTimeout = 10
|
||||||
|
|
||||||
|
[BakaShrot.Peer.$PeerName]
|
||||||
|
Host = 127.0.0.1
|
||||||
|
Port = $PeerPort
|
||||||
|
Topic = logs
|
||||||
|
Node = server$PeerName
|
||||||
|
PublicKey = $($Peer.Pub)
|
||||||
|
|
||||||
|
[BakaShrot.Client.$PeerName]
|
||||||
|
PublicKeys = $($Peer.Pub)
|
||||||
|
Identities = logs:server$PeerName
|
||||||
|
|
||||||
|
[BakaShrot.Client.kitchen]
|
||||||
|
PublicKeys = $($K.Pub)
|
||||||
|
Identities = logs:kitchen
|
||||||
|
PushTopics = logs;other;secret
|
||||||
|
ReadTopics = *
|
||||||
|
AllowQuery = 1
|
||||||
|
|
||||||
|
[BakaShrot.Client.garage]
|
||||||
|
PublicKeys = $($G.Pub)
|
||||||
|
Identities = logs:garage
|
||||||
|
PushTopics = logs
|
||||||
|
ReadTopics = logs
|
||||||
|
"@
|
||||||
|
}
|
||||||
|
$ServerKeys = @{ 12413 = $A.Pub; 12414 = $B.Pub }
|
||||||
|
function Client-Ini($Name, $Keys, $Node, $Port) {
|
||||||
|
$P = Join-Path $Dir "$Name.ini"
|
||||||
|
Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($Keys.Priv)`r`nPublicKey = $($Keys.Pub)`r`nTopic = logs`r`nNode = $Node`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($ServerKeys[$Port])"
|
||||||
|
$P
|
||||||
|
}
|
||||||
|
$KitchenA = Client-Ini "kitchen-a" $K "kitchen" 12413
|
||||||
|
$GarageA = Client-Ini "garage-a" $G "garage" 12413
|
||||||
|
$KitchenB = Client-Ini "kitchen-b" $K "kitchen" 12414
|
||||||
|
|
||||||
|
foreach ($Port in 12413, 12414) { if (Test-Port $Port) { throw "Port $Port is already in use" } }
|
||||||
|
$SA = Start-Srv "a"; $SB = $null
|
||||||
|
try {
|
||||||
|
Wait-Port 12413 $SA
|
||||||
|
|
||||||
|
"--- 1. Through the raw client"
|
||||||
|
$R = Tool "AttachmentEdgeClient.exe" @("edge", $KitchenA, $GarageA)
|
||||||
|
$R.Lines | Where-Object { $_ -match "^(PASS|FAIL| ->)" }
|
||||||
|
$Script:Fails += @($R.Lines | Where-Object { $_ -match "^FAIL" }).Count
|
||||||
|
Check "the raw client ran to the end" ($R.Code -ne $null -and ($R.Out -match "LEFT (\d+) (\d+)")) $R.Lines[-1]
|
||||||
|
$Partial = $Matches[1]; $Complete = $Matches[2]
|
||||||
|
$LeftAt = Get-Date
|
||||||
|
|
||||||
|
"--- 2. Uploads left behind (UploadTimeout = 10)"
|
||||||
|
$Sql = "SELECT blob_id, state, received FROM blobs WHERE blob_id IN ($Partial, $Complete) ORDER BY blob_id"
|
||||||
|
$R = Query $Sql $KitchenA
|
||||||
|
Check "within UploadTimeout: both kept, receiving (0) and complete (1)" ($R.Out -match "\[\[`"$Partial`",`"0`",`"1048576`"\],\[`"$Complete`",`"1`",`"5000`"\]\]") $R.Out
|
||||||
|
$R = Wait-Query "SELECT COUNT(*) FROM blobs WHERE blob_id IN ($Partial, $Complete)" $KitchenA '\[\["0"\]\]' 25
|
||||||
|
$After = ((Get-Date) - $LeftAt).TotalSeconds
|
||||||
|
Check "past it: both deleted" ($R.Out -match '\[\["0"\]\]') ("{0:N1} s after they were left" -f $After)
|
||||||
|
Check " not before 10 s" ($After -ge 8) ("{0:N1} s" -f $After)
|
||||||
|
Expect " their parts too" (Query "SELECT COUNT(*) FROM blob_chunks WHERE blob_id IN ($Partial, $Complete)" $KitchenA) '\[\["0"\]\]'
|
||||||
|
Expect " and the one with the wrong SHA-256 (dropped at once)" (Query "SELECT COUNT(*) FROM blobs WHERE state <> 2" $KitchenA) '\[\["0"\]\]'
|
||||||
|
Expect " the attached one is kept" (Query "SELECT COUNT(*) FROM blobs WHERE state = 2" $KitchenA) '\[\["1"\]\]'
|
||||||
|
$R = Tool "AttachmentEdgeClient.exe" @("late", $KitchenA, $Partial, $Complete)
|
||||||
|
$R.Lines | Where-Object { $_ -match "^(PASS|FAIL| ->)" }
|
||||||
|
$Script:Fails += @($R.Lines | Where-Object { $_ -match "^FAIL" }).Count
|
||||||
|
|
||||||
|
"--- 3. Replication resuming (B killed in the middle of 400 MB)"
|
||||||
|
$Big = New-File "big.bin" 400MB 9
|
||||||
|
$R = Push '{"big":1}' $KitchenA $Big
|
||||||
|
Check "push 400 MB to A" ($R.Code -eq 0 -and $R.Out -match "message #(\d+), with an attachment") $R.Out
|
||||||
|
$BigId = $Matches[1]
|
||||||
|
$SB = Start-Srv "b"
|
||||||
|
Wait-Port 12414 $SB
|
||||||
|
$Received = "SELECT COALESCE(MAX(b.received), 0) FROM attachments a JOIN topics t ON t.topic_id = a.topic_id LEFT JOIN blobs b ON b.blob_id = a.blob_id WHERE t.name = 'logs' AND a.message_id = $BigId"
|
||||||
|
$KilledAt = -1
|
||||||
|
$D = (Get-Date).AddSeconds(60)
|
||||||
|
while ((Get-Date) -lt $D) {
|
||||||
|
$N = Num (Query $Received $KitchenB).Out
|
||||||
|
if ($N -ge 40MB) { Stop-Process -Id $SB.P.Id -Force; $SB.P.WaitForExit(10000) | Out-Null; $KilledAt = $N; break }
|
||||||
|
Start-Sleep -Milliseconds 50
|
||||||
|
}
|
||||||
|
Check "B killed in the middle" ($KilledAt -gt 0 -and $KilledAt -lt 400MB) ("{0:N0} MB of 400 received" -f ($KilledAt / 1MB))
|
||||||
|
$SB = Start-Srv "b"
|
||||||
|
Wait-Port 12414 $SB
|
||||||
|
$AfterRestart = Num (Query $Received $KitchenB).Out
|
||||||
|
Check "after the restart, what it had is still there" ($AfterRestart -ge $KilledAt) ("{0:N0} MB" -f ($AfterRestart / 1MB))
|
||||||
|
$Copy = Join-Path $Dir "big-from-b.bin"
|
||||||
|
$D = (Get-Date).AddSeconds(90)
|
||||||
|
do {
|
||||||
|
$R = Tool "GetAttachment.exe" @("logs", "kitchen", $BigId, $Copy, $KitchenB)
|
||||||
|
if ($R.Code -eq 0) { break }
|
||||||
|
Start-Sleep -Milliseconds 500
|
||||||
|
} while ((Get-Date) -lt $D)
|
||||||
|
Check "B ends up with all of it, identical" ($R.Code -eq 0 -and (Hash $Copy) -eq (Hash $Big)) $R.Out
|
||||||
|
$LogA = (Get-ChildItem $Dir -Filter "a.*.log" | ForEach-Object { Get-Content $_.FullName -Raw }) -join "`n"
|
||||||
|
$Resumed = [regex]::Matches($LogA, "Sent the attachment of logs:kitchen#$BigId to 'b' in \d+ ms, from part (\d+)")
|
||||||
|
$From = if ($Resumed.Count) { [int]$Resumed[$Resumed.Count - 1].Groups[1].Value } else { -1 }
|
||||||
|
Check "A went on from where B stopped, not from 0" ($From -gt 0 -and $From * 1MB -le $AfterRestart) ("from part $From, B had {0:N0} MB" -f ($AfterRestart / 1MB))
|
||||||
|
Remove-Item $Copy, $Big -ErrorAction SilentlyContinue
|
||||||
|
|
||||||
|
"--- 4. A corrupted attachment"
|
||||||
|
$HasPython = $false
|
||||||
|
try { & $Python -c "import sqlite3" 2>&1 | Out-Null; $HasPython = ($LASTEXITCODE -eq 0) } catch { }
|
||||||
|
if (-not $HasPython) {
|
||||||
|
"SKIP no Python ($Python)"
|
||||||
|
} else {
|
||||||
|
Stop-Srv $SB; $SB = $null
|
||||||
|
$Small = New-File "small.bin" (3MB + 99) 10
|
||||||
|
$R = Push '{"corrupt":1}' $KitchenA $Small
|
||||||
|
Check "push 3 MB to A, B stopped" ($R.Code -eq 0 -and $R.Out -match "message #(\d+), with an attachment") $R.Out
|
||||||
|
$BadId = $Matches[1]
|
||||||
|
Stop-Srv $SA
|
||||||
|
$Flip = @"
|
||||||
|
import sqlite3, sys
|
||||||
|
db = sqlite3.connect(sys.argv[1])
|
||||||
|
row = db.execute("SELECT c.rowid, c.chunk_data FROM blob_chunks c JOIN attachments a ON a.blob_id = c.blob_id WHERE a.message_id = ? AND a.topic_id = 1 AND c.chunk_index = 1", (int(sys.argv[2]),)).fetchone()
|
||||||
|
data = bytearray(row[1]); data[1000] ^= 0xFF
|
||||||
|
db.execute("UPDATE blob_chunks SET chunk_data = ? WHERE rowid = ?", (bytes(data), row[0]))
|
||||||
|
db.commit(); print("flipped")
|
||||||
|
"@
|
||||||
|
Set-Content (Join-Path $Dir "flip.py") -Encoding Ascii -Value $Flip
|
||||||
|
$Out = & $Python -B (Join-Path $Dir "flip.py") (Join-Path $Dir "a.sqlite") $BadId 2>&1
|
||||||
|
Check "a byte flipped in A's database, part 1" ("$Out" -eq "flipped") "$Out"
|
||||||
|
$SA = Start-Srv "a"
|
||||||
|
Wait-Port 12413 $SA
|
||||||
|
$Copy = Join-Path $Dir "bad-from-a.bin"
|
||||||
|
Expect "reading it from A: the client refuses it" (Tool "GetAttachment.exe" @("logs", "kitchen", $BadId, $Copy, $KitchenA)) "doesn't match its SHA-256" 1
|
||||||
|
Check " and leaves no file" (-not (Test-Path $Copy)) "checked"
|
||||||
|
$SB = Start-Srv "b"
|
||||||
|
Wait-Port 12414 $SB
|
||||||
|
Start-Sleep -Seconds 6
|
||||||
|
$LogB = Get-Content $SB.Log -Raw
|
||||||
|
$Drops = [regex]::Matches($LogB, "attachment of logs:kitchen#$BadId from peer 'a' doesn't match its SHA-256, dropped").Count
|
||||||
|
Check "B drops it: doesn't match" ($Drops -ge 1) "$Drops times in 6 s"
|
||||||
|
Expect "B doesn't serve it" (Tool "GetAttachment.exe" @("logs", "kitchen", $BadId, $Copy, $KitchenB)) "isn't here yet" 1
|
||||||
|
$R = Query "SELECT a.state, COALESCE(a.blob_id, 0) FROM attachments a JOIN topics t ON t.topic_id = a.topic_id WHERE t.name = 'logs' AND a.message_id = $BadId" $KitchenB
|
||||||
|
Check "B's attachment is back to missing (0), no blob" ($R.Out -match '\[\["0","0"\]\]') $R.Out
|
||||||
|
Expect "B: no blob left behind, once cleaned" (Wait-Query "SELECT COUNT(*) FROM blobs WHERE state <> 2" $KitchenB '\[\["0"\]\]' 5) '\[\["0"\]\]'
|
||||||
|
"INFO A sends it again at every check-in: $Drops times in 6 s (PeerSyncInterval 1)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally {
|
||||||
|
Stop-Srv $SA; Stop-Srv $SB
|
||||||
|
}
|
||||||
|
|
||||||
|
"--- Logs"
|
||||||
|
$All = (Get-ChildItem $Dir -Filter "*.log" | ForEach-Object { Get-Content $_.FullName }) | Where-Object { $_ -match "invalid|unexpected|doesn't decrypt" }
|
||||||
|
Check "no invalid or unexpected packets in any log" ($All.Count -eq 0) ($All -join " / ")
|
||||||
|
|
||||||
|
""
|
||||||
|
if ($Fails) { "$Fails FAILED"; exit 1 } else { "All passed" }
|
||||||
@@ -0,0 +1,296 @@
|
|||||||
|
# End-to-end test of attachments (Design/Attachments.md), through the tools
|
||||||
|
# (PushMessage -a, GetAttachment, GetLatestMessage):
|
||||||
|
# - pushed with a message, read back identical (100 KB, 5 MB + a bit,
|
||||||
|
# exactly 2 MB: one part, several, a whole number of them);
|
||||||
|
# - a message without one: refused when asked for it;
|
||||||
|
# - replicated after their messages, identical on the other server;
|
||||||
|
# - bigger than the other server's MaxAttachmentSize: its message comes,
|
||||||
|
# the attachment is refused there as not kept;
|
||||||
|
# - too big to push: refused, and the message isn't stored;
|
||||||
|
# - deleted with their message by the retention, parts included.
|
||||||
|
# Two linked servers, A (port 12410, MaxAttachmentSize 64M) and B (12411, 3M).
|
||||||
|
# Needs Build\ (Build.ps1) and Build\Bench\BenchServer.exe.
|
||||||
|
# Usage: powershell -ExecutionPolicy Bypass -File Tests\Attachments-Test.ps1
|
||||||
|
param([string]$Build = (Join-Path $PSScriptRoot "..\Build"))
|
||||||
|
$ErrorActionPreference = "Stop"
|
||||||
|
$Build = (Resolve-Path $Build).Path
|
||||||
|
$Dir = Join-Path $Build "_attachtest"
|
||||||
|
Remove-Item -Recurse -Force $Dir -ErrorAction SilentlyContinue
|
||||||
|
New-Item -ItemType Directory $Dir | Out-Null
|
||||||
|
$Server = Join-Path $Build "Bench\BenchServer.exe"
|
||||||
|
$Fails = 0
|
||||||
|
|
||||||
|
function New-KeyPair {
|
||||||
|
$L = & (Join-Path $Build "KeyGen.exe")
|
||||||
|
@{ Priv = $L[0] -replace "^PrivateKey = ", ""; Pub = $L[1] -replace "^PublicKey = ", "" }
|
||||||
|
}
|
||||||
|
function Test-Port($P) {
|
||||||
|
$C = New-Object System.Net.Sockets.TcpClient
|
||||||
|
try { $A = $C.BeginConnect("127.0.0.1", $P, $null, $null); $A.AsyncWaitHandle.WaitOne(200) -and $C.Connected } catch { $false } finally { $C.Close() }
|
||||||
|
}
|
||||||
|
function Tool([string]$Name, [string[]]$A) {
|
||||||
|
$O = & (Join-Path $Build $Name) @A 2>&1
|
||||||
|
@{ Code = $LASTEXITCODE; Out = ($O -join " | ") }
|
||||||
|
}
|
||||||
|
function Check([string]$What, [bool]$Ok, [string]$Detail) {
|
||||||
|
if (-not $Ok) { $script:Fails++ }
|
||||||
|
"{0} {1}`n -> {2}" -f $(if ($Ok) { "PASS" } else { "FAIL" }), $What, $Detail
|
||||||
|
}
|
||||||
|
function Expect([string]$What, $Result, [string]$Pattern, [int]$Code = 0) {
|
||||||
|
Check $What (($Result.Code -eq $Code) -and ($Result.Out -match $Pattern)) ("[{0}] {1}" -f $Result.Code, $Result.Out)
|
||||||
|
}
|
||||||
|
function Start-Srv($Name) {
|
||||||
|
$Stop = Join-Path $Dir "$Name.stop"
|
||||||
|
Remove-Item $Stop -ErrorAction SilentlyContinue
|
||||||
|
$P = Start-Process -FilePath $Server -ArgumentList "`"$(Join-Path $Dir "$Name.ini")`"", "`"$Stop`"" -WorkingDirectory $Dir `
|
||||||
|
-RedirectStandardOutput (Join-Path $Dir "$Name.log") -WindowStyle Hidden -PassThru
|
||||||
|
$null = $P.Handle
|
||||||
|
@{ P = $P; Stop = $Stop; Name = $Name }
|
||||||
|
}
|
||||||
|
function Stop-Srv($S) {
|
||||||
|
if ($S.P.HasExited) { return }
|
||||||
|
Set-Content $S.Stop "x"
|
||||||
|
if (-not $S.P.WaitForExit(15000)) { Stop-Process -Id $S.P.Id -Force }
|
||||||
|
}
|
||||||
|
function Wait-Port($Port, $S) {
|
||||||
|
$D = (Get-Date).AddSeconds(15)
|
||||||
|
while (-not (Test-Port $Port)) {
|
||||||
|
if ($S.P.HasExited) { throw "$($S.Name) exited: $(Get-Content (Join-Path $Dir "$($S.Name).log") -Raw)" }
|
||||||
|
if ((Get-Date) -gt $D) { throw "$($S.Name) not listening" }
|
||||||
|
Start-Sleep -Milliseconds 100
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function Query($Sql, $Ini) {
|
||||||
|
$F = Join-Path $Dir "q.sql"; Set-Content $F -Encoding Ascii -Value $Sql
|
||||||
|
Tool "Query.exe" @("@$F", $Ini)
|
||||||
|
}
|
||||||
|
function Wait-Query($Sql, $Ini, $Pattern, $Seconds = 20) {
|
||||||
|
$D = (Get-Date).AddSeconds($Seconds)
|
||||||
|
do {
|
||||||
|
$R = Query $Sql $Ini
|
||||||
|
if ($R.Code -eq 0 -and $R.Out -match $Pattern) { return $R }
|
||||||
|
Start-Sleep -Milliseconds 250
|
||||||
|
} while ((Get-Date) -lt $D)
|
||||||
|
$R
|
||||||
|
}
|
||||||
|
function Push($Data, $Ini, [string]$Topic = "", [string]$Attach = "") {
|
||||||
|
$F = Join-Path $Dir "push.txt"
|
||||||
|
[IO.File]::WriteAllText($F, $Data, (New-Object System.Text.UTF8Encoding $false))
|
||||||
|
$A = @()
|
||||||
|
if ($Topic) { $A += @("-t", $Topic) }
|
||||||
|
if ($Attach) { $A += @("-a", $Attach) }
|
||||||
|
Tool "PushMessage.exe" ($A + @("@$F", $Ini))
|
||||||
|
}
|
||||||
|
# A file of Size random bytes.
|
||||||
|
function New-File($Name, [int]$Size, [int]$Seed) {
|
||||||
|
$P = Join-Path $Dir $Name
|
||||||
|
$B = New-Object byte[] $Size
|
||||||
|
(New-Object System.Random $Seed).NextBytes($B)
|
||||||
|
[IO.File]::WriteAllBytes($P, $B)
|
||||||
|
$P
|
||||||
|
}
|
||||||
|
function Hash($Path) { if (Test-Path $Path) { (Get-FileHash $Path -Algorithm SHA256).Hash } else { "no file" } }
|
||||||
|
# Saves an attachment and compares it with the original.
|
||||||
|
function Expect-Same([string]$What, $Topic, $Node, $Id, $Original, $Ini) {
|
||||||
|
$Out = Join-Path $Dir ("got-" + [guid]::NewGuid().ToString("N") + ".bin")
|
||||||
|
$R = Tool "GetAttachment.exe" @($Topic, $Node, "$Id", $Out, $Ini)
|
||||||
|
$Same = ($R.Code -eq 0) -and ((Hash $Out) -eq (Hash $Original))
|
||||||
|
Check $What $Same ("[{0}] {1}" -f $R.Code, $R.Out)
|
||||||
|
}
|
||||||
|
# Retries GetAttachment until it works: replicated ones come after their message.
|
||||||
|
function Wait-Same([string]$What, $Topic, $Node, $Id, $Original, $Ini, $Seconds = 20) {
|
||||||
|
$Out = Join-Path $Dir ("got-" + [guid]::NewGuid().ToString("N") + ".bin")
|
||||||
|
$D = (Get-Date).AddSeconds($Seconds)
|
||||||
|
do {
|
||||||
|
$R = Tool "GetAttachment.exe" @($Topic, $Node, "$Id", $Out, $Ini)
|
||||||
|
if ($R.Code -eq 0) { break }
|
||||||
|
Start-Sleep -Milliseconds 250
|
||||||
|
} while ((Get-Date) -lt $D)
|
||||||
|
Check $What (($R.Code -eq 0) -and ((Hash $Out) -eq (Hash $Original))) ("[{0}] {1}" -f $R.Code, $R.Out)
|
||||||
|
}
|
||||||
|
|
||||||
|
$A = New-KeyPair; $B = New-KeyPair; $K = New-KeyPair
|
||||||
|
|
||||||
|
Set-Content (Join-Path $Dir "a.ini") -Encoding Ascii -Value @"
|
||||||
|
[BakaShrot]
|
||||||
|
PrivateKey = $($A.Priv)
|
||||||
|
Topic = logs
|
||||||
|
Node = serverA
|
||||||
|
|
||||||
|
[BakaShrot.Topics]
|
||||||
|
logs = 1
|
||||||
|
short = 2
|
||||||
|
photos = 3
|
||||||
|
|
||||||
|
[BakaShrot.Nodes]
|
||||||
|
serverA = 10
|
||||||
|
serverB = 11
|
||||||
|
kitchen = 2
|
||||||
|
garage = 3
|
||||||
|
|
||||||
|
[BakaShrot.Retention]
|
||||||
|
short = 4s
|
||||||
|
|
||||||
|
[BakaShrot.Server]
|
||||||
|
Host = 127.0.0.1
|
||||||
|
Port = 12410
|
||||||
|
ReplicatingTopics = logs;short;photos
|
||||||
|
DatabasePath = $(Join-Path $Dir "a.sqlite")
|
||||||
|
PeerSyncInterval = 1
|
||||||
|
PeerRetryDelay = 1
|
||||||
|
RetentionInterval = 1
|
||||||
|
MaxAttachmentSize = 64M
|
||||||
|
|
||||||
|
[BakaShrot.Peer.b]
|
||||||
|
Host = 127.0.0.1
|
||||||
|
Port = 12411
|
||||||
|
Topic = logs
|
||||||
|
Node = serverB
|
||||||
|
PublicKey = $($B.Pub)
|
||||||
|
|
||||||
|
[BakaShrot.Client.b]
|
||||||
|
PublicKeys = $($B.Pub)
|
||||||
|
Identities = logs:serverB
|
||||||
|
|
||||||
|
[BakaShrot.Client.kitchen]
|
||||||
|
PublicKeys = $($K.Pub)
|
||||||
|
Identities = logs:kitchen
|
||||||
|
PushTopics = logs;short
|
||||||
|
ReadTopics = *
|
||||||
|
AllowQuery = 1
|
||||||
|
"@
|
||||||
|
|
||||||
|
Set-Content (Join-Path $Dir "b.ini") -Encoding Ascii -Value @"
|
||||||
|
[BakaShrot]
|
||||||
|
PrivateKey = $($B.Priv)
|
||||||
|
Topic = logs
|
||||||
|
Node = serverB
|
||||||
|
|
||||||
|
[BakaShrot.Topics]
|
||||||
|
logs = 300
|
||||||
|
short = 301
|
||||||
|
photos = 302
|
||||||
|
|
||||||
|
[BakaShrot.Nodes]
|
||||||
|
serverA = 1
|
||||||
|
serverB = 2
|
||||||
|
kitchen = 30
|
||||||
|
garage = 31
|
||||||
|
|
||||||
|
[BakaShrot.Server]
|
||||||
|
Host = 127.0.0.1
|
||||||
|
Port = 12411
|
||||||
|
ReplicatingTopics = logs;short;photos
|
||||||
|
DatabasePath = $(Join-Path $Dir "b.sqlite")
|
||||||
|
PeerSyncInterval = 1
|
||||||
|
PeerRetryDelay = 1
|
||||||
|
RetentionInterval = 1
|
||||||
|
MaxAttachmentSize = 3M
|
||||||
|
|
||||||
|
[BakaShrot.Peer.a]
|
||||||
|
Host = 127.0.0.1
|
||||||
|
Port = 12410
|
||||||
|
Topic = logs
|
||||||
|
Node = serverA
|
||||||
|
PublicKey = $($A.Pub)
|
||||||
|
|
||||||
|
[BakaShrot.Client.a]
|
||||||
|
PublicKeys = $($A.Pub)
|
||||||
|
Identities = logs:serverA
|
||||||
|
|
||||||
|
[BakaShrot.Client.garage]
|
||||||
|
PublicKeys = $($K.Pub)
|
||||||
|
Identities = photos:garage
|
||||||
|
PushTopics = photos
|
||||||
|
ReadTopics = *
|
||||||
|
AllowQuery = 1
|
||||||
|
"@
|
||||||
|
|
||||||
|
$ServerKeys = @{ 12410 = $A.Pub; 12411 = $B.Pub }
|
||||||
|
function Client-Ini($Name, $Topic, $Node, $Port) {
|
||||||
|
$P = Join-Path $Dir "$Name.ini"
|
||||||
|
Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($K.Priv)`r`nPublicKey = $($K.Pub)`r`nTopic = $Topic`r`nNode = $Node`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($ServerKeys[$Port])"
|
||||||
|
$P
|
||||||
|
}
|
||||||
|
$OnA = Client-Ini "kitchen-a" "logs" "kitchen" 12410
|
||||||
|
$OnB = Client-Ini "garage-b" "photos" "garage" 12411
|
||||||
|
|
||||||
|
$Small = New-File "small.bin" (100 * 1024) 1
|
||||||
|
$Mid = New-File "mid.bin" (5 * 1024 * 1024 + 123) 2
|
||||||
|
$Exact = New-File "exact.bin" (2 * 1024 * 1024) 3
|
||||||
|
$Tiny = New-File "tiny.bin" 1 4
|
||||||
|
|
||||||
|
foreach ($Port in 12410, 12411) { if (Test-Port $Port) { throw "Port $Port is already in use" } }
|
||||||
|
$SA = Start-Srv "a"; $SB = Start-Srv "b"
|
||||||
|
try {
|
||||||
|
Wait-Port 12410 $SA; Wait-Port 12411 $SB
|
||||||
|
Start-Sleep -Seconds 1
|
||||||
|
|
||||||
|
"--- Pushed with their message, read back"
|
||||||
|
Expect "push #1 with 100 KB" (Push '{"n":1}' $OnA "" $Small) "message #1, with an attachment of 102400 bytes"
|
||||||
|
$Started = Get-Date
|
||||||
|
Expect "push #2 with 5 MB + 123 bytes (6 parts)" (Push '{"n":2}' $OnA "" $Mid) "message #2, with an attachment of 5243003 bytes"
|
||||||
|
$UploadMs = ((Get-Date) - $Started).TotalMilliseconds
|
||||||
|
Expect "push #3 with exactly 2 MB (2 parts)" (Push '{"n":3}' $OnA "" $Exact) "message #3, with an attachment of 2097152 bytes"
|
||||||
|
Expect "push #4 with 1 byte" (Push '{"n":4}' $OnA "" $Tiny) "message #4"
|
||||||
|
Expect "push #5 without" (Push '{"n":5}' $OnA) "message #5$"
|
||||||
|
Expect-Same "#1 read back identical" "logs" "kitchen" 1 $Small $OnA
|
||||||
|
$Started = Get-Date
|
||||||
|
Expect-Same "#2 read back identical" "logs" "kitchen" 2 $Mid $OnA
|
||||||
|
$DownloadMs = ((Get-Date) - $Started).TotalMilliseconds
|
||||||
|
Check "5 MB up and down, tool start included" $true ("{0:N0} ms up, {1:N0} ms down" -f $UploadMs, $DownloadMs)
|
||||||
|
Expect-Same "#3 read back identical" "logs" "kitchen" 3 $Exact $OnA
|
||||||
|
Expect-Same "#4 read back identical" "logs" "kitchen" 4 $Tiny $OnA
|
||||||
|
Expect "#5 has none: refused" (Tool "GetAttachment.exe" @("logs", "kitchen", "5", (Join-Path $Dir "none.bin"), $OnA)) "No attachment for logs:kitchen#5" 1
|
||||||
|
Check "a refused one leaves no file" (-not (Test-Path (Join-Path $Dir "none.bin"))) "checked"
|
||||||
|
Expect "a message that doesn't exist: refused" (Tool "GetAttachment.exe" @("logs", "kitchen", "99", (Join-Path $Dir "none.bin"), $OnA)) "No attachment" 1
|
||||||
|
Expect "GetLatestMessage: #5, no attachment line" (Tool "GetLatestMessage.exe" @("logs", "kitchen", $OnA)) "#5 \(ids 1:2\), pushed [^|]+\| \{`"n`":5\}$"
|
||||||
|
$R = Query "SELECT message_id, size, state FROM attachments WHERE topic_id = 1 AND node_id = 2 ORDER BY message_id" $OnA
|
||||||
|
Check "A's attachments: 4, all ready (2)" ($R.Out -match '\[\["1","102400","2"\],\["2","5243003","2"\],\["3","2097152","2"\],\["4","1","2"\]\]') $R.Out
|
||||||
|
Expect "A stores 6 + 2 + 1 + 1 parts" (Query "SELECT COUNT(*) FROM blob_chunks" $OnA) '\[\["10"\]\]'
|
||||||
|
|
||||||
|
"--- Replicated after their messages (B takes up to 3M)"
|
||||||
|
$R = Wait-Query "SELECT COUNT(*) FROM messages WHERE topic = 'logs' AND node = 'kitchen'" $OnB '\[\["5"\]\]'
|
||||||
|
Check "B got the 5 messages" ($R.Out -match '\[\["5"\]\]') $R.Out
|
||||||
|
Wait-Same "B: #1 identical" "logs" "kitchen" 1 $Small $OnB
|
||||||
|
Wait-Same "B: #3 identical (2 MB)" "logs" "kitchen" 3 $Exact $OnB
|
||||||
|
Wait-Same "B: #4 identical (1 byte)" "logs" "kitchen" 4 $Tiny $OnB
|
||||||
|
Expect "B: #2 isn't kept (5 MB > 3M)" (Tool "GetAttachment.exe" @("logs", "kitchen", "2", (Join-Path $Dir "none.bin"), $OnB)) "isn't kept here" 1
|
||||||
|
$R = Query "SELECT a.message_id, a.state FROM attachments a JOIN topics t ON t.topic_id = a.topic_id WHERE t.name = 'logs' ORDER BY a.message_id" $OnB
|
||||||
|
Check "B's attachments: ready, not kept (3), ready, ready" ($R.Out -match '\[\["1","2"\],\["2","3"\],\["3","2"\],\["4","2"\]\]') $R.Out
|
||||||
|
Expect "B: GetLatestMessage logs:kitchen, #5 has none" (Tool "GetLatestMessage.exe" @("logs", "kitchen", $OnB)) "#5 \(ids 300:30\), pushed [^|]+\| \{`"n`":5\}"
|
||||||
|
|
||||||
|
"--- Pushed on B, too big there, then replicated to A"
|
||||||
|
Expect "B refuses 5 MB (more than 3M)" (Push '{"photo":0}' $OnB "" $Mid) "too big: 5243003 bytes, at most 3145728" 1
|
||||||
|
Expect "the message wasn't stored: the next is #1" (Push '{"photo":1}' $OnB "" $Small) "message #1, with an attachment"
|
||||||
|
Wait-Same "A got B's photos:garage#1 identical" "photos" "garage" 1 $Small $OnA
|
||||||
|
Expect "A: the latest of photos:garage" (Tool "GetLatestMessage.exe" @("photos", "garage", $OnA)) "Attachment: 102400 bytes \| \{`"photo`":1\}"
|
||||||
|
|
||||||
|
"--- Deleted with their message (A: short = 4s)"
|
||||||
|
$Before = (Query "SELECT COUNT(*) FROM blob_chunks" $OnA).Out
|
||||||
|
Expect "push short #1 with 2 MB" (Push '{"s":1}' $OnA "short" $Exact) "message #1, with an attachment"
|
||||||
|
Expect "A has 2 more parts" (Query "SELECT COUNT(*) FROM blob_chunks" $OnA) '\[\["13"\]\]'
|
||||||
|
$R = Wait-Query "SELECT COUNT(*) FROM messages WHERE topic = 'short'" $OnA '\[\["0"\]\]' 15
|
||||||
|
Check "the message is deleted past 4 s" ($R.Out -match '\[\["0"\]\]') $R.Out
|
||||||
|
$R = Wait-Query "SELECT COUNT(*) FROM blob_chunks" $OnA '\[\["11"\]\]' 10
|
||||||
|
Check "and its 2 parts" ($R.Out -match '\[\["11"\]\]') "before $Before, now $($R.Out)"
|
||||||
|
Expect "and its attachments row" (Query "SELECT COUNT(*) FROM attachments WHERE topic_id = 2" $OnA) '\[\["0"\]\]'
|
||||||
|
Expect "and its blob" (Query "SELECT COUNT(*) FROM blobs WHERE state = 3" $OnA) '\[\["0"\]\]'
|
||||||
|
Wait-Same "B kept short#1 (no max age there)" "short" "kitchen" 1 $Exact $OnB
|
||||||
|
}
|
||||||
|
finally {
|
||||||
|
Stop-Srv $SA; Stop-Srv $SB
|
||||||
|
}
|
||||||
|
|
||||||
|
"--- Logs"
|
||||||
|
$LogA = Get-Content (Join-Path $Dir "a.log") -Raw
|
||||||
|
$LogB = Get-Content (Join-Path $Dir "b.log") -Raw
|
||||||
|
Check "A sent B the attachments it takes" ($LogA -match "Sent the attachment of logs:kitchen#1 to 'b'" -and $LogA -match "Sent the attachment of logs:kitchen#3 to 'b'") "checked"
|
||||||
|
Check "A never sent #2 (not kept by B)" (-not ($LogA -match "Sent the attachment of logs:kitchen#2")) "checked"
|
||||||
|
Check "B sent A its photo" ($LogB -match "Sent the attachment of photos:garage#1 to 'a'") "checked"
|
||||||
|
Check "A logged deleting the parts" ($LogA -match "deleted 2 attachment parts") "checked"
|
||||||
|
$Other = ($LogA + "`n" + $LogB) -split "`r?`n" | Where-Object { $_ -match "Failed|invalid|unexpected|doesn't decrypt|SHA-256" -and $_ -notmatch "Refused a request" }
|
||||||
|
Check "no failure in A's or B's log" ($Other.Count -eq 0) ($Other -join " / ")
|
||||||
|
|
||||||
|
""
|
||||||
|
if ($Fails) { "$Fails FAILED"; exit 1 } else { "All passed" }
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
; ============================================================================
|
||||||
|
; BakaShrot GetAttachment
|
||||||
|
;
|
||||||
|
; Usage: GetAttachment <Topic> <Node> <MessageId> <OutFile> [ClientIni]
|
||||||
|
; Topic, Node Whose message, each a name or an id.
|
||||||
|
; MessageId Which message.
|
||||||
|
; OutFile Where to save its attachment (replaced).
|
||||||
|
; ClientIni Identity and server to use, defaults to "client.ini".
|
||||||
|
;
|
||||||
|
; Saves the attachment of a message, read from the server a part at a time
|
||||||
|
; and checked with its SHA-256, and prints its size. The server refuses if
|
||||||
|
; the client's ReadTopics don't allow the topic, if the message has none, or
|
||||||
|
; if it isn't on that server yet (a replicated one comes after its message).
|
||||||
|
; A failed one leaves no file. See Design/Attachments.md.
|
||||||
|
; Compile as a console program, exits with 0 on success, 1 on failure.
|
||||||
|
; ============================================================================
|
||||||
|
|
||||||
|
EnableExplicit
|
||||||
|
|
||||||
|
XIncludeFile "../Common/ToolClient.pbi"
|
||||||
|
XIncludeFile "../../Commons/Networking/Names.pbi"
|
||||||
|
|
||||||
|
|
||||||
|
Define Topic.s, Node.s, MessageText.s, OutFile.s, IniPath.s, MessageId.q, Size.q, StartTime.i
|
||||||
|
|
||||||
|
OpenConsole()
|
||||||
|
|
||||||
|
If CountProgramParameters() < 4
|
||||||
|
PrintN("Usage: GetAttachment <Topic> <Node> <MessageId> <OutFile> [ClientIni]")
|
||||||
|
PrintN(" Topic and Node are names or ids.")
|
||||||
|
End 1
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
Topic = ProgramParameter(0)
|
||||||
|
Node = ProgramParameter(1)
|
||||||
|
If Not BakaShrot_IsValidRef(Topic) Or Not BakaShrot_IsValidRef(Node)
|
||||||
|
PrintN("Invalid topic or node, expected names or ids 0-65535")
|
||||||
|
End 1
|
||||||
|
EndIf
|
||||||
|
MessageText = ProgramParameter(2)
|
||||||
|
MessageId = Val(MessageText)
|
||||||
|
If MessageId < 1 Or Str(MessageId) <> MessageText
|
||||||
|
PrintN("Invalid message id '" + MessageText + "'")
|
||||||
|
End 1
|
||||||
|
EndIf
|
||||||
|
OutFile = ProgramParameter(3)
|
||||||
|
|
||||||
|
IniPath = "client.ini"
|
||||||
|
If CountProgramParameters() > 4
|
||||||
|
IniPath = ProgramParameter(4)
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If Not ToolClient_Connect(IniPath)
|
||||||
|
End 1
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
StartTime = ElapsedMilliseconds()
|
||||||
|
Size = BakaShrot_SaveAttachment(Topic, Node, MessageId, OutFile)
|
||||||
|
If Size < 0
|
||||||
|
ToolClient_PrintFailure()
|
||||||
|
ToolClient_Close()
|
||||||
|
End 1
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
PrintN("Saved " + Str(Size) + " bytes to '" + OutFile + "' in " + Str(ElapsedMilliseconds() - StartTime) + " ms")
|
||||||
|
|
||||||
|
ToolClient_Close()
|
||||||
|
End 0
|
||||||
@@ -6,7 +6,8 @@
|
|||||||
; ClientIni Identity and server to use, defaults to "client.ini".
|
; ClientIni Identity and server to use, defaults to "client.ini".
|
||||||
;
|
;
|
||||||
; Prints the latest message stored for that topic/node, and when it was
|
; Prints the latest message stored for that topic/node, and when it was
|
||||||
; pushed (UTC), then its data. The server refuses
|
; pushed (UTC), its attachment if it has one (GetAttachment saves it), then
|
||||||
|
; its data. The server refuses
|
||||||
; if the client's ReadTopics don't allow the topic, if either is unknown, or
|
; if the client's ReadTopics don't allow the topic, if either is unknown, or
|
||||||
; if there's no message.
|
; if there's no message.
|
||||||
; Compile as a console program, exits with 0 on success, 1 on failure.
|
; Compile as a console program, exits with 0 on success, 1 on failure.
|
||||||
@@ -57,6 +58,13 @@ EndIf
|
|||||||
|
|
||||||
PrintN("Message " + BakaShrot_GetMessageTopicString() + ":" + BakaShrot_GetMessageNodeString() + "#" + Str(BakaShrot_GetMessageId()) +
|
PrintN("Message " + BakaShrot_GetMessageTopicString() + ":" + BakaShrot_GetMessageNodeString() + "#" + Str(BakaShrot_GetMessageId()) +
|
||||||
" (ids " + Str(BakaShrot_GetMessageTopicId()) + ":" + Str(BakaShrot_GetMessageNodeId()) + "), pushed " + ToolClient_FormatUtc(BakaShrot_GetMessagePushedAt()))
|
" (ids " + Str(BakaShrot_GetMessageTopicId()) + ":" + Str(BakaShrot_GetMessageNodeId()) + "), pushed " + ToolClient_FormatUtc(BakaShrot_GetMessagePushedAt()))
|
||||||
|
If BakaShrot_GetMessageAttachmentSize() > 0
|
||||||
|
If BakaShrot_IsMessageAttachmentReady()
|
||||||
|
PrintN("Attachment: " + Str(BakaShrot_GetMessageAttachmentSize()) + " bytes")
|
||||||
|
Else
|
||||||
|
PrintN("Attachment: " + Str(BakaShrot_GetMessageAttachmentSize()) + " bytes, not on this server yet")
|
||||||
|
EndIf
|
||||||
|
EndIf
|
||||||
PrintN(BakaShrot_GetMessageDataString())
|
PrintN(BakaShrot_GetMessageDataString())
|
||||||
|
|
||||||
ToolClient_Close()
|
ToolClient_Close()
|
||||||
|
|||||||
@@ -1,10 +1,13 @@
|
|||||||
; ============================================================================
|
; ============================================================================
|
||||||
; BakaShrot PushMessage
|
; BakaShrot PushMessage
|
||||||
;
|
;
|
||||||
; Usage: PushMessage [-t <Topic>] <Json|@JsonFile> [ClientIni]
|
; Usage: PushMessage [-t <Topic>] [-a <File>] <Json|@JsonFile> [ClientIni]
|
||||||
; -t Topic The topic to push to, a name or an id. Defaults to the
|
; -t Topic The topic to push to, a name or an id. Defaults to the
|
||||||
; client's own topic (its TopicId). The client's PushTopics on
|
; client's own topic (its TopicId). The client's PushTopics on
|
||||||
; the server must allow it.
|
; the server must allow it.
|
||||||
|
; -a File Attaches File to the message (any size up to the server's
|
||||||
|
; MaxAttachmentSize): uploaded first, the message is only
|
||||||
|
; stored once all of it is. See Design/Attachments.md.
|
||||||
; Json The message to push, or @ followed by a file holding it.
|
; Json The message to push, or @ followed by a file holding it.
|
||||||
; Usually JSON, but anything goes: the server flags it in is_json.
|
; Usually JSON, but anything goes: the server flags it in is_json.
|
||||||
; PureBasic's ProgramParameter() drops double quotes and
|
; PureBasic's ProgramParameter() drops double quotes and
|
||||||
@@ -23,7 +26,7 @@ XIncludeFile "../Common/ToolClient.pbi"
|
|||||||
XIncludeFile "../../Commons/Networking/Names.pbi"
|
XIncludeFile "../../Commons/Networking/Names.pbi"
|
||||||
|
|
||||||
|
|
||||||
Define JsonData.s, IniPath.s, Topic.s, FileText.String, MessageId.q, i.i, Argument.s
|
Define JsonData.s, IniPath.s, Topic.s, AttachPath.s, FileText.String, MessageId.q, i.i, Argument.s
|
||||||
Define NewList Arguments.s()
|
Define NewList Arguments.s()
|
||||||
|
|
||||||
OpenConsole()
|
OpenConsole()
|
||||||
@@ -37,6 +40,13 @@ For i = 0 To CountProgramParameters() - 1
|
|||||||
PrintN("Invalid topic '" + Topic + "', expected a name or an id 0-65535")
|
PrintN("Invalid topic '" + Topic + "', expected a name or an id 0-65535")
|
||||||
End 1
|
End 1
|
||||||
EndIf
|
EndIf
|
||||||
|
ElseIf (Argument = "-a" Or Argument = "--attach") And i < CountProgramParameters() - 1
|
||||||
|
i + 1
|
||||||
|
AttachPath = ProgramParameter(i)
|
||||||
|
If FileSize(AttachPath) < 1
|
||||||
|
PrintN("Can't attach '" + AttachPath + "': no such file, or empty")
|
||||||
|
End 1
|
||||||
|
EndIf
|
||||||
Else
|
Else
|
||||||
AddElement(Arguments())
|
AddElement(Arguments())
|
||||||
Arguments() = Argument
|
Arguments() = Argument
|
||||||
@@ -44,7 +54,7 @@ For i = 0 To CountProgramParameters() - 1
|
|||||||
Next
|
Next
|
||||||
|
|
||||||
If ListSize(Arguments()) < 1
|
If ListSize(Arguments()) < 1
|
||||||
PrintN("Usage: PushMessage [-t <Topic>] <Json|@JsonFile> [ClientIni]")
|
PrintN("Usage: PushMessage [-t <Topic>] [-a <File>] <Json|@JsonFile> [ClientIni]")
|
||||||
PrintN(" Command-line arguments lose their double quotes, so use @JsonFile for JSON with strings.")
|
PrintN(" Command-line arguments lose their double quotes, so use @JsonFile for JSON with strings.")
|
||||||
End 1
|
End 1
|
||||||
EndIf
|
EndIf
|
||||||
@@ -67,14 +77,22 @@ If Not ToolClient_Connect(IniPath)
|
|||||||
End 1
|
End 1
|
||||||
EndIf
|
EndIf
|
||||||
|
|
||||||
MessageId = BakaShrot_PushMessageTo(Topic, JsonData)
|
If AttachPath <> ""
|
||||||
|
MessageId = BakaShrot_PushMessageWithFile(Topic, JsonData, AttachPath)
|
||||||
|
Else
|
||||||
|
MessageId = BakaShrot_PushMessageTo(Topic, JsonData)
|
||||||
|
EndIf
|
||||||
If MessageId < 1
|
If MessageId < 1
|
||||||
ToolClient_PrintFailure()
|
ToolClient_PrintFailure()
|
||||||
ToolClient_Close()
|
ToolClient_Close()
|
||||||
End 1
|
End 1
|
||||||
EndIf
|
EndIf
|
||||||
|
|
||||||
PrintN("Pushed as message #" + Str(MessageId))
|
If AttachPath <> ""
|
||||||
|
PrintN("Pushed as message #" + Str(MessageId) + ", with an attachment of " + Str(FileSize(AttachPath)) + " bytes")
|
||||||
|
Else
|
||||||
|
PrintN("Pushed as message #" + Str(MessageId))
|
||||||
|
EndIf
|
||||||
|
|
||||||
ToolClient_Close()
|
ToolClient_Close()
|
||||||
End 0
|
End 0
|
||||||
|
|||||||
Reference in New Issue
Block a user