1
0
mirror of https://github.com/aziascreations/BakaShrot.git synced 2026-11-23 20:58:46 +01:00

Initial commit

This commit is contained in:
2026-11-05 22:45:47 +01:00
commit a0daf73c8e
19 changed files with 1368 additions and 0 deletions
+260
View File
@@ -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.<name>] -> one BakaShrot_CoreConfig\Peers() entry per
; section; <name> is only a key for this file,
; it is never sent on the wire.
; ============================================================================
; Ini Section: [BakaShrot.Peer.<name>] (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.<name>] 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.<name>] 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.<name>] 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
+8
View File
@@ -0,0 +1,8 @@
IDE Options = PureBasic 6.41 beta 2 (Windows - x64)
CursorPosition = 135
Folding = --
EnableXP
DPIAware
CompileSourceDirectory
EnableCompileCount = 1
EnableBuildCount = 0
+56
View File
@@ -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.<name>] section per peer this node talks to.
; <name> 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 =
+14
View File
@@ -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
+203
View File
@@ -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
+32
View File
@@ -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
+34
View File
@@ -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