From a0daf73c8e3dc6a95a77275dca274f77d5b7612e Mon Sep 17 00:00:00 2001 From: Herwin Bozet Date: Thu, 5 Nov 2026 22:45:47 +0100 Subject: [PATCH] Initial commit --- .gitignore | 12 + .gitmodules | 3 + ...ramework) - PureBasic Forums - English.url | 2 + Commons/Cryptography/Libsodium.pbi | 182 +++++++++++ Commons/Networking/Connections.pbi | 21 ++ Commons/Networking/Packets.pbi | 26 ++ .../Packets/AuthenticationPacket.pbi | 303 ++++++++++++++++++ Core/Config/Config.pbi | 260 +++++++++++++++ Core/Config/Config.pbi.cfg | 8 + Core/Config/schema.ini | 56 ++++ Core/Config/schema_out.ini | 14 + Core/Storage/Storage.pbi | 203 ++++++++++++ Core/Storage/db_schema_v0.dbml | 32 ++ Core/Storage/db_schema_v1.dbml | 34 ++ Includes/PB-MessagePack | 1 + .../Index of -libsodium-releases-.url | 2 + Review.md | 13 + readme.md | 11 + sqlite_json_index_demo.py | 185 +++++++++++ 19 files changed, 1368 insertions(+) create mode 100644 .gitignore create mode 100644 .gitmodules create mode 100644 BTJSON Framework (Better Json - New json handling framework) - PureBasic Forums - English.url create mode 100644 Commons/Cryptography/Libsodium.pbi create mode 100644 Commons/Networking/Connections.pbi create mode 100644 Commons/Networking/Packets.pbi create mode 100644 Commons/Networking/Packets/AuthenticationPacket.pbi create mode 100644 Core/Config/Config.pbi create mode 100644 Core/Config/Config.pbi.cfg create mode 100644 Core/Config/schema.ini create mode 100644 Core/Config/schema_out.ini create mode 100644 Core/Storage/Storage.pbi create mode 100644 Core/Storage/db_schema_v0.dbml create mode 100644 Core/Storage/db_schema_v1.dbml create mode 160000 Includes/PB-MessagePack create mode 100644 Libs/libsodium/Index of -libsodium-releases-.url create mode 100644 Review.md create mode 100644 readme.md create mode 100644 sqlite_json_index_demo.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..65cfc43 --- /dev/null +++ b/.gitignore @@ -0,0 +1,12 @@ +# IDEs +.vs/ +.idea/ + +# Build Artifacts +*.exe +*.dll +*.so +*.a +*.pdb +*.lib +*.exp diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..e8a3d2b --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "Includes/PB-MessagePack"] + path = Includes/PB-MessagePack + url = https://github.com/aziascreations/PB-MessagePack.git diff --git a/BTJSON Framework (Better Json - New json handling framework) - PureBasic Forums - English.url b/BTJSON Framework (Better Json - New json handling framework) - PureBasic Forums - English.url new file mode 100644 index 0000000..b88dba5 --- /dev/null +++ b/BTJSON Framework (Better Json - New json handling framework) - PureBasic Forums - English.url @@ -0,0 +1,2 @@ +[InternetShortcut] +URL=https://www.purebasic.fr/english/viewtopic.php?t=89425 diff --git a/Commons/Cryptography/Libsodium.pbi b/Commons/Cryptography/Libsodium.pbi new file mode 100644 index 0000000..efb51e4 --- /dev/null +++ b/Commons/Cryptography/Libsodium.pbi @@ -0,0 +1,182 @@ +; ============================================================================ +; BakaShrot Cryptography +; +; Authenticates packets using Ed25519 signatures (via libsodium - this does +; NOT reimplement any cryptographic primitive). +; +; EncodeData signs a buffer with the sending node's own private key. +; DecodeData checks that signature against the claimed sender's public key. +; +; This buys integrity + authenticity, NOT confidentiality: anyone who can see +; the packet can still read it, but they cannot forge one or tamper with one +; without the signature check failing. That matches BakaShrot's +; replication/broadcast model, where a message is meant to be read by every +; peer in the group - encrypting it for a single recipient would defeat that. +; +; Key material: +; - Public key: #BakaShrot_Ed25519_PublicKeySize (32) raw bytes. +; - Private key: #BakaShrot_Ed25519_PrivateKeySize (64) raw bytes. +; (libsodium's Ed25519 secret key already embeds the seed and the public +; key, which is why it is twice the size of the public key.) +; A node's private key lives in BakaShrot_CoreConfig\PrivateKey (Config.pbi); +; the public key it hands out to peers lives in each +; BakaShrot_PeerConfig\PublicKey. Both are stored as Base64 text in the ini +; file - see EncodeKeyToString()/DecodeKeyFromString() below. +; +; Setup required to build/run this: +; - Windows: the official libsodium release's "libsodium.lib" (import +; library) and "libsodium.dll" alongside the executable. +; - Linux: libsodium-dev (Debian/Ubuntu) or libsodium-devel (Fedora) +; installed, so "-lsodium" resolves at link time and +; libsodium.so.* is available at runtime. +; libsodium itself is the same standard, audited library on both platforms, +; so signatures made on one are verifiable on the other without change. +; ============================================================================ + + +#BakaShrot_Ed25519_PublicKeySize = 32 +#BakaShrot_Ed25519_PrivateKeySize = 64 +#BakaShrot_Ed25519_SignatureSize = 64 + + +CompilerIf #PB_Compiler_OS = #PB_OS_Windows + ImportC "libsodium.lib" +CompilerElse + ImportC "-lsodium" +CompilerEndIf + + ; Must be called once (any number of extra calls are harmless) before any + ; other function below is used. Returns 0 on success, 1 if it was already + ; initialized, -1 if libsodium failed to self-check (e.g. no RNG available). + sodium_init.l() + + ; Fills *PublicKey (32 bytes) and *PrivateKey (64 bytes) with a fresh, + ; cryptographically random Ed25519 keypair. + crypto_sign_keypair.l(*PublicKey, *PrivateKey) + + ; Writes a #BakaShrot_Ed25519_SignatureSize-byte signature of *Message + ; (MessageLength bytes) to *Signature, made with *PrivateKey. + crypto_sign_detached.l(*Signature, *SignatureLength, *Message, MessageLength.q, *PrivateKey) + + ; Returns 0 if *Signature is a valid signature of *Message (MessageLength + ; bytes) made by the holder of the private key matching *PublicKey; + ; non-zero otherwise (forged, corrupted, or signed different data). + crypto_sign_verify_detached.l(*Signature, *Message, MessageLength.q, *PublicKey) + +EndImport + + +; Must be called once at startup, before GenerateKeyPair/EncodeData/DecodeData. +; Returns #False if libsodium could not initialize - treat that as fatal, +; there is no safe fallback to running without it. +Procedure.i InitCryptography() + ProcedureReturn Bool(sodium_init() >= 0) +EndProcedure + + +; Generates a new Ed25519 keypair for provisioning a node. +; *PublicKey must point to #BakaShrot_Ed25519_PublicKeySize bytes, +; *PrivateKey to #BakaShrot_Ed25519_PrivateKeySize bytes. +Procedure GenerateKeyPair(*PublicKey, *PrivateKey) + crypto_sign_keypair(*PublicKey, *PrivateKey) +EndProcedure + + +; Signs *Data (DataLength bytes) with *PrivateKey (this node's own private +; key, #BakaShrot_Ed25519_PrivateKeySize bytes). +; Writes the signature to *Signature, which must point to +; #BakaShrot_Ed25519_SignatureSize bytes. *Data itself is left untouched. +Procedure.i EncodeData(*Data, DataLength.i, *PrivateKey, *Signature) + Protected SignatureLength.q + ProcedureReturn Bool(crypto_sign_detached(*Signature, @SignatureLength, *Data, DataLength, *PrivateKey) = 0) +EndProcedure + + +; Verifies that *Signature (#BakaShrot_Ed25519_SignatureSize bytes) is a +; valid signature of *Data (DataLength bytes), made by the holder of the +; private key matching *PublicKey (the claimed sender's public key, from +; BakaShrot_PeerConfig\PublicKey). +; Returns #True only if the signature checks out. On #False, reject the +; packet outright - do not process it, do not fall back to trusting it. +Procedure.i DecodeData(*Data, DataLength.i, *PublicKey, *Signature) + ProcedureReturn Bool(crypto_sign_verify_detached(*Signature, *Data, DataLength, *PublicKey) = 0) +EndProcedure + + +; Encodes KeySize raw bytes at *Key as a Base64 string, for storing a key in +; the ini file (PrivateKey / PublicKey fields in Config.pbi). +Procedure.s EncodeKeyToString(*Key, KeySize.i) + ProcedureReturn Base64Encoder(*Key, KeySize) +EndProcedure + + +; Decodes KeyString back into KeySize raw bytes at *Key. +; Returns #False (and leaves *Key untouched) if KeyString is not valid +; Base64 or does not decode to exactly KeySize bytes - a malformed or +; truncated key in the config file must never be silently accepted as one +; that's merely different. +Procedure.i DecodeKeyFromString(KeyString.s, *Key, KeySize.i) + ; PureBasic's own docs warn the output buffer must have some slack over + ; the exact decoded size or the decoder can overflow it - at least 25% + ; extra and never under 64 bytes, hence the margin below. + Protected *Buffer, BufferSize.i, DecodedSize.i + + BufferSize = (KeySize * 5) / 4 + 64 + *Buffer = AllocateMemory(BufferSize) + DecodedSize = Base64Decoder(KeyString, *Buffer, BufferSize) + If DecodedSize = KeySize + CopyMemory(*Buffer, *Key, KeySize) + EndIf + FreeMemory(*Buffer) + + ProcedureReturn Bool(DecodedSize = KeySize) +EndProcedure + + +; 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. +CompilerIf #PB_Compiler_IsMainFile + + If Not InitCryptography() + Debug "Failed to initialize libsodium." + Else + Define *PublicKey = AllocateMemory(#BakaShrot_Ed25519_PublicKeySize) + Define *PrivateKey = AllocateMemory(#BakaShrot_Ed25519_PrivateKeySize) + Define *Signature = AllocateMemory(#BakaShrot_Ed25519_SignatureSize) + Define Message.s = ~"{\"messageData\": {\"MsgType\": \"hello\"}}" + Define MessageLength = StringByteLength(Message, #PB_Ascii) + Define *MessageBytes = AllocateMemory(MessageLength) + + PokeS(*MessageBytes, Message, -1, #PB_Ascii) + + GenerateKeyPair(*PublicKey, *PrivateKey) + Debug "PublicKey: " + EncodeKeyToString(*PublicKey, #BakaShrot_Ed25519_PublicKeySize) + Debug "PrivateKey: " + EncodeKeyToString(*PrivateKey, #BakaShrot_Ed25519_PrivateKeySize) + + If EncodeData(*MessageBytes, MessageLength, *PrivateKey, *Signature) + Debug "Signed ok. Signature: " + EncodeKeyToString(*Signature, #BakaShrot_Ed25519_SignatureSize) + + If DecodeData(*MessageBytes, MessageLength, *PublicKey, *Signature) + Debug "Verified ok, as expected." + Else + Debug "FAILED to verify a genuine signature - something is broken." + EndIf + + ; Tamper with one byte and make sure verification then rejects it. + PokeB(*MessageBytes, PeekB(*MessageBytes) ! 1) + If DecodeData(*MessageBytes, MessageLength, *PublicKey, *Signature) + Debug "FAILED: tampered data was accepted as genuine." + Else + Debug "Tampered data correctly rejected." + EndIf + Else + Debug "Failed to sign data." + EndIf + + FreeMemory(*PublicKey) + FreeMemory(*PrivateKey) + FreeMemory(*Signature) + FreeMemory(*MessageBytes) + EndIf + +CompilerEndIf diff --git a/Commons/Networking/Connections.pbi b/Commons/Networking/Connections.pbi new file mode 100644 index 0000000..693202b --- /dev/null +++ b/Commons/Networking/Connections.pbi @@ -0,0 +1,21 @@ + + + + +Enumeration BakaShrot_ConnectionStatuses + #BakaShrot_ConnectionStatus_New + #BakaShrot_ConnectionStatus_Authenticated + #BakaShrot_ConnectionStatus_Idk + #BakaShrot_ConnectionStatus_Disconnected + #BakaShrot_ConnectionStatus_Aborted +EndEnumeration + + + + + + + + + + diff --git a/Commons/Networking/Packets.pbi b/Commons/Networking/Packets.pbi new file mode 100644 index 0000000..10df221 --- /dev/null +++ b/Commons/Networking/Packets.pbi @@ -0,0 +1,26 @@ + + +; Represents the root of all BakaShrot packets. +; Any packets below this size MUST be thrown out. +Structure BakaShrot_PacketBase + Magic.l + Version.l + PacketType.l +EndStructure + +; Fixed values every BakaShrot_PacketBase must carry. Checked on decode so a +; packet from a different protocol/version is thrown out instead of being +; misparsed. +#BakaShrot_ProtocolMagic = $42534854 ; "BSHT" +#BakaShrot_ProtocolVersion = 1 + +Enumeration BakaShrot_PacketTypes + ; Safety fallback value, should be dropped when encountered + #BakaShrot_PacketType_None = 0 + + #BakaShrot_PacketType_AuthenticationRequest = 1 + #BakaShrot_PacketType_AuthenticationChallenge = 2 + #BakaShrot_PacketType_AuthenticationResult = 3 +EndEnumeration + + diff --git a/Commons/Networking/Packets/AuthenticationPacket.pbi b/Commons/Networking/Packets/AuthenticationPacket.pbi new file mode 100644 index 0000000..1339d49 --- /dev/null +++ b/Commons/Networking/Packets/AuthenticationPacket.pbi @@ -0,0 +1,303 @@ + + +; ============================================================================ +; BakaShrot Authentication Packets +; +; The three packets exchanged during the auth handshake: +; C2S AuthRequest - client introduces itself and its public key. +; S2C AuthChallenge - server sends back something for the client to sign. +; C2S AuthResult - client replies with the signed challenge. +; +; Wire format: BakaShrot_PacketBase (Magic, Version, PacketType - see +; Packets.pbi) followed by each struct's own fields, in declaration order. +; Every string field is packed as {len}{str}: a 4-byte (Long) UTF-8 byte +; length, followed by exactly that many UTF-8 bytes - no null terminator. +; ============================================================================ + + +XIncludeFile "../Packets.pbi" + +; C2S auth request +Structure BakaShrot_AuthRequest Extends BakaShrot_PacketBase + ClientGroupId.l + ClientNodeId.l + ClientPubKeyB64.s +EndStructure + +; S2C Chalenge the client must sign it with their private key +Structure BakaShrot_AuthChallenge Extends BakaShrot_PacketBase + ClientPubKeyB64.s +EndStructure + +; C2S Response with the chalenge signed by their private key +Structure BakaShrot_AuthResult Extends BakaShrot_PacketBase + ChallengeResponseB64.s +EndStructure + + +DeclareModule BakaShrot_AuthenticationPacket + + ; Encodes *Request/*Challenge/*Result into a freshly allocated buffer. + ; *OutSize receives its size in bytes. Returns 0 (and leaves *OutSize + ; untouched) if the input is invalid (null) or the buffer could not be + ; allocated. Caller owns the returned buffer - free it with FreeMemory. + Declare.i EncodeRequest(*Request.BakaShrot_AuthRequest, *OutSize.l) + Declare.i EncodeChallenge(*Challenge.BakaShrot_AuthChallenge, *OutSize.l) + Declare.i EncodeResult(*Result.BakaShrot_AuthResult, *OutSize.l) + + ; Decodes *Buffer (BufferSize bytes) into a freshly allocated struct. + ; Returns 0 if the packet is too small, malformed, truncated, or not of + ; the expected kind. Caller owns the returned struct - free it with + ; FreeStructure. + Declare.i DecodeRequest(*Buffer, BufferSize.i) + Declare.i DecodeChallenge(*Buffer, BufferSize.i) + Declare.i DecodeResult(*Buffer, BufferSize.i) + +EndDeclareModule + + +Module BakaShrot_AuthenticationPacket + + ; ------------------------------------------------------------------------ + ; Wire helpers. Every string on the wire is {len}{str}: a 4-byte UTF-8 + ; byte length followed by exactly that many UTF-8 bytes. + ; ------------------------------------------------------------------------ + + ; Size, in bytes, Str will take once written as {len}{str}. + Procedure.i PackedStringSize(Str.s) + ProcedureReturn 4 + StringByteLength(Str, #PB_UTF8) + EndProcedure + + ; Writes Str at *Buffer + Offset as {len}{str}. *Buffer must have room + ; for at least PackedStringSize(Str) bytes from Offset onward. + Procedure WritePackedString(*Buffer, Offset.i, Str.s) + PokeL(*Buffer + Offset, StringByteLength(Str, #PB_UTF8)) + PokeS(*Buffer + Offset + 4, Str, -1, #PB_UTF8) + EndProcedure + + ; #True if a {len}{str} value starting at Offset is fully contained + ; within the first BufferSize bytes of *Buffer. Always check this before + ; calling ReadPackedString() - it does no bounds checking of its own. + Procedure.i PackedStringFits(*Buffer, BufferSize.i, Offset.i) + Protected ByteLen.l + + If Offset + 4 > BufferSize + ProcedureReturn #False + EndIf + + ByteLen = PeekL(*Buffer + Offset) + If ByteLen < 0 Or Offset + 4 + ByteLen > BufferSize + ProcedureReturn #False + EndIf + + ProcedureReturn #True + EndProcedure + + ; Reads the {len}{str} value at *Buffer + Offset. Caller MUST have + ; checked PackedStringFits() first. + Procedure.s ReadPackedString(*Buffer, Offset.i) + ProcedureReturn PeekS(*Buffer + Offset + 4, PeekL(*Buffer + Offset), #PB_UTF8 | #PB_ByteLength) + EndProcedure + + + ; ------------------------------------------------------------------------ + ; Header. All three packets share the same BakaShrot_PacketBase layout: + ; Magic.l, Version.l, PacketType.l. + ; ------------------------------------------------------------------------ + + ; Writes the packet header at the start of *Buffer. Returns the offset of + ; the first byte after the header. + Procedure.i WriteHeader(*Buffer, PacketType.l) + PokeL(*Buffer, #BakaShrot_ProtocolMagic) + PokeL(*Buffer + 4, #BakaShrot_ProtocolVersion) + PokeL(*Buffer + 8, PacketType) + + ProcedureReturn SizeOf(BakaShrot_PacketBase) + EndProcedure + + ; Validates the header at the start of *Buffer: big enough to hold one, + ; correct Magic/Version, and PacketType matching ExpectedPacketType. + ; Returns the offset of the first byte after the header on success, or + ; -1 if the packet must be thrown out. + Procedure.i ReadHeader(*Buffer, BufferSize.i, ExpectedPacketType.l) + If BufferSize < SizeOf(BakaShrot_PacketBase) + ProcedureReturn -1 + EndIf + + If PeekL(*Buffer) <> #BakaShrot_ProtocolMagic + ProcedureReturn -1 + EndIf + + If PeekL(*Buffer + 4) <> #BakaShrot_ProtocolVersion + ProcedureReturn -1 + EndIf + + If PeekL(*Buffer + 8) <> ExpectedPacketType + ProcedureReturn -1 + EndIf + + ProcedureReturn SizeOf(BakaShrot_PacketBase) + EndProcedure + + + ; ------------------------------------------------------------------------ + ; AuthRequest (C2S) + ; ------------------------------------------------------------------------ + + Procedure.i EncodeRequest(*Request.BakaShrot_AuthRequest, *OutSize.l) + Protected Size.i, *Buffer, Offset.i + + If Not *Request + ProcedureReturn 0 + EndIf + + Size = SizeOf(BakaShrot_PacketBase) + 4 + 4 + PackedStringSize(*Request\ClientPubKeyB64) + + *Buffer = AllocateMemory(Size) + If Not *Buffer + ProcedureReturn 0 + EndIf + + Offset = WriteHeader(*Buffer, #BakaShrot_PacketType_AuthenticationRequest) + + PokeL(*Buffer + Offset, *Request\ClientGroupId) + Offset = Offset + 4 + PokeL(*Buffer + Offset, *Request\ClientNodeId) + Offset = Offset + 4 + + WritePackedString(*Buffer, Offset, *Request\ClientPubKeyB64) + + *OutSize\l = Size + ProcedureReturn *Buffer + EndProcedure + + Procedure.i DecodeRequest(*Buffer, BufferSize.i) + Protected Offset.i, *Request.BakaShrot_AuthRequest + + Offset = ReadHeader(*Buffer, BufferSize, #BakaShrot_PacketType_AuthenticationRequest) + If Offset = -1 + ProcedureReturn 0 + EndIf + + If Offset + 4 + 4 > BufferSize + ProcedureReturn 0 + EndIf + + *Request = AllocateStructure(BakaShrot_AuthRequest) + + *Request\Magic = #BakaShrot_ProtocolMagic + *Request\Version = #BakaShrot_ProtocolVersion + *Request\PacketType = #BakaShrot_PacketType_AuthenticationRequest + + *Request\ClientGroupId = PeekL(*Buffer + Offset) + Offset = Offset + 4 + *Request\ClientNodeId = PeekL(*Buffer + Offset) + Offset = Offset + 4 + + If Not PackedStringFits(*Buffer, BufferSize, Offset) + FreeStructure(*Request) + ProcedureReturn 0 + EndIf + *Request\ClientPubKeyB64 = ReadPackedString(*Buffer, Offset) + + ProcedureReturn *Request + EndProcedure + + + ; ------------------------------------------------------------------------ + ; AuthChallenge (S2C) + ; ------------------------------------------------------------------------ + + Procedure.i EncodeChallenge(*Challenge.BakaShrot_AuthChallenge, *OutSize.l) + Protected Size.i, *Buffer, Offset.i + + If Not *Challenge + ProcedureReturn 0 + EndIf + + Size = SizeOf(BakaShrot_PacketBase) + PackedStringSize(*Challenge\ClientPubKeyB64) + + *Buffer = AllocateMemory(Size) + If Not *Buffer + ProcedureReturn 0 + EndIf + + Offset = WriteHeader(*Buffer, #BakaShrot_PacketType_AuthenticationChallenge) + WritePackedString(*Buffer, Offset, *Challenge\ClientPubKeyB64) + + *OutSize\l = Size + ProcedureReturn *Buffer + EndProcedure + + Procedure.i DecodeChallenge(*Buffer, BufferSize.i) + Protected Offset.i, *Challenge.BakaShrot_AuthChallenge + + Offset = ReadHeader(*Buffer, BufferSize, #BakaShrot_PacketType_AuthenticationChallenge) + If Offset = -1 + ProcedureReturn 0 + EndIf + + If Not PackedStringFits(*Buffer, BufferSize, Offset) + ProcedureReturn 0 + EndIf + + *Challenge = AllocateStructure(BakaShrot_AuthChallenge) + + *Challenge\Magic = #BakaShrot_ProtocolMagic + *Challenge\Version = #BakaShrot_ProtocolVersion + *Challenge\PacketType = #BakaShrot_PacketType_AuthenticationChallenge + *Challenge\ClientPubKeyB64 = ReadPackedString(*Buffer, Offset) + + ProcedureReturn *Challenge + EndProcedure + + + ; ------------------------------------------------------------------------ + ; AuthResult (C2S) + ; ------------------------------------------------------------------------ + + Procedure.i EncodeResult(*Result.BakaShrot_AuthResult, *OutSize.l) + Protected Size.i, *Buffer, Offset.i + + If Not *Result + ProcedureReturn 0 + EndIf + + Size = SizeOf(BakaShrot_PacketBase) + PackedStringSize(*Result\ChallengeResponseB64) + + *Buffer = AllocateMemory(Size) + If Not *Buffer + ProcedureReturn 0 + EndIf + + Offset = WriteHeader(*Buffer, #BakaShrot_PacketType_AuthenticationResult) + WritePackedString(*Buffer, Offset, *Result\ChallengeResponseB64) + + *OutSize\l = Size + ProcedureReturn *Buffer + EndProcedure + + Procedure.i DecodeResult(*Buffer, BufferSize.i) + Protected Offset.i, *Result.BakaShrot_AuthResult + + Offset = ReadHeader(*Buffer, BufferSize, #BakaShrot_PacketType_AuthenticationResult) + If Offset = -1 + ProcedureReturn 0 + EndIf + + If Not PackedStringFits(*Buffer, BufferSize, Offset) + ProcedureReturn 0 + EndIf + + *Result = AllocateStructure(BakaShrot_AuthResult) + + *Result\Magic = #BakaShrot_ProtocolMagic + *Result\Version = #BakaShrot_ProtocolVersion + *Result\PacketType = #BakaShrot_PacketType_AuthenticationResult + *Result\ChallengeResponseB64 = ReadPackedString(*Buffer, Offset) + + ProcedureReturn *Result + EndProcedure + +EndModule + diff --git a/Core/Config/Config.pbi b/Core/Config/Config.pbi new file mode 100644 index 0000000..4220ca8 --- /dev/null +++ b/Core/Config/Config.pbi @@ -0,0 +1,260 @@ +; ============================================================================ +; BakaShrot Config +; +; Loads and saves the node's configuration from/to an ini file via +; PureBasic's native Preferences library. +; +; Section layout: +; [BakaShrot] -> BakaShrot_CoreConfig +; [BakaShrot.Server] -> BakaShrot_CoreConfig\Server +; [BakaShrot.Client] -> BakaShrot_CoreConfig\Client +; [BakaShrot.Peer.] -> one BakaShrot_CoreConfig\Peers() entry per +; section; is only a key for this file, +; it is never sent on the wire. +; ============================================================================ + + +; Ini Section: [BakaShrot.Peer.] (one section per known peer) +Structure BakaShrot_PeerConfig + + ; Remote adress of the peer + ; Can be a domain name, IPV4, IPV6 + Host.s + + ; Remote port of the peer + ; 0-65535 + Port.u + + ; Remote node's GID + ; The connection will be aborted if it differs. + GroupId.u + + ; Remote node's node id + ; The connection will be aborted if it differs. + NodeId.u + + ; This peer's Ed25519 public key (Base64), used to verify the signature + ; on every packet it sends. See Networking/Cryptography.pbi. + PublicKey.s + +EndStructure + + +; Ini Section: [BakaShrot.Server] +Structure BakaShrot_ServerConfig + + ; IPV4 that it will be bound to + Host.s + + ; Used port + Port.u + + ; List of groups from which the server will attempt to replicate from. + ; Format: 0;1;100-150;200;... + List ReplicatingGroupIds.i() + +EndStructure + + +; Ini Section: [BakaShrot.Client] +Structure BakaShrot_ClientConfig + + ; No idea, feel free to suggest ideas + +EndStructure + + +; Ini Section: [BakaShrot] +Structure BakaShrot_CoreConfig + + ; This node's Ed25519 private key (Base64), used to sign every packet it + ; sends. Its matching public key must be handed to peers, who store it + ; as PublicKey in the relevant [BakaShrot.Peer.] section of THEIR + ; own config. See Networking/Cryptography.pbi. + PrivateKey.s + + ; Replication Group ID to which the node belongs. + ; Will be used during the connection phase to identify itself. + ; Will be used to set the messages' GID + ; Will be used by itself and other nodes to know which messages to replicate and which to ignore. + GroupId.u + + ; Node ID that uniquely represents the node within a replication group. + ; Will be used during the connection phase to identify itself. + ; Will be used to set the messages' NID + NodeId.u + + ; [BakaShrot.Server] + Server.BakaShrot_ServerConfig + + ; [BakaShrot.Client] + Client.BakaShrot_ClientConfig + + ; One [BakaShrot.Peer.] entry per map key. + Map Peers.BakaShrot_PeerConfig() + +EndStructure + + +Macro Ptr_BakaShrot_CoreConfig : i : EndMacro + + +; Parses a "0;1;100-150;200" style range list into a flat list of ids. +Procedure ParseGroupIdRanges(RangesString.s, List Ids.i()) + Protected i, Part.s, DashPos, FromId, ToId, Id + + ClearList(Ids()) + + For i = 1 To CountString(RangesString, ";") + 1 + Part = Trim(StringField(RangesString, i, ";")) + If Part = "" + Continue + EndIf + + DashPos = FindString(Part, "-") + If DashPos + FromId = Val(Left(Part, DashPos - 1)) + ToId = Val(Mid(Part, DashPos + 1)) + For Id = FromId To ToId + AddElement(Ids()) + Ids() = Id + Next + Else + AddElement(Ids()) + Ids() = Val(Part) + EndIf + Next + +EndProcedure + + +; Serializes a flat list of ids back into "id;id;id" form. +; (Ranges are not reconstructed on save; each id is written out individually.) +Procedure.s FormatGroupIdList(List Ids.i()) + Protected Result.s + + ForEach Ids() + If Result <> "" + Result + ";" + EndIf + Result + Str(Ids()) + Next + + ProcedureReturn Result +EndProcedure + + +Procedure.Ptr_BakaShrot_CoreConfig LoadConfig(IniFilePath.s) + Protected *Config.BakaShrot_CoreConfig + Protected GroupName.s, PeerName.s + + If Not OpenPreferences(IniFilePath) + ProcedureReturn 0 + EndIf + + *Config = AllocateStructure(BakaShrot_CoreConfig) + + PreferenceGroup("BakaShrot") + *Config\PrivateKey = ReadPreferenceString("PrivateKey", "") + *Config\GroupId = ReadPreferenceLong("GroupId", 0) + *Config\NodeId = ReadPreferenceLong("NodeId", 0) + + PreferenceGroup("BakaShrot.Server") + *Config\Server\Host = ReadPreferenceString("Host", "") + *Config\Server\Port = ReadPreferenceLong("Port", 0) + ParseGroupIdRanges(ReadPreferenceString("ReplicatingGroupIds", ""), *Config\Server\ReplicatingGroupIds()) + + ; [BakaShrot.Client] has no fields yet. + + ; Discover every [BakaShrot.Peer.] section dynamically, so adding a + ; peer never needs a second "list of peer names" kept in sync by hand. + ExaminePreferenceGroups() + While NextPreferenceGroup() + GroupName = PreferenceGroupName() + + If Left(GroupName, Len("BakaShrot.Peer.")) = "BakaShrot.Peer." + PeerName = Mid(GroupName, Len("BakaShrot.Peer.") + 1) + If PeerName <> "" + AddMapElement(*Config\Peers(), PeerName) + *Config\Peers()\Host = ReadPreferenceString("Host", "") + *Config\Peers()\Port = ReadPreferenceLong("Port", 0) + *Config\Peers()\GroupId = ReadPreferenceLong("GroupId", 0) + *Config\Peers()\NodeId = ReadPreferenceLong("NodeId", 0) + *Config\Peers()\PublicKey = ReadPreferenceString("PublicKey", "") + EndIf + EndIf + Wend + + ClosePreferences() + + ProcedureReturn *Config +EndProcedure + + +Procedure.i SaveConfig(IniFilePath.s, *Config.BakaShrot_CoreConfig) + + If Not CreatePreferences(IniFilePath) + ProcedureReturn #False + EndIf + + PreferenceGroup("BakaShrot") + WritePreferenceString("PrivateKey", *Config\PrivateKey) + WritePreferenceLong("GroupId", *Config\GroupId) + WritePreferenceLong("NodeId", *Config\NodeId) + + PreferenceGroup("BakaShrot.Server") + WritePreferenceString("Host", *Config\Server\Host) + WritePreferenceLong("Port", *Config\Server\Port) + WritePreferenceString("ReplicatingGroupIds", FormatGroupIdList(*Config\Server\ReplicatingGroupIds())) + + PreferenceGroup("BakaShrot.Client") + ; No fields yet. + + ForEach *Config\Peers() + PreferenceGroup("BakaShrot.Peer." + MapKey(*Config\Peers())) + WritePreferenceString("Host", *Config\Peers()\Host) + WritePreferenceLong("Port", *Config\Peers()\Port) + WritePreferenceLong("GroupId", *Config\Peers()\GroupId) + WritePreferenceLong("NodeId", *Config\Peers()\NodeId) + WritePreferenceString("PublicKey", *Config\Peers()\PublicKey) + Next + + ClosePreferences() + + ProcedureReturn #True +EndProcedure + + +Procedure FreeConfig(*Config.BakaShrot_CoreConfig) + FreeStructure(*Config) +EndProcedure + + +; 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. +CompilerIf #PB_Compiler_IsMainFile + + Define *Config.BakaShrot_CoreConfig = LoadConfig("schema.ini") + + If *Config + Debug "PrivateKey: " + *Config\PrivateKey + Debug "GroupId: " + Str(*Config\GroupId) + Debug "NodeId: " + Str(*Config\NodeId) + + Debug "Server: " + *Config\Server\Host + ":" + Str(*Config\Server\Port) + ForEach *Config\Server\ReplicatingGroupIds() + Debug " Replicating group: " + Str(*Config\Server\ReplicatingGroupIds()) + Next + + ForEach *Config\Peers() + Debug "Peer '" + MapKey(*Config\Peers()) + "': " + *Config\Peers()\Host + ":" + Str(*Config\Peers()\Port) + " PublicKey=" + *Config\Peers()\PublicKey + Next + + SaveConfig("schema_out.ini", *Config) + + FreeConfig(*Config) + Else + Debug "Failed to load schema.ini" + EndIf + +CompilerEndIf diff --git a/Core/Config/Config.pbi.cfg b/Core/Config/Config.pbi.cfg new file mode 100644 index 0000000..943c0db --- /dev/null +++ b/Core/Config/Config.pbi.cfg @@ -0,0 +1,8 @@ +IDE Options = PureBasic 6.41 beta 2 (Windows - x64) +CursorPosition = 135 +Folding = -- +EnableXP +DPIAware +CompileSourceDirectory +EnableCompileCount = 1 +EnableBuildCount = 0 diff --git a/Core/Config/schema.ini b/Core/Config/schema.ini new file mode 100644 index 0000000..b86cfcb --- /dev/null +++ b/Core/Config/schema.ini @@ -0,0 +1,56 @@ +; BakaShrot config file. +; Section names are literal strings as far as PureBasic's Preferences +; library is concerned — the dots below are just part of the name. + +[BakaShrot] +; Config shared by every type of config. + +; This node's Ed25519 private key (Base64), used to sign every packet it +; sends. Its matching public key must be handed to peers, who store it as +; PublicKey below in THEIR own config. See Networking/Cryptography.pbi. +PrivateKey = + +; Replication Group ID to which this node belongs. +GroupId = + +; Node ID that uniquely represents this node within its replication group. +NodeId = + + +[BakaShrot.Server] +; IPV4 that the server will be bound to. +Host = + +; Used port. +Port = + +; List of groups from which the server will attempt to replicate. +; Format: 0;1;100-150;200;... +ReplicatingGroupIds = + +; Amount of threads used for networking-related tasks +NetThreadPoolSize = 4 + + +[BakaShrot.Client] +; No fields yet. + + +; One [BakaShrot.Peer.] section per peer this node talks to. +; is only a key for this file; it is never sent on the wire. +[BakaShrot.Peer.example] +; Remote address of the peer. Can be a domain name, IPV4 or IPV6. +Host = + +; Remote port of the peer (0-65535). +Port = + +; Remote node's GID. The connection is aborted if it differs. +GroupId = + +; Remote node's node id. The connection is aborted if it differs. +NodeId = + +; This peer's Ed25519 public key (Base64), used to verify the signature on +; every packet it sends. See Networking/Cryptography.pbi. +PublicKey = diff --git a/Core/Config/schema_out.ini b/Core/Config/schema_out.ini new file mode 100644 index 0000000..2c829a2 --- /dev/null +++ b/Core/Config/schema_out.ini @@ -0,0 +1,14 @@ + +[BakaShrot] +PrivateKey = +GroupId = 0 +NodeId = 0 +[BakaShrot.Server] +Host = +Port = 0 +ReplicatingGroupIds = +[BakaShrot.Peer.example] +Host = +Port = 0 +GroupId = 0 +NodeId = 0 diff --git a/Core/Storage/Storage.pbi b/Core/Storage/Storage.pbi new file mode 100644 index 0000000..0a6ee56 --- /dev/null +++ b/Core/Storage/Storage.pbi @@ -0,0 +1,203 @@ +; ============================================================================ +; BakaShrot Storage +; +; Opens the SQLite database file that backs the node's local storage, and +; provides the basic read/write operations on top of it. +; Schema: see db_schema_v1.dbml in this same folder. +; ============================================================================ + + +UseSQLiteDatabase() + + +; One row of the "data" table (see db_schema_v1.dbml). +Structure BakaShrot_Message + MessageId.i + JsonData.s +EndStructure + + +; Opens (and creates, if missing) the SQLite database at DatabasePath. +; Returns the PureBasic database number, or 0 if the file could not be opened. +Procedure.i OpenStorageDatabase(DatabasePath.s) + ProcedureReturn OpenDatabase(#PB_Any, DatabasePath, "", "") +EndProcedure + + +; Creates the tables and indexes described by db_schema_v1.dbml, if they +; don't exist yet. Plain "CREATE IF NOT EXISTS" for now - a real versioned +; upgrade mechanism (DbUpdater) will replace this later. +Procedure.i SetupStorageDatabase(DbId.i) + + If Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS archives (" + + "delete_by INTEGER NOT NULL, " + + "message_data TEXT NOT NULL)") + ProcedureReturn #False + EndIf + + If Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS data (" + + "group_id INTEGER NOT NULL, " + + "node_id INTEGER NOT NULL, " + + "message_id INTEGER NOT NULL, " + + "message_data TEXT NOT NULL)") + ProcedureReturn #False + EndIf + If Not DatabaseUpdate(DbId, "CREATE INDEX IF NOT EXISTS idx_data_group_node ON data (group_id, node_id)") + ProcedureReturn #False + EndIf + If Not DatabaseUpdate(DbId, "CREATE INDEX IF NOT EXISTS idx_data_message_id ON data (message_id)") + ProcedureReturn #False + EndIf + + ; Not used yet, but created now so the on-disk schema already matches + ; db_schema_v1.dbml. + If Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS attachements (" + + "group_id INTEGER NOT NULL, " + + "node_id INTEGER NOT NULL, " + + "message_id INTEGER NOT NULL, " + + "attachement_data BLOB NOT NULL)") + ProcedureReturn #False + EndIf + If Not DatabaseUpdate(DbId, "CREATE INDEX IF NOT EXISTS idx_attachements_group_node ON attachements (group_id, node_id)") + ProcedureReturn #False + EndIf + If Not DatabaseUpdate(DbId, "CREATE INDEX IF NOT EXISTS idx_attachements_message_id ON attachements (message_id)") + ProcedureReturn #False + EndIf + + ProcedureReturn #True +EndProcedure + + +; Inserts one JSON message into the "data" table. +Procedure.i Insert(DbId.i, GroupId.i, NodeId.i, MessageId.i, JsonData.s) + SetDatabaseLong(DbId, 0, GroupId) + SetDatabaseLong(DbId, 1, NodeId) + SetDatabaseLong(DbId, 2, MessageId) + SetDatabaseString(DbId, 3, JsonData) + + ProcedureReturn DatabaseUpdate(DbId, "INSERT INTO data (group_id, node_id, message_id, message_data) VALUES (?, ?, ?, ?)") +EndProcedure + + +; Gets every message stored for a given group_id/node_id pair - the +; "(group_id, node_id)" index - ordered by message_id. +Procedure.i GetMessagesByGroupAndNode(DbId.i, GroupId.i, NodeId.i, List Messages.BakaShrot_Message()) + ClearList(Messages()) + + SetDatabaseLong(DbId, 0, GroupId) + SetDatabaseLong(DbId, 1, NodeId) + + If Not DatabaseQuery(DbId, "SELECT message_id, message_data FROM data WHERE group_id = ? AND node_id = ? ORDER BY message_id") + ProcedureReturn #False + EndIf + + While NextDatabaseRow(DbId) + AddElement(Messages()) + Messages()\MessageId = GetDatabaseLong(DbId, 0) + Messages()\JsonData = GetDatabaseString(DbId, 1) + Wend + FinishDatabaseQuery(DbId) + + ProcedureReturn #True +EndProcedure + + +; Gets every message stored under a given message_id, regardless of which +; group/node it belongs to - the standalone "message_id" index. +Procedure.i GetMessagesByMessageId(DbId.i, MessageId.i, List Messages.BakaShrot_Message()) + ClearList(Messages()) + + SetDatabaseLong(DbId, 0, MessageId) + + If Not DatabaseQuery(DbId, "SELECT message_id, message_data FROM data WHERE message_id = ?") + ProcedureReturn #False + EndIf + + While NextDatabaseRow(DbId) + AddElement(Messages()) + Messages()\MessageId = GetDatabaseLong(DbId, 0) + Messages()\JsonData = GetDatabaseString(DbId, 1) + Wend + FinishDatabaseQuery(DbId) + + ProcedureReturn #True +EndProcedure + + +; Test helper: scans every stored message and collects the value found at +; JsonPath (e.g. "$.messageData.MsgType"), skipping messages where it's +; missing or null. Kept basic on purpose - no paging, no group/node filter. +Procedure.i GetValuesAtJsonPath(DbId.i, JsonPath.s, List Values.s()) + ClearList(Values()) + + SetDatabaseString(DbId, 0, JsonPath) + SetDatabaseString(DbId, 1, JsonPath) + + If Not DatabaseQuery(DbId, "SELECT message_data ->> ? FROM data WHERE message_data ->> ? IS NOT NULL") + ProcedureReturn #False + EndIf + + While NextDatabaseRow(DbId) + AddElement(Values()) + Values() = GetDatabaseString(DbId, 0) + Wend + FinishDatabaseQuery(DbId) + + ProcedureReturn #True +EndProcedure + + +; Returns the highest message_id stored for a given group_id/node_id pair, +; or -1 if there's none yet. Will likely grow into a cached counter later. +Procedure.i GetLatestMessageId(DbId.i, GroupId.i, NodeId.i) + Protected MessageId.i = -1 + + SetDatabaseLong(DbId, 0, GroupId) + SetDatabaseLong(DbId, 1, NodeId) + + If DatabaseQuery(DbId, "SELECT COALESCE(MAX(message_id), -1) FROM data WHERE group_id = ? AND node_id = ?") + If NextDatabaseRow(DbId) + MessageId = GetDatabaseLong(DbId, 0) + EndIf + FinishDatabaseQuery(DbId) + EndIf + + ProcedureReturn MessageId +EndProcedure + + +; 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. +CompilerIf #PB_Compiler_IsMainFile + + Define DbId = OpenStorageDatabase("storage.sqlite") + + If DbId + If SetupStorageDatabase(DbId) + Insert(DbId, 1, 1, 1, ~"{\"messageData\": {\"MsgType\": \"hello\"}}") + Insert(DbId, 1, 1, 2, ~"{\"messageData\": {\"MsgType\": \"world\"}}") + + NewList Messages.BakaShrot_Message() + GetMessagesByGroupAndNode(DbId, 1, 1, Messages()) + ForEach Messages() + Debug "Message #" + Str(Messages()\MessageId) + ": " + Messages()\JsonData + Next + + NewList MsgTypes.s() + GetValuesAtJsonPath(DbId, "$.messageData.MsgType", MsgTypes()) + ForEach MsgTypes() + Debug "MsgType: " + MsgTypes() + Next + + Debug "Latest message id: " + Str(GetLatestMessageId(DbId, 1, 1)) + Else + Debug "Failed to set up database: " + DatabaseError() + EndIf + + CloseDatabase(DbId) + Else + Debug "Failed to open database: " + DatabaseError() + EndIf + +CompilerEndIf diff --git a/Core/Storage/db_schema_v0.dbml b/Core/Storage/db_schema_v0.dbml new file mode 100644 index 0000000..a878064 --- /dev/null +++ b/Core/Storage/db_schema_v0.dbml @@ -0,0 +1,32 @@ + +table archives { + # UTC Unix Timestamp after which this archived message should be deleted. + delete_by ??? [NOT NULL] + + message_data TEXT [NOT NULL] +} + +table data { + group_id INTEGER [NOT NULL] + node_id INTEGER [NOT NULL] + message_id INTEGER [NOT NULL] + message_data TEXT [NOT NULL] +} + +# Create it, but we'll implement this later. +table attachements { + group_id INTEGER [NOT NULL] + node_id INTEGER [NOT NULL] + message_id INTEGER [NOT NULL] + attachement_data BLOB [NOT NULL] +} + +index { + data, on combined group_id/node_id + data, on message_id + attachements, on combined group_id/node_id + attachements, on message_id +} + +# Note, ignore it +# msg_type TEXT GENERATED ALWAYS AS (data ->> '$.messageData.MsgType') VIRTUAL diff --git a/Core/Storage/db_schema_v1.dbml b/Core/Storage/db_schema_v1.dbml new file mode 100644 index 0000000..f22ad1e --- /dev/null +++ b/Core/Storage/db_schema_v1.dbml @@ -0,0 +1,34 @@ +table archives { + // UTC Unix Timestamp after which this archived message should be deleted. + delete_by integer [not null] + + message_data text [not null] +} + +table data { + group_id integer [not null] + node_id integer [not null] + message_id integer [not null] + message_data text [not null] + + indexes { + (group_id, node_id) + message_id + } +} + +// Create it, but we'll implement this later. +table attachements { + group_id integer [not null] + node_id integer [not null] + message_id integer [not null] + attachement_data blob [not null] + + indexes { + (group_id, node_id) + message_id + } +} + +// Note, ignore it +// msg_type TEXT GENERATED ALWAYS AS (data ->> '$.messageData.MsgType') VIRTUAL diff --git a/Includes/PB-MessagePack b/Includes/PB-MessagePack new file mode 160000 index 0000000..ea38a45 --- /dev/null +++ b/Includes/PB-MessagePack @@ -0,0 +1 @@ +Subproject commit ea38a45cf307a8a8165ba910e2bb86fa26512161 diff --git a/Libs/libsodium/Index of -libsodium-releases-.url b/Libs/libsodium/Index of -libsodium-releases-.url new file mode 100644 index 0000000..009736f --- /dev/null +++ b/Libs/libsodium/Index of -libsodium-releases-.url @@ -0,0 +1,2 @@ +[InternetShortcut] +URL=https://download.libsodium.org/libsodium/releases/ diff --git a/Review.md b/Review.md new file mode 100644 index 0000000..c4be360 --- /dev/null +++ b/Review.md @@ -0,0 +1,13 @@ + +Ignore for the time being + +# Rules + +## ??? +Any structure related to networking cannot use the `.i` data type. +Any use of this type in those should fail the review. + +## ??? +Any enumerations related to networking must declare its values explicitely. +Not doing this can cause parsing failures. +Any missing value should fail the review. diff --git a/readme.md b/readme.md new file mode 100644 index 0000000..78ba525 --- /dev/null +++ b/readme.md @@ -0,0 +1,11 @@ +# BakaShrot + + +## ??? + + + +# + + + diff --git a/sqlite_json_index_demo.py b/sqlite_json_index_demo.py new file mode 100644 index 0000000..7769df4 --- /dev/null +++ b/sqlite_json_index_demo.py @@ -0,0 +1,185 @@ +""" +SQLite JSON subfield indexing demo. + +Shows the pattern discussed: a table with a JSON blob column where rows have +varying shapes, a generated column that pulls one subfield out of the JSON, +and an index on that generated column so lookups by the subfield don't +require a full table scan. Also adds a couple of views so the result is +pleasant to poke around in a GUI tool like SQLiteStudio. + +Stdlib only (sqlite3, json, random, pathlib). Writes events.db next to this +script; re-running the script deletes and regenerates it from scratch. +""" + +import json +import random +import sqlite3 +from pathlib import Path + +DB_PATH = Path(__file__).resolve().parent / "events.db" +MIN_SQLITE_VERSION = (3, 31, 0) # generated columns require this + + +def check_sqlite_version() -> None: + version = tuple(int(part) for part in sqlite3.sqlite_version.split(".")) + if version < MIN_SQLITE_VERSION: + raise RuntimeError( + f"sqlite3 {sqlite3.sqlite_version} is too old; generated columns " + f"need >= {'.'.join(map(str, MIN_SQLITE_VERSION))}" + ) + + +def create_schema(conn: sqlite3.Connection) -> None: + conn.execute( + """ + CREATE TABLE events ( + id INTEGER PRIMARY KEY, + data TEXT NOT NULL, + -- pulled out of data for indexing/querying; not stored twice + msg_type TEXT GENERATED ALWAYS AS ( + json_extract(data, '$.messageData.MsgType') + ) VIRTUAL + ) + """ + ) + conn.execute("CREATE INDEX idx_events_msg_type ON events (msg_type)") + + +def create_views(conn: sqlite3.Connection) -> None: + # Flattened, browsable overview of every row regardless of shape -- + # fields that don't apply to a given msg_type just come back NULL. + conn.execute( + """ + CREATE VIEW event_summary AS + SELECT + id, + msg_type, + json_extract(data, '$.messageData.userId') AS user_id, + data + FROM events + """ + ) + + # Type-specific view: only PURCHASE rows, with cents converted to a + # normal dollar amount. This is the pattern for any other MsgType you + # want to drill into -- copy this, swap the WHERE and the extracted + # fields. + conn.execute( + """ + CREATE VIEW purchase_details AS + SELECT + id, + json_extract(data, '$.messageData.userId') AS user_id, + json_extract(data, '$.messageData.amountCents') / 100.0 AS amount_usd, + json_extract(data, '$.messageData.items') AS items + FROM events + WHERE msg_type = 'PURCHASE' + """ + ) + + +def make_row(msg_type: str) -> dict: + """Each MsgType has a genuinely different JSON shape.""" + if msg_type == "LOGIN": + return { + "messageData": { + "MsgType": "LOGIN", + "userId": random.randint(1, 500), + "ip": f"10.0.{random.randint(0, 255)}.{random.randint(0, 255)}", + } + } + if msg_type == "LOGOUT": + return { + "messageData": { + "MsgType": "LOGOUT", + "userId": random.randint(1, 500), + "sessionDurationSec": random.randint(5, 3600), + } + } + if msg_type == "PURCHASE": + return { + "messageData": { + "MsgType": "PURCHASE", + "userId": random.randint(1, 500), + "amountCents": random.randint(99, 20000), + "items": random.randint(1, 5), + } + } + if msg_type == "ERROR": + # no userId at all here -- deliberately a different shape + return { + "messageData": { + "MsgType": "ERROR", + "code": random.choice(["TIMEOUT", "BAD_AUTH", "RATE_LIMIT"]), + "retryable": random.choice([True, False]), + } + } + raise ValueError(f"unknown msg_type: {msg_type}") + + +def generate_rows(count: int) -> list[tuple[str]]: + weights = {"LOGIN": 40, "LOGOUT": 35, "PURCHASE": 15, "ERROR": 10} + types = list(weights.keys()) + picks = random.choices(types, weights=list(weights.values()), k=count) + return [(json.dumps(make_row(t)),) for t in picks] + + +def insert_rows(conn: sqlite3.Connection, rows: list[tuple[str]]) -> None: + conn.executemany("INSERT INTO events (data) VALUES (?)", rows) + + +def query_counts_by_type(conn: sqlite3.Connection) -> None: + print("-- counts by msg_type --") + for msg_type, count in conn.execute( + "SELECT msg_type, COUNT(*) FROM events GROUP BY msg_type ORDER BY msg_type" + ): + print(f"{msg_type:10s} {count}") + + +def query_purchases(conn: sqlite3.Connection) -> None: + print("\n-- sample PURCHASE rows (via the indexed column) --") + rows = conn.execute( + """ + SELECT id, + json_extract(data, '$.messageData.userId') AS user_id, + json_extract(data, '$.messageData.amountCents') AS amount_cents + FROM events + WHERE msg_type = 'PURCHASE' + ORDER BY id + LIMIT 5 + """ + ).fetchall() + for row in rows: + print(row) + + +def confirm_index_is_used(conn: sqlite3.Connection) -> None: + plan = conn.execute( + "EXPLAIN QUERY PLAN SELECT * FROM events WHERE msg_type = 'ERROR'" + ).fetchall() + plan_text = " | ".join(row[-1] for row in plan) + print(f"\n-- query plan for WHERE msg_type = 'ERROR' --\n{plan_text}") + if "idx_events_msg_type" not in plan_text: + raise AssertionError( + f"expected idx_events_msg_type to be used, got: {plan_text}" + ) + + +def main() -> None: + check_sqlite_version() + random.seed(0) # reproducible output + + conn = sqlite3.connect(":memory:") + create_schema(conn) + insert_rows(conn, generate_rows(2000)) + conn.commit() + + query_counts_by_type(conn) + query_purchases(conn) + confirm_index_is_used(conn) + + conn.close() + + +if __name__ == "__main__": + main()