Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
009d62a155 | ||
|
|
237d404bcd | ||
|
|
88ceeb2ae9 | ||
|
|
a1f1789d7b | ||
|
|
617f22dda1 | ||
|
|
0a52bb5c03 | ||
|
|
271cdd18e3 | ||
|
|
19b349143d | ||
|
|
7bebbf7bd7 | ||
|
|
2829bcfecd | ||
|
|
7cec803174 | ||
|
|
fe4cb2ca21 | ||
|
|
6dc246e68c | ||
|
|
bc5b5b3b3a | ||
|
|
bc46e11158 | ||
|
|
40f4352a31 | ||
|
|
cb696f5c0f | ||
|
|
fe96ac69d7 | ||
|
|
212f82dedd | ||
|
|
59b7310385 | ||
|
|
8837e49248 | ||
|
|
7e1f7ec4aa | ||
|
|
146878629e | ||
|
|
d7fb26c03b | ||
|
|
74c8bdde71 | ||
|
|
f22ecf493b | ||
|
|
2b35112566 | ||
|
|
a80820b9a8 | ||
|
|
c0bc0e3dfe | ||
|
|
2d593e4107 | ||
|
|
c1bd6f09a9 | ||
|
|
0ff27e6de9 | ||
|
|
59906bbd2f | ||
|
|
7871dc2d3d | ||
|
|
a0dce8e604 | ||
|
|
04ffde421d | ||
|
|
9545ca28cf | ||
|
|
4098358233 | ||
|
|
f2d8330ccc | ||
|
|
1032eebbbe | ||
|
|
93ab8ddf91 | ||
|
|
6ce1b576ee | ||
|
|
99e98827f7 | ||
|
|
26564b6081 | ||
|
|
9ddb1209c9 | ||
|
|
b68232653a | ||
|
|
2e4f551e8e | ||
|
|
40b8723132 | ||
|
|
4d178d951f | ||
|
|
f6fbf8e58e | ||
|
|
3c915a8f58 | ||
|
|
515278c264 | ||
|
|
7100fa5f76 | ||
|
|
77e293bef2 | ||
|
|
d6f257de14 | ||
|
|
8a21a836e5 | ||
|
|
439e229294 | ||
|
|
ffcdcf7350 | ||
|
|
26d1f3522f | ||
|
|
326b92142d | ||
|
|
18c878dfb5 | ||
|
|
1f7e7f88fa | ||
|
|
e0b6dea168 |
No files matched your search
+9
-2
@@ -5,6 +5,7 @@ build/
|
|||||||
!**/src/test/**/build/
|
!**/src/test/**/build/
|
||||||
|
|
||||||
### IntelliJ IDEA ###
|
### IntelliJ IDEA ###
|
||||||
|
.idea
|
||||||
.idea/modules.xml
|
.idea/modules.xml
|
||||||
.idea/jarRepositories.xml
|
.idea/jarRepositories.xml
|
||||||
.idea/compiler.xml
|
.idea/compiler.xml
|
||||||
@@ -23,8 +24,7 @@ out/
|
|||||||
.project
|
.project
|
||||||
.settings
|
.settings
|
||||||
.springBeans
|
.springBeans
|
||||||
.sts4-cache
|
.sts4-caches
|
||||||
bin/
|
|
||||||
!**/src/main/**/bin/
|
!**/src/main/**/bin/
|
||||||
!**/src/test/**/bin/
|
!**/src/test/**/bin/
|
||||||
|
|
||||||
@@ -44,3 +44,10 @@ bin/
|
|||||||
# More
|
# More
|
||||||
.kotlin
|
.kotlin
|
||||||
/.idea/workspace.xml
|
/.idea/workspace.xml
|
||||||
|
/.gigaide/gigaide.properties
|
||||||
|
local.properties
|
||||||
|
/kotlin-js-store/yarn.lock
|
||||||
|
|
||||||
|
# JVM crash diagnostics must never be published
|
||||||
|
*.hprof
|
||||||
|
hs_err_pid*.log
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
<component name="ArtifactManager">
|
||||||
|
<artifact type="jar" name="kiloparsec-js-0.1.2-SNAPSHOT">
|
||||||
|
<output-path>$PROJECT_DIR$/build/libs</output-path>
|
||||||
|
<root id="archive" name="kiloparsec-js-0.1.2-SNAPSHOT.jar" />
|
||||||
|
</artifact>
|
||||||
|
</component>
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
<component name="ArtifactManager">
|
||||||
|
<artifact type="jar" name="kiloparsec-js-0.2.2-SNAPSHOT">
|
||||||
|
<output-path>$PROJECT_DIR$/build/libs</output-path>
|
||||||
|
<root id="archive" name="kiloparsec-js-0.2.2-SNAPSHOT.jar">
|
||||||
|
<element id="module-output" name="kiloparsec.jsMain" />
|
||||||
|
</root>
|
||||||
|
</artifact>
|
||||||
|
</component>
|
||||||
Generated
+8
@@ -0,0 +1,8 @@
|
|||||||
|
<component name="ArtifactManager">
|
||||||
|
<artifact type="jar" name="kiloparsec-js-0.2.3">
|
||||||
|
<output-path>$PROJECT_DIR$/build/libs</output-path>
|
||||||
|
<root id="archive" name="kiloparsec-js-0.2.3.jar">
|
||||||
|
<element id="module-output" name="kiloparsec.jsMain" />
|
||||||
|
</root>
|
||||||
|
</artifact>
|
||||||
|
</component>
|
||||||
Generated
+8
@@ -0,0 +1,8 @@
|
|||||||
|
<component name="ArtifactManager">
|
||||||
|
<artifact type="jar" name="kiloparsec-js-0.2.4">
|
||||||
|
<output-path>$PROJECT_DIR$/build/libs</output-path>
|
||||||
|
<root id="archive" name="kiloparsec-js-0.2.4.jar">
|
||||||
|
<element id="module-output" name="kiloparsec.jsMain" />
|
||||||
|
</root>
|
||||||
|
</artifact>
|
||||||
|
</component>
|
||||||
Generated
+8
@@ -0,0 +1,8 @@
|
|||||||
|
<component name="ArtifactManager">
|
||||||
|
<artifact type="jar" name="kiloparsec-js-0.2.5">
|
||||||
|
<output-path>$PROJECT_DIR$/build/libs</output-path>
|
||||||
|
<root id="archive" name="kiloparsec-js-0.2.5.jar">
|
||||||
|
<element id="module-output" name="kiloparsec.jsMain" />
|
||||||
|
</root>
|
||||||
|
</artifact>
|
||||||
|
</component>
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
<component name="ArtifactManager">
|
||||||
|
<artifact type="jar" name="kiloparsec-js-0.2.5-SNAPSHOT">
|
||||||
|
<output-path>$PROJECT_DIR$/build/libs</output-path>
|
||||||
|
<root id="archive" name="kiloparsec-js-0.2.5-SNAPSHOT.jar">
|
||||||
|
<element id="module-output" name="kiloparsec.jsMain" />
|
||||||
|
</root>
|
||||||
|
</artifact>
|
||||||
|
</component>
|
||||||
Generated
+6
@@ -0,0 +1,6 @@
|
|||||||
|
<component name="ArtifactManager">
|
||||||
|
<artifact type="jar" name="kiloparsec-js-0.2.6">
|
||||||
|
<output-path>$PROJECT_DIR$/build/libs</output-path>
|
||||||
|
<root id="archive" name="kiloparsec-js-0.2.6.jar" />
|
||||||
|
</artifact>
|
||||||
|
</component>
|
||||||
Generated
+8
@@ -0,0 +1,8 @@
|
|||||||
|
<component name="ArtifactManager">
|
||||||
|
<artifact type="jar" name="kiloparsec-js-0.3.1">
|
||||||
|
<output-path>$PROJECT_DIR$/build/libs</output-path>
|
||||||
|
<root id="archive" name="kiloparsec-js-0.3.1.jar">
|
||||||
|
<element id="module-output" name="kiloparsec.jsMain" />
|
||||||
|
</root>
|
||||||
|
</artifact>
|
||||||
|
</component>
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
<component name="ArtifactManager">
|
||||||
|
<artifact type="jar" name="kiloparsec-js-0.3.1-SNAPSHOT">
|
||||||
|
<output-path>$PROJECT_DIR$/build/libs</output-path>
|
||||||
|
<root id="archive" name="kiloparsec-js-0.3.1-SNAPSHOT.jar">
|
||||||
|
<element id="module-output" name="kiloparsec.jsMain" />
|
||||||
|
</root>
|
||||||
|
</artifact>
|
||||||
|
</component>
|
||||||
Generated
+8
@@ -0,0 +1,8 @@
|
|||||||
|
<component name="ArtifactManager">
|
||||||
|
<artifact type="jar" name="kiloparsec-js-0.3.2">
|
||||||
|
<output-path>$PROJECT_DIR$/build/libs</output-path>
|
||||||
|
<root id="archive" name="kiloparsec-js-0.3.2.jar">
|
||||||
|
<element id="module-output" name="kiloparsec.jsMain" />
|
||||||
|
</root>
|
||||||
|
</artifact>
|
||||||
|
</component>
|
||||||
Generated
+8
@@ -0,0 +1,8 @@
|
|||||||
|
<component name="ArtifactManager">
|
||||||
|
<artifact type="jar" name="kiloparsec-js-0.3.3">
|
||||||
|
<output-path>$PROJECT_DIR$/build/libs</output-path>
|
||||||
|
<root id="archive" name="kiloparsec-js-0.3.3.jar">
|
||||||
|
<element id="module-output" name="kiloparsec.jsMain" />
|
||||||
|
</root>
|
||||||
|
</artifact>
|
||||||
|
</component>
|
||||||
Generated
+8
@@ -0,0 +1,8 @@
|
|||||||
|
<component name="ArtifactManager">
|
||||||
|
<artifact type="jar" name="kiloparsec-js-0.4.1">
|
||||||
|
<output-path>$PROJECT_DIR$/build/libs</output-path>
|
||||||
|
<root id="archive" name="kiloparsec-js-0.4.1.jar">
|
||||||
|
<element id="module-output" name="kiloparsec.jsMain" />
|
||||||
|
</root>
|
||||||
|
</artifact>
|
||||||
|
</component>
|
||||||
Generated
+8
@@ -0,0 +1,8 @@
|
|||||||
|
<component name="ArtifactManager">
|
||||||
|
<artifact type="jar" name="kiloparsec-js-0.4.3">
|
||||||
|
<output-path>$PROJECT_DIR$/build/libs</output-path>
|
||||||
|
<root id="archive" name="kiloparsec-js-0.4.3.jar">
|
||||||
|
<element id="module-output" name="kiloparsec.jsMain" />
|
||||||
|
</root>
|
||||||
|
</artifact>
|
||||||
|
</component>
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
<component name="ArtifactManager">
|
||||||
|
<artifact type="jar" name="kiloparsec-jvm-0.1.2-SNAPSHOT">
|
||||||
|
<output-path>$PROJECT_DIR$/build/libs</output-path>
|
||||||
|
<root id="archive" name="kiloparsec-jvm-0.1.2-SNAPSHOT.jar" />
|
||||||
|
</artifact>
|
||||||
|
</component>
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
<component name="ArtifactManager">
|
||||||
|
<artifact type="jar" name="kiloparsec-jvm-0.2.2-SNAPSHOT">
|
||||||
|
<output-path>$PROJECT_DIR$/build/libs</output-path>
|
||||||
|
<root id="archive" name="kiloparsec-jvm-0.2.2-SNAPSHOT.jar">
|
||||||
|
<element id="module-output" name="kiloparsec.jvmMain" />
|
||||||
|
</root>
|
||||||
|
</artifact>
|
||||||
|
</component>
|
||||||
Generated
+8
@@ -0,0 +1,8 @@
|
|||||||
|
<component name="ArtifactManager">
|
||||||
|
<artifact type="jar" name="kiloparsec-jvm-0.2.3">
|
||||||
|
<output-path>$PROJECT_DIR$/build/libs</output-path>
|
||||||
|
<root id="archive" name="kiloparsec-jvm-0.2.3.jar">
|
||||||
|
<element id="module-output" name="kiloparsec.jvmMain" />
|
||||||
|
</root>
|
||||||
|
</artifact>
|
||||||
|
</component>
|
||||||
Generated
+8
@@ -0,0 +1,8 @@
|
|||||||
|
<component name="ArtifactManager">
|
||||||
|
<artifact type="jar" name="kiloparsec-jvm-0.2.4">
|
||||||
|
<output-path>$PROJECT_DIR$/build/libs</output-path>
|
||||||
|
<root id="archive" name="kiloparsec-jvm-0.2.4.jar">
|
||||||
|
<element id="module-output" name="kiloparsec.jvmMain" />
|
||||||
|
</root>
|
||||||
|
</artifact>
|
||||||
|
</component>
|
||||||
Generated
+8
@@ -0,0 +1,8 @@
|
|||||||
|
<component name="ArtifactManager">
|
||||||
|
<artifact type="jar" name="kiloparsec-jvm-0.2.5">
|
||||||
|
<output-path>$PROJECT_DIR$/build/libs</output-path>
|
||||||
|
<root id="archive" name="kiloparsec-jvm-0.2.5.jar">
|
||||||
|
<element id="module-output" name="kiloparsec.jvmMain" />
|
||||||
|
</root>
|
||||||
|
</artifact>
|
||||||
|
</component>
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
<component name="ArtifactManager">
|
||||||
|
<artifact type="jar" name="kiloparsec-jvm-0.2.5-SNAPSHOT">
|
||||||
|
<output-path>$PROJECT_DIR$/build/libs</output-path>
|
||||||
|
<root id="archive" name="kiloparsec-jvm-0.2.5-SNAPSHOT.jar">
|
||||||
|
<element id="module-output" name="kiloparsec.jvmMain" />
|
||||||
|
</root>
|
||||||
|
</artifact>
|
||||||
|
</component>
|
||||||
Generated
+6
@@ -0,0 +1,6 @@
|
|||||||
|
<component name="ArtifactManager">
|
||||||
|
<artifact type="jar" name="kiloparsec-jvm-0.2.6">
|
||||||
|
<output-path>$PROJECT_DIR$/build/libs</output-path>
|
||||||
|
<root id="archive" name="kiloparsec-jvm-0.2.6.jar" />
|
||||||
|
</artifact>
|
||||||
|
</component>
|
||||||
Generated
+8
@@ -0,0 +1,8 @@
|
|||||||
|
<component name="ArtifactManager">
|
||||||
|
<artifact type="jar" name="kiloparsec-jvm-0.3.1">
|
||||||
|
<output-path>$PROJECT_DIR$/build/libs</output-path>
|
||||||
|
<root id="archive" name="kiloparsec-jvm-0.3.1.jar">
|
||||||
|
<element id="module-output" name="kiloparsec.jvmMain" />
|
||||||
|
</root>
|
||||||
|
</artifact>
|
||||||
|
</component>
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
<component name="ArtifactManager">
|
||||||
|
<artifact type="jar" name="kiloparsec-jvm-0.3.1-SNAPSHOT">
|
||||||
|
<output-path>$PROJECT_DIR$/build/libs</output-path>
|
||||||
|
<root id="archive" name="kiloparsec-jvm-0.3.1-SNAPSHOT.jar">
|
||||||
|
<element id="module-output" name="kiloparsec.jvmMain" />
|
||||||
|
</root>
|
||||||
|
</artifact>
|
||||||
|
</component>
|
||||||
Generated
+8
@@ -0,0 +1,8 @@
|
|||||||
|
<component name="ArtifactManager">
|
||||||
|
<artifact type="jar" name="kiloparsec-jvm-0.3.2">
|
||||||
|
<output-path>$PROJECT_DIR$/build/libs</output-path>
|
||||||
|
<root id="archive" name="kiloparsec-jvm-0.3.2.jar">
|
||||||
|
<element id="module-output" name="kiloparsec.jvmMain" />
|
||||||
|
</root>
|
||||||
|
</artifact>
|
||||||
|
</component>
|
||||||
Generated
+8
@@ -0,0 +1,8 @@
|
|||||||
|
<component name="ArtifactManager">
|
||||||
|
<artifact type="jar" name="kiloparsec-jvm-0.3.3">
|
||||||
|
<output-path>$PROJECT_DIR$/build/libs</output-path>
|
||||||
|
<root id="archive" name="kiloparsec-jvm-0.3.3.jar">
|
||||||
|
<element id="module-output" name="kiloparsec.jvmMain" />
|
||||||
|
</root>
|
||||||
|
</artifact>
|
||||||
|
</component>
|
||||||
Generated
+8
@@ -0,0 +1,8 @@
|
|||||||
|
<component name="ArtifactManager">
|
||||||
|
<artifact type="jar" name="kiloparsec-jvm-0.4.1">
|
||||||
|
<output-path>$PROJECT_DIR$/build/libs</output-path>
|
||||||
|
<root id="archive" name="kiloparsec-jvm-0.4.1.jar">
|
||||||
|
<element id="module-output" name="kiloparsec.jvmMain" />
|
||||||
|
</root>
|
||||||
|
</artifact>
|
||||||
|
</component>
|
||||||
Generated
+8
@@ -0,0 +1,8 @@
|
|||||||
|
<component name="ArtifactManager">
|
||||||
|
<artifact type="jar" name="kiloparsec-jvm-0.4.3">
|
||||||
|
<output-path>$PROJECT_DIR$/build/libs</output-path>
|
||||||
|
<root id="archive" name="kiloparsec-jvm-0.4.3.jar">
|
||||||
|
<element id="module-output" name="kiloparsec.jvmMain" />
|
||||||
|
</root>
|
||||||
|
</artifact>
|
||||||
|
</component>
|
||||||
Generated
+24
@@ -1,5 +1,29 @@
|
|||||||
<component name="ProjectCodeStyleConfiguration">
|
<component name="ProjectCodeStyleConfiguration">
|
||||||
<code_scheme name="Project" version="173">
|
<code_scheme name="Project" version="173">
|
||||||
|
<DBN-PSQL>
|
||||||
|
<case-options enabled="true">
|
||||||
|
<option name="KEYWORD_CASE" value="lower" />
|
||||||
|
<option name="FUNCTION_CASE" value="lower" />
|
||||||
|
<option name="PARAMETER_CASE" value="lower" />
|
||||||
|
<option name="DATATYPE_CASE" value="lower" />
|
||||||
|
<option name="OBJECT_CASE" value="preserve" />
|
||||||
|
</case-options>
|
||||||
|
<formatting-settings enabled="false" />
|
||||||
|
</DBN-PSQL>
|
||||||
|
<DBN-SQL>
|
||||||
|
<case-options enabled="true">
|
||||||
|
<option name="KEYWORD_CASE" value="lower" />
|
||||||
|
<option name="FUNCTION_CASE" value="lower" />
|
||||||
|
<option name="PARAMETER_CASE" value="lower" />
|
||||||
|
<option name="DATATYPE_CASE" value="lower" />
|
||||||
|
<option name="OBJECT_CASE" value="preserve" />
|
||||||
|
</case-options>
|
||||||
|
<formatting-settings enabled="false">
|
||||||
|
<option name="STATEMENT_SPACING" value="one_line" />
|
||||||
|
<option name="CLAUSE_CHOP_DOWN" value="chop_down_if_statement_long" />
|
||||||
|
<option name="ITERATION_ELEMENTS_WRAPPING" value="chop_down_if_not_single" />
|
||||||
|
</formatting-settings>
|
||||||
|
</DBN-SQL>
|
||||||
<ScalaCodeStyleSettings>
|
<ScalaCodeStyleSettings>
|
||||||
<option name="MULTILINE_STRING_CLOSING_QUOTES_ON_NEW_LINE" value="true" />
|
<option name="MULTILINE_STRING_CLOSING_QUOTES_ON_NEW_LINE" value="true" />
|
||||||
</ScalaCodeStyleSettings>
|
</ScalaCodeStyleSettings>
|
||||||
|
|||||||
Generated
+6
@@ -0,0 +1,6 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="MarkdownSettings">
|
||||||
|
<option name="showProblemsInCodeBlocks" value="false" />
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
Generated
+3
-1
@@ -3,5 +3,7 @@
|
|||||||
<component name="FrameworkDetectionExcludesConfiguration">
|
<component name="FrameworkDetectionExcludesConfiguration">
|
||||||
<file type="web" url="file://$PROJECT_DIR$" />
|
<file type="web" url="file://$PROJECT_DIR$" />
|
||||||
</component>
|
</component>
|
||||||
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="corretto-17" project-jdk-type="JavaSDK" />
|
<component name="ProjectRootManager" version="2" languageLevel="JDK_21" project-jdk-name="corretto-17" project-jdk-type="JavaSDK">
|
||||||
|
<output url="file://$PROJECT_DIR$/out" />
|
||||||
|
</component>
|
||||||
</project>
|
</project>
|
||||||
Generated
+6
@@ -0,0 +1,6 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="ScalaCompilerConfiguration">
|
||||||
|
<option name="separateProdTestSources" value="false" />
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
Generated
+124
@@ -0,0 +1,124 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="Palette2">
|
||||||
|
<group name="Swing">
|
||||||
|
<item class="com.intellij.uiDesigner.HSpacer" tooltip-text="Horizontal Spacer" icon="/com/intellij/uiDesigner/icons/hspacer.svg" removable="false" auto-create-binding="false" can-attach-label="false">
|
||||||
|
<default-constraints vsize-policy="1" hsize-policy="6" anchor="0" fill="1" />
|
||||||
|
</item>
|
||||||
|
<item class="com.intellij.uiDesigner.VSpacer" tooltip-text="Vertical Spacer" icon="/com/intellij/uiDesigner/icons/vspacer.svg" removable="false" auto-create-binding="false" can-attach-label="false">
|
||||||
|
<default-constraints vsize-policy="6" hsize-policy="1" anchor="0" fill="2" />
|
||||||
|
</item>
|
||||||
|
<item class="javax.swing.JPanel" icon="/com/intellij/uiDesigner/icons/panel.svg" removable="false" auto-create-binding="false" can-attach-label="false">
|
||||||
|
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3" />
|
||||||
|
</item>
|
||||||
|
<item class="javax.swing.JScrollPane" icon="/com/intellij/uiDesigner/icons/scrollPane.svg" removable="false" auto-create-binding="false" can-attach-label="true">
|
||||||
|
<default-constraints vsize-policy="7" hsize-policy="7" anchor="0" fill="3" />
|
||||||
|
</item>
|
||||||
|
<item class="javax.swing.JButton" icon="/com/intellij/uiDesigner/icons/button.svg" removable="false" auto-create-binding="true" can-attach-label="false">
|
||||||
|
<default-constraints vsize-policy="0" hsize-policy="3" anchor="0" fill="1" />
|
||||||
|
<initial-values>
|
||||||
|
<property name="text" value="Button" />
|
||||||
|
</initial-values>
|
||||||
|
</item>
|
||||||
|
<item class="javax.swing.JRadioButton" icon="/com/intellij/uiDesigner/icons/radioButton.svg" removable="false" auto-create-binding="true" can-attach-label="false">
|
||||||
|
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
|
||||||
|
<initial-values>
|
||||||
|
<property name="text" value="RadioButton" />
|
||||||
|
</initial-values>
|
||||||
|
</item>
|
||||||
|
<item class="javax.swing.JCheckBox" icon="/com/intellij/uiDesigner/icons/checkBox.svg" removable="false" auto-create-binding="true" can-attach-label="false">
|
||||||
|
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
|
||||||
|
<initial-values>
|
||||||
|
<property name="text" value="CheckBox" />
|
||||||
|
</initial-values>
|
||||||
|
</item>
|
||||||
|
<item class="javax.swing.JLabel" icon="/com/intellij/uiDesigner/icons/label.svg" removable="false" auto-create-binding="false" can-attach-label="false">
|
||||||
|
<default-constraints vsize-policy="0" hsize-policy="0" anchor="8" fill="0" />
|
||||||
|
<initial-values>
|
||||||
|
<property name="text" value="Label" />
|
||||||
|
</initial-values>
|
||||||
|
</item>
|
||||||
|
<item class="javax.swing.JTextField" icon="/com/intellij/uiDesigner/icons/textField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
|
||||||
|
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
|
||||||
|
<preferred-size width="150" height="-1" />
|
||||||
|
</default-constraints>
|
||||||
|
</item>
|
||||||
|
<item class="javax.swing.JPasswordField" icon="/com/intellij/uiDesigner/icons/passwordField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
|
||||||
|
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
|
||||||
|
<preferred-size width="150" height="-1" />
|
||||||
|
</default-constraints>
|
||||||
|
</item>
|
||||||
|
<item class="javax.swing.JFormattedTextField" icon="/com/intellij/uiDesigner/icons/formattedTextField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
|
||||||
|
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
|
||||||
|
<preferred-size width="150" height="-1" />
|
||||||
|
</default-constraints>
|
||||||
|
</item>
|
||||||
|
<item class="javax.swing.JTextArea" icon="/com/intellij/uiDesigner/icons/textArea.svg" removable="false" auto-create-binding="true" can-attach-label="true">
|
||||||
|
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
|
||||||
|
<preferred-size width="150" height="50" />
|
||||||
|
</default-constraints>
|
||||||
|
</item>
|
||||||
|
<item class="javax.swing.JTextPane" icon="/com/intellij/uiDesigner/icons/textPane.svg" removable="false" auto-create-binding="true" can-attach-label="true">
|
||||||
|
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
|
||||||
|
<preferred-size width="150" height="50" />
|
||||||
|
</default-constraints>
|
||||||
|
</item>
|
||||||
|
<item class="javax.swing.JEditorPane" icon="/com/intellij/uiDesigner/icons/editorPane.svg" removable="false" auto-create-binding="true" can-attach-label="true">
|
||||||
|
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
|
||||||
|
<preferred-size width="150" height="50" />
|
||||||
|
</default-constraints>
|
||||||
|
</item>
|
||||||
|
<item class="javax.swing.JComboBox" icon="/com/intellij/uiDesigner/icons/comboBox.svg" removable="false" auto-create-binding="true" can-attach-label="true">
|
||||||
|
<default-constraints vsize-policy="0" hsize-policy="2" anchor="8" fill="1" />
|
||||||
|
</item>
|
||||||
|
<item class="javax.swing.JTable" icon="/com/intellij/uiDesigner/icons/table.svg" removable="false" auto-create-binding="true" can-attach-label="false">
|
||||||
|
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
|
||||||
|
<preferred-size width="150" height="50" />
|
||||||
|
</default-constraints>
|
||||||
|
</item>
|
||||||
|
<item class="javax.swing.JList" icon="/com/intellij/uiDesigner/icons/list.svg" removable="false" auto-create-binding="true" can-attach-label="false">
|
||||||
|
<default-constraints vsize-policy="6" hsize-policy="2" anchor="0" fill="3">
|
||||||
|
<preferred-size width="150" height="50" />
|
||||||
|
</default-constraints>
|
||||||
|
</item>
|
||||||
|
<item class="javax.swing.JTree" icon="/com/intellij/uiDesigner/icons/tree.svg" removable="false" auto-create-binding="true" can-attach-label="false">
|
||||||
|
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
|
||||||
|
<preferred-size width="150" height="50" />
|
||||||
|
</default-constraints>
|
||||||
|
</item>
|
||||||
|
<item class="javax.swing.JTabbedPane" icon="/com/intellij/uiDesigner/icons/tabbedPane.svg" removable="false" auto-create-binding="true" can-attach-label="false">
|
||||||
|
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
|
||||||
|
<preferred-size width="200" height="200" />
|
||||||
|
</default-constraints>
|
||||||
|
</item>
|
||||||
|
<item class="javax.swing.JSplitPane" icon="/com/intellij/uiDesigner/icons/splitPane.svg" removable="false" auto-create-binding="false" can-attach-label="false">
|
||||||
|
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
|
||||||
|
<preferred-size width="200" height="200" />
|
||||||
|
</default-constraints>
|
||||||
|
</item>
|
||||||
|
<item class="javax.swing.JSpinner" icon="/com/intellij/uiDesigner/icons/spinner.svg" removable="false" auto-create-binding="true" can-attach-label="true">
|
||||||
|
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
|
||||||
|
</item>
|
||||||
|
<item class="javax.swing.JSlider" icon="/com/intellij/uiDesigner/icons/slider.svg" removable="false" auto-create-binding="true" can-attach-label="false">
|
||||||
|
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
|
||||||
|
</item>
|
||||||
|
<item class="javax.swing.JSeparator" icon="/com/intellij/uiDesigner/icons/separator.svg" removable="false" auto-create-binding="false" can-attach-label="false">
|
||||||
|
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3" />
|
||||||
|
</item>
|
||||||
|
<item class="javax.swing.JProgressBar" icon="/com/intellij/uiDesigner/icons/progressbar.svg" removable="false" auto-create-binding="true" can-attach-label="false">
|
||||||
|
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1" />
|
||||||
|
</item>
|
||||||
|
<item class="javax.swing.JToolBar" icon="/com/intellij/uiDesigner/icons/toolbar.svg" removable="false" auto-create-binding="false" can-attach-label="false">
|
||||||
|
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1">
|
||||||
|
<preferred-size width="-1" height="20" />
|
||||||
|
</default-constraints>
|
||||||
|
</item>
|
||||||
|
<item class="javax.swing.JToolBar$Separator" icon="/com/intellij/uiDesigner/icons/toolbarSeparator.svg" removable="false" auto-create-binding="false" can-attach-label="false">
|
||||||
|
<default-constraints vsize-policy="0" hsize-policy="0" anchor="0" fill="1" />
|
||||||
|
</item>
|
||||||
|
<item class="javax.swing.JScrollBar" icon="/com/intellij/uiDesigner/icons/scrollbar.svg" removable="false" auto-create-binding="true" can-attach-label="false">
|
||||||
|
<default-constraints vsize-policy="6" hsize-policy="0" anchor="0" fill="2" />
|
||||||
|
</item>
|
||||||
|
</group>
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
+106
@@ -0,0 +1,106 @@
|
|||||||
|
# Numeric transport priority — protocol 2
|
||||||
|
|
||||||
|
```kotlin
|
||||||
|
import net.sergeych.kiloparsec.call
|
||||||
|
import net.sergeych.kiloparsec.push
|
||||||
|
|
||||||
|
remote.call(command, arguments, priority = 100)
|
||||||
|
remote.push(notification, arguments, priority = 0)
|
||||||
|
```
|
||||||
|
|
||||||
|
Larger signed `Int` values go first within the allowed nonce range. Equal
|
||||||
|
priorities use nonce order for encrypted packets and FIFO for unnumbered packets. Existing
|
||||||
|
call/push entry points remain unchanged and use zero unless invoked inside an
|
||||||
|
explicit priority call context. The overloads are extension functions, preserving
|
||||||
|
existing RemoteInterface implementers. A coroutine context carries the selected
|
||||||
|
value through the encrypted RPC wrappers; it becomes serialized outer-block data.
|
||||||
|
|
||||||
|
The transport owns a nonce-aware outgoing writer and submits one block at a time
|
||||||
|
to the adapter, preserving the selected order through the carrier. Waiting for a response does not occupy the
|
||||||
|
writer: calls retain independent request IDs and response waiters. Both transport
|
||||||
|
responses and errors copy the request's priority, including encrypted RPC errors
|
||||||
|
returned inside an outer response. Pushes have no normal response.
|
||||||
|
|
||||||
|
## Wire compatibility
|
||||||
|
|
||||||
|
The legacy block tag and body are unchanged. Nonzero priority is appended as four
|
||||||
|
big-endian two's-complement bytes. Zero omits the trailer entirely. The new reader
|
||||||
|
defaults to zero only when the trailer is absent; a partial trailer is malformed.
|
||||||
|
|
||||||
|
This relies on each Transport.Block having its own finite byte-array frame. TCP's
|
||||||
|
existing length prefix, WebSocket messages and UDP data blocks provide that
|
||||||
|
boundary. The old decoder consumes the legacy body and ignores trailing bytes.
|
||||||
|
Do not use this EOF-terminated extension to concatenate unframed Block objects or
|
||||||
|
embed them directly in a positional collection; wrap each block in its own bytes.
|
||||||
|
The priority trailer itself retains its legacy encoding. The secure handshake
|
||||||
|
requires protocol 2; this does not enable communication with protocol-1 peers. BiPack @Extendable is deliberately not added: it would insert a new
|
||||||
|
field-count prefix before existing fields and break old readers.
|
||||||
|
|
||||||
|
## Adapter behavior
|
||||||
|
|
||||||
|
TCP, WebSocket client/server, and UDP use a per-connection priority writer.
|
||||||
|
The writer reads the legacy header lengths and skips payloads to locate priority;
|
||||||
|
it does not deserialize/copy/decrypt the payload or guess from the last four bytes.
|
||||||
|
`Transport.Device.send(block)` defaults to the existing output channel for custom
|
||||||
|
or legacy devices. Built-in ProxyDevice-based adapters override it to enter their
|
||||||
|
writer directly. The old output channel remains available, bridged into that writer;
|
||||||
|
new transports should call send so pending senders are visible to priority ordering.
|
||||||
|
Transport callers now receive nonce-aware scheduling even with a custom FIFO
|
||||||
|
adapter. Direct adapter users retain the adapter-level scheduling behavior.
|
||||||
|
|
||||||
|
Queue admission is bounded to 128 waiting blocks and 32 MiB (plus the block
|
||||||
|
currently being written). Overflow fails explicitly rather than allocating an
|
||||||
|
unbounded backlog. Send awaits its adapter write callback, not a remote RPC reply.
|
||||||
|
Queued cancellation removes the block; cancellation cannot recall a write already
|
||||||
|
started. Closing the writer releases pending senders. There is no rate limiter or
|
||||||
|
batch-collection delay. WebSocket writes flush after each block to avoid excessive
|
||||||
|
look-ahead in the engine's FIFO. Socket/TLS buffers and network loss can still delay
|
||||||
|
control behind bytes already submitted; priority is not a preemption guarantee.
|
||||||
|
|
||||||
|
## Nonce-aware admission and fairness
|
||||||
|
|
||||||
|
`OutQueue.push(message, nonce, priority)` records scheduling metadata locally; no
|
||||||
|
new wire fields are added. `pop()` finds the smallest queued nonce and selects the
|
||||||
|
highest-priority message no more than 2730 positions ahead of it. This is two
|
||||||
|
thirds of the 4096-position receive replay window. Gaps count as nonce distance,
|
||||||
|
not as transmitted packets. The bound prevents an old encrypted message from
|
||||||
|
being starved until it becomes stale. It leaves headroom for external reordering,
|
||||||
|
but does not promise acceptance after arbitrary network delay or reordering.
|
||||||
|
|
||||||
|
A transport's preparation mutex covers nonce allocation, encryption, final block
|
||||||
|
encoding and queue admission. Encryption remains in the secure-layer callbacks.
|
||||||
|
All encrypted paths (identity/finished, calls, pushes and replies) use this path.
|
||||||
|
The mutex is released before waiting for transmission. Full queues reject
|
||||||
|
admission immediately; there is no capacity wait while holding this mutex.
|
||||||
|
Cancellation may leave a nonce gap but never reuses a nonce.
|
||||||
|
|
||||||
|
The transport writer serializes carrier submissions, so a downstream adapter
|
||||||
|
cannot reorder these submissions again. Public direct writes to an adapter's
|
||||||
|
output channel bypass this transport contract.
|
||||||
|
|
||||||
|
Large-message preparation is not preemptible by priority. A local JVM probe with
|
||||||
|
concurrent 1 MiB and 1 KiB payloads measured preparation including mutex waiting
|
||||||
|
at medians of about 87 ms for both sizes (maximum about 118 ms). This includes
|
||||||
|
encoding and allocation, not just cipher time; it is a local observation, not a
|
||||||
|
throughput or latency guarantee.
|
||||||
|
|
||||||
|
## Current verification
|
||||||
|
|
||||||
|
Focused tests cover replay-window boundaries and bitmap wraparound, concurrent
|
||||||
|
nonce admission in both directions, duplicate/stale delivery, local send failure
|
||||||
|
recovery, cancellation/capacity/close, and an encrypted 4098-message backlog whose
|
||||||
|
old low-priority message remains acceptable. The saturated encrypted-link test
|
||||||
|
continues to pass. Kotlin JVM tests, JS/Wasm compilation, TypeScript tests and
|
||||||
|
TypeScript-to-JVM interoperability were checked for this change.
|
||||||
|
|
||||||
|
## Earlier priority-release verification
|
||||||
|
|
||||||
|
Focused JVM tests cover signed numeric ordering, stable ties, queued cancellation,
|
||||||
|
bounded admission, close, absent/partial trailers, unchanged legacy bodies, and
|
||||||
|
priority inheritance through encrypted concurrent calls and encrypted errors.
|
||||||
|
An encrypted simulated 16 KiB/s link saturated in both directions maintains control
|
||||||
|
round trips below 400 ms and aggregate utilization above 80% of full-duplex capacity.
|
||||||
|
This simulation does not model kernel/TLS buffering or packet loss.
|
||||||
|
JVM, Android and JS compilation and socket/resource lifecycle tests pass.
|
||||||
|
Caravan also checked call/error/response fixtures with the actual packaged
|
||||||
|
0.7.1-SNAPSHOT binary and the new 0.7.2-SNAPSHOT binary in separate JVM processes.
|
||||||
@@ -1,35 +1,74 @@
|
|||||||
# Kiloparsec
|
# Kiloparsec
|
||||||
|
|
||||||
The new generation of __PARanoid SECurity__ protocol, advanced, faster, more secure. It also allows connecting any "block device" transport to the same local interface. Out if the box it
|
The Kotlin implementation and the native [TypeScript + WASM client](typescript/README.md)
|
||||||
|
are maintained here together. Current source version **0.8.0** uses
|
||||||
|
**protocol 2**, which authenticates RPC correlation metadata inside encrypted
|
||||||
|
packets. Both peers must be upgraded together; protocol 1 peers are rejected with
|
||||||
|
no automatic downgrade. See [the security analysis](typescript/docs/SECURITY.md).
|
||||||
|
|
||||||
|
The new generation of __PARanoid SECurity__ protocol, advanced, faster, more secure. It also allows connecting any "
|
||||||
|
block device" transport to the same local interface. Out if the box it
|
||||||
provides the following transports:
|
provides the following transports:
|
||||||
|
|
||||||
| name | JVM | JS | native |
|
| name | JVM | JS | wasmJS | native |
|
||||||
|----------------|-----|----|--------|
|
|-------------------|:----:|:---:|:-------:|:------:|
|
||||||
| TCP/IP server | * | | |
|
| TCP/IP server | ✓ | | | ✓ |
|
||||||
| TCP/IP client | * | | |
|
| TCP/IP client | ✓ | | | ✓ |
|
||||||
| Websock server | * | | |
|
| UDP server | ✓ | | | ✓ |
|
||||||
| Websock client | * | * | * |
|
| UDP client | ✓ | | | ✓ |
|
||||||
|
| Websockets server | ✓ | | | |
|
||||||
|
| Websockets client | ✓ | ✓ | ✓ | ✓ |
|
||||||
|
|
||||||
At the moment we're working on supporting TCP/IP on most native targets. This feature is planned to rach public beta in August and production in early september 2024.
|
### Note on version compatibility
|
||||||
|
|
||||||
|
Version 0.8.0 introduces an intentional wire break to close the response
|
||||||
|
correlation vulnerability. Earlier 0.3–0.7 versions share the old envelope and
|
||||||
|
must not be assumed compatible with current source. Application command schemas
|
||||||
|
and the Kotlin interface/session programming model remain unchanged.
|
||||||
|
|
||||||
## TCP/IP transport
|
#### ID calculation algorithm is changed since 0.4.1
|
||||||
|
|
||||||
It is the fastest. JVM implementation uses nio2 async sockets and optimizes TCP socket to play
|
Historical note: 0.4.1 changed public/shared key ID derivation. Current deployments
|
||||||
well with blocks (smart NO_DELAY mode). It is multiplatform, nut lacks of async TCP/IP support
|
should target protocol 2; upgrading only to an older 0.4 release does not fix the
|
||||||
on natvic targetm this is where I need help having little time. I'd prefer to use something asyn like UV on native targets.
|
authenticated correlation issue.
|
||||||
|
|
||||||
I know no existing way to implement it in KotlinJS for the modern browsers.
|
### Supported native targets
|
||||||
|
|
||||||
## Websock server
|
- iosArm64, iosX64
|
||||||
|
- macosArm64, macosArm64
|
||||||
|
- linuxArm64, linuxX64
|
||||||
|
|
||||||
While it is much slower than pure TCP, it is still faster than any http-based transport. It uses binary frames based on the Ktor server framework to easily integrate with web services. We recommend using it instead of a classic HTTP API as it beats it in terms of speed and server load even with HTTP/2.
|
### Non-native targets
|
||||||
|
|
||||||
We recommend to create the `KiloInterface<S>` instance and connect it to the websock and tcp servers in real applications to get easy access from anywhere.
|
- JS (browser and Node.js)
|
||||||
|
- JVM (android, macOS, windows, linux, everywhere where JRE is installed)
|
||||||
|
|
||||||
|
## TCP/IP and UDP transports
|
||||||
|
|
||||||
|
These are the fastest based on async socket implementation of a ktor client. They work everywhere but JS target as
|
||||||
|
there are currently no widely adopted sockets for browser JavaScript.
|
||||||
|
|
||||||
|
While UDP is faster than TCP/IP, it is less reliable, especially with commands and return values that serialize to more
|
||||||
|
than 240 bytes approx, and has no retransmission facilities (use TCP!). UDP, though, shines when all you need is
|
||||||
|
to [push](https://code.sergeych.net/docs/kiloparsec/kiloparsec/net.sergeych.kiloparsec/-remote-interface/push.html) with
|
||||||
|
little or no data in it.
|
||||||
|
|
||||||
|
## Websockets server
|
||||||
|
|
||||||
|
While it is much slower than TCP or UDP, it is still faster than any http-based API; it uses binary frames based on
|
||||||
|
the Ktor server framework to easily integrate with web services. We recommend using it instead of a classic HTTP API as
|
||||||
|
it beats it in terms of speed and server load even with HTTP/2.
|
||||||
|
|
||||||
|
We recommend to create the `KiloInterface<S>` instance and connect it to the websockets and tcp servers in real
|
||||||
|
applications to get easy access from anywhere.
|
||||||
|
|
||||||
|
## Websocket client
|
||||||
|
|
||||||
|
It is slower than TCP or UDP, but it works on literally all platforms. See the sample below.
|
||||||
|
|
||||||
# Usage
|
# Usage
|
||||||
|
|
||||||
Th elibrary should be used as maven dependency, not as source.
|
The library should be used as a maven dependency, not as source.
|
||||||
|
|
||||||
## Adding dependency
|
## Adding dependency
|
||||||
|
|
||||||
@@ -50,12 +89,12 @@ It could be, depending on your project structure, something like:
|
|||||||
```kotlin
|
```kotlin
|
||||||
val commonMain by getting {
|
val commonMain by getting {
|
||||||
dependencies {
|
dependencies {
|
||||||
api("net.sergeych:kiloparsec:0.2.3")
|
api("net.sergeych:kiloparsec:0.6.8")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## Create shared interface for your server and the client
|
## Create a shared interface for your server and the client
|
||||||
|
|
||||||
It could be a multiplatform library that exports it or just a shared or copied source file declaring structures
|
It could be a multiplatform library that exports it or just a shared or copied source file declaring structures
|
||||||
and functions available, like:
|
and functions available, like:
|
||||||
@@ -79,7 +118,7 @@ val cmdPushClient by command<String,Unit>()
|
|||||||
## Call it from the client:
|
## Call it from the client:
|
||||||
|
|
||||||
Remember, we need to implement client interface `cmdPushClient` in our example, so we need to provide
|
Remember, we need to implement client interface `cmdPushClient` in our example, so we need to provide
|
||||||
local interace too:
|
local interface too:
|
||||||
|
|
||||||
```kotlin
|
```kotlin
|
||||||
// Unit: no session on the client:
|
// Unit: no session on the client:
|
||||||
@@ -106,10 +145,11 @@ assertEquals(FooArgs("bar", 117), client.call(cmdGetFoo))
|
|||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Create ktor-based server
|
## Create a ktor-based server
|
||||||
|
|
||||||
Normally server side needs some session. It is convenient and avoid sending repeating data on each request speeding up
|
Normally the server side needs some session. It is convenient and avoids sending repeating data on each request speeding
|
||||||
the protocol. With KILOPARSEC it is rather basic operation:\
|
up
|
||||||
|
the protocol. With KILOPARSEC, it is a rather basic operation:
|
||||||
|
|
||||||
~~~kotlin
|
~~~kotlin
|
||||||
// Our session just keeps Foo for cmd{Get|Set}Foo:
|
// Our session just keeps Foo for cmd{Get|Set}Foo:
|
||||||
@@ -134,38 +174,189 @@ val ns: NettyApplicationEngine = embeddedServer(Netty, port = 8080, host = "0.0.
|
|||||||
setupWebsocketServer(serverInterface) { Session() }
|
setupWebsocketServer(serverInterface) { Session() }
|
||||||
}).start(wait = false)
|
}).start(wait = false)
|
||||||
|
|
||||||
|
|
||||||
~~~
|
~~~
|
||||||
|
|
||||||
|
## Create a TCP / IP client and server
|
||||||
|
|
||||||
|
Using plain TCP/IP is even simpler, and it works way faster than websocket one, and is _the same
|
||||||
|
protected as `wss://` (and `ws://`) the variant above due to same kiloparsec encryption in both cases. Still, a TCP/IP
|
||||||
|
client is not available in JavaScript browser targets, and custom TCP ports could often be blocked by firewalls.
|
||||||
|
|
||||||
|
Documentation is available in samples here:
|
||||||
|
|
||||||
|
- [TCP/IP server creation](https://code.sergeych.net/docs/kiloparsec/kiloparsec/net.sergeych.kiloparsec/-kilo-server/index.html)
|
||||||
|
|
||||||
|
- [TCP/IP client](https://code.sergeych.net/docs/kiloparsec/kiloparsec/net.sergeych.kiloparsec/-kilo-client/index.html)
|
||||||
|
|
||||||
|
In short, there are two functions that implement asynchronous TCP/IP transport on all platforms buy JS:
|
||||||
|
|
||||||
|
- [acceptTcpDevice](https://code.sergeych.net/docs/kiloparsec/kiloparsec/net.sergeych.kiloparsec.adapter/accept-tcp-device.html?query=fun%20acceptTcpDevice(port:%20Int):%20Flow%3CInetTransportDevice%3E)
|
||||||
|
to create a server
|
||||||
|
|
||||||
|
- [connectTcpDevice](https://code.sergeych.net/docs/kiloparsec/kiloparsec/net.sergeych.kiloparsec.adapter/connect-tcp-device.html)
|
||||||
|
to connect to the server
|
||||||
|
|
||||||
|
## UDP client and server
|
||||||
|
|
||||||
|
Is very much straightforward, same as with TCP/IP:
|
||||||
|
|
||||||
|
- [UDP server creation](https://code.sergeych.net/docs/kiloparsec/kiloparsec/net.sergeych.kiloparsec.adapter/accept-udp-device.html)
|
||||||
|
- [Connect UDP client](https://code.sergeych.net/docs/kiloparsec/kiloparsec/net.sergeych.kiloparsec.adapter/connect-udp-device.html)
|
||||||
|
|
||||||
|
### UDP specifics
|
||||||
|
|
||||||
|
#### Command size
|
||||||
|
|
||||||
|
Each command invocation and result are packed in a separate UDP diagram using effective binary packing.
|
||||||
|
Thus, for the best results commands and results should be relatively short, best to fit into 240 bytes. While bigger
|
||||||
|
datagrams are often transmitted successfully, the probability of the effective transmission drops with the size.
|
||||||
|
|
||||||
|
Kiloparsec UDP transport does not retransmit not delivered packets. Use TCP/IP or websocket if it is a concern.
|
||||||
|
|
||||||
|
For the best results, we recommend
|
||||||
|
using [push](https://code.sergeych.net/docs/kiloparsec/kiloparsec/net.sergeych.kiloparsec/-remote-interface/index.html#1558240250%2FFunctions%2F788909594)
|
||||||
|
for remote interfaces with UDP.
|
||||||
|
|
||||||
|
#### Timeouts
|
||||||
|
|
||||||
|
As Datagrams do not form protocol itself, kiloparsec issues pings when no data is circulated between parties.
|
||||||
|
When no pings are received long enough, the kiloparsec connection is closed. There are `maxInactivityTimeout` in all
|
||||||
|
relevant functions and constructors.
|
||||||
|
|
||||||
|
Client should not issue pings manually.
|
||||||
|
|
||||||
|
## Reusing code between servers
|
||||||
|
|
||||||
|
The same instance of
|
||||||
|
the [KiloInterface](https://code.sergeych.net/docs/kiloparsec/kiloparsec/net.sergeych.kiloparsec/-kilo-interface/index.html?query=open%20class%20KiloInterface%3CS%3E%20:%20LocalInterface%3CKiloScope%3CS%3E%3E)
|
||||||
|
could easily be reused with all instances of servers with different protocols.
|
||||||
|
|
||||||
|
This is a common practice to create a business logic in a `KiloInterface`, then create a TCP/IP and Websocket servers
|
||||||
|
passing the same instance of the logic to both.
|
||||||
|
|
||||||
|
## Note on the server identification
|
||||||
|
|
||||||
|
We do not recommend relying on TLS (HTTPS://, WSS://) host identification solely; in the modern world there is
|
||||||
|
a high probability of attacks on unfriendly (in respect to at least some of your users) states to the SSL certificates
|
||||||
|
chain, in which case the [MITM attack] and spoofing will be undetected. Check
|
||||||
|
the [remoteId](https://code.sergeych.net/docs/kiloparsec/kiloparsec/net.sergeych.kiloparsec/-kilo-client/remote-id.html?query=suspend%20fun%20remoteId():%20VerifyingPublicKey?)
|
||||||
|
in your client on each connection and provide the
|
||||||
|
safe [serverSecretKey](https://code.sergeych.net/docs/kiloparsec/kiloparsec/net.sergeych.kiloparsec/-kilo-server/index.html)
|
||||||
|
when creating a server.
|
||||||
|
|
||||||
|
This will effectively protect against certificate chain spoofing in the case of the application installed from the
|
||||||
|
trusted source.
|
||||||
|
|
||||||
|
__Important note__. The web application could not be completely secured this way unless is loaded from the IP-address,
|
||||||
|
as the DNS could be spoofed the same, especially when used with `Cloudflare` or other CDN that can transparently
|
||||||
|
substitute the whole site. For applications, we strongly recommend not using CDN except your own, controlled ones. You
|
||||||
|
generally can't neither detect nor repel [MITM attack] performed from _any single cloudflare 'ray'_.
|
||||||
|
|
||||||
|
## See also:
|
||||||
|
|
||||||
|
- [Source documentation](https://code.sergeych.net/docs/kiloparsec/)
|
||||||
|
- [Project's WIKI](https://gitea.sergeych.net/SergeychWorks/kiloparsec/wiki)
|
||||||
|
|
||||||
# Details
|
# Details
|
||||||
|
|
||||||
It is not compatible with parsec family and no more based on an Universa crypto library. To better fit
|
It is not compatible with Parsec family and no more based on the Universa crypto library. To better fit
|
||||||
the modern state of threats and rate of cyber crimes, KiloParsec uses more encryption and random key exchange on each
|
the modern state of threats and rate of cyber crimes, KiloParsec uses more encryption and random key exchange on each
|
||||||
and every connection (while parsec caches session keys to avoid time-consuming keys exchange). For the same reason,
|
and every connection (while parsec caches session keys to avoid time-consuming keys exchange). For the same reason,
|
||||||
keys cryptography for session is shifted to use ed25519 curves which are supposed to provide agreeable strength with
|
keys cryptography for session is shifted to use ed25519 curves, which are supposed to provide agreeable strength with
|
||||||
enough speed to protect every connection with a unique new keys. Also, we completely get rid of SHA2.
|
enough speed to protect every connection with unique new keys. Also, we completely get rid of SHA2.
|
||||||
|
|
||||||
Kiloparsec also uses a denser binary format [bipack](https://gitea.sergeych.net/SergeychWorks/mp_bintools), no more key-values,
|
Kiloparsec also uses a denser binary format [bipack](https://gitea.sergeych.net/SergeychWorks/mp_bintools), no more
|
||||||
|
key-values,
|
||||||
which reveals much less on the inner data structure, providing advanced
|
which reveals much less on the inner data structure, providing advanced
|
||||||
typed RPC interfaces with kotlinx.serialization. There is also Rust implementation [bipack_ru](https://gitea.sergeych.net/DiWAN/bipack_ru).
|
typed RPC interfaces with kotlinx.serialization. There is also Rust
|
||||||
The architecture allows connecting same functional interfaces to several various type channels at once.
|
implementation [bipack_ru](https://gitea.sergeych.net/DiWAN/bipack_ru).
|
||||||
|
The architecture allows connecting the same functional interfaces to several various type channels at once.
|
||||||
|
|
||||||
Also, the difference from parsecs is that there are no more unencrypted layer commands available to users.
|
Also, the difference from parsecs is that there are no more unencrypted layer commands available to users.
|
||||||
All RPC is performed over the encrypted connection.
|
All RPC is performed over the encrypted connection.
|
||||||
|
|
||||||
# Technical description
|
# Technical description
|
||||||
|
|
||||||
Kiloparsec is a dull-duplex fully async (coroutine based) Remote Procedure Call protocol with typed parameters
|
Kiloparsec is a full-duplex fully async (coroutine-based) Remote Procedure Call protocol with typed parameters
|
||||||
and support for serializing exceptions (e.g. exception thrown while executing remote command will be caught and
|
and support for serializing exceptions (e.g. exception thrown while executing remote command will be caught and
|
||||||
rethrown at the caller context).
|
rethrown at the caller context).
|
||||||
|
|
||||||
Kiloparsec is not REST, it _has advanced session mechanisms_ and built-in authentication based on the same curve keys.
|
Kiloparsec is not REST, it _has advanced session mechanisms_ and built-in authentication based on the same curve keys.
|
||||||
Integrated tools to prevent MITM attacks include also non-transferred independently generated token that is calculated
|
Integrated tools to prevent MITM attacks include also non-transferred independently generated token that is calculated
|
||||||
independently on the ends and is never transferred with the network. Comparing it somehow (visually, with QR code, etc)
|
independently on the ends and is never transferred with the network. Comparing it somehow (visually, with QR code, etc.)
|
||||||
could add a very robust guarantee of the connection safety and ingenuity.
|
could add a very robust guarantee of the connection safety and ingenuity.
|
||||||
|
|
||||||
Kiloparsec has built-in completely asynchronous (coroutine based top-down) transport layer based on TCP (JVM only as for now) and the same async Websocket-based transport based on KTOR. Websocket client is multiplatform, though the server is JVM only insofar.
|
Kiloparsec has a built-in completely asynchronous (coroutine-based top-down) transport layer based on TCP (JVM only as
|
||||||
|
for
|
||||||
|
now) and the same async Websocket-based transport based on KTOR. Websocket client is multiplatform, though the server is
|
||||||
|
JVM only insofar.
|
||||||
|
|
||||||
# Licensing
|
# Licensing
|
||||||
|
|
||||||
When the project reaches some stable state, it will be available under Apache or MIT license. I promise ;) I do
|
This is a work in progress, not yet moved to the public domain;
|
||||||
write opensource ;)
|
you need to obtain a license from https://8-rays.dev or [Sergey Chernov]. For open source projects it will most be free
|
||||||
|
on some special terms.
|
||||||
|
|
||||||
|
It will be moved to open source; we also guarantee that it will be moved to open source immediately if the software
|
||||||
|
export restrictions are lifted. We do not support such practices here at 8-rays.dev.
|
||||||
|
|
||||||
|
[MITM]: https://en.wikipedia.org/wiki/Man-in-the-middle_attack
|
||||||
|
|
||||||
|
[Sergey Chernov]: https://t.me/real_sergeych
|
||||||
|
[^1]: On some new Xiaomi phones we found problems with websocket binary frames, probably in ktor; use text frames
|
||||||
|
otherwise.
|
||||||
|
|
||||||
|
## Numeric transport priority (0.7.2-SNAPSHOT)
|
||||||
|
|
||||||
|
`call(command, args, priority = 100)` and `push(command, args, priority = 0)`
|
||||||
|
select numeric outgoing priority. Responses inherit request priority, calls remain
|
||||||
|
concurrent, and the framed wire extension interoperates with legacy peers.
|
||||||
|
See [priority API, compatibility and limits](PRIORITY.md).
|
||||||
|
|
||||||
|
|
||||||
|
## Connection health and WebSocket keepalive (0.7.2-SNAPSHOT)
|
||||||
|
|
||||||
|
Encrypted application heartbeat is opt-in: `KiloClientConnection.run()` does not
|
||||||
|
start it. Pass `ConnectionHealth` explicitly only when periodic probes are needed.
|
||||||
|
`ReconnectionOptions` configures connection deadlines, retry delay, and an optional
|
||||||
|
finite attempt budget; `reconnectExhausted` signals when that budget ends.
|
||||||
|
|
||||||
|
The server WebSocket helper retains its existing defaults and signature. Its new
|
||||||
|
configuration overload permits applications to disable the transport pinger:
|
||||||
|
|
||||||
|
```kotlin
|
||||||
|
setupWebsocketServer(api, path = "/rpc", serverKey = key,
|
||||||
|
configureWebSockets = { pingPeriodMillis = 0 }) { Session() }
|
||||||
|
```
|
||||||
|
|
||||||
|
Without heartbeat, applications must handle transport closure and bound real
|
||||||
|
request response times. A successful socket write does not prove peer reachability.
|
||||||
|
Proxy/NAT inactivity timeouts remain independent of these settings.
|
||||||
|
|
||||||
|
## Publishing
|
||||||
|
|
||||||
|
`./gradlew publishAllPublicationsToMavenRepository` publishes the configured
|
||||||
|
version to the private Gitea Maven registry using the existing local credential
|
||||||
|
file. Never commit that credential. This project can compile and publish its Apple
|
||||||
|
KLIB variants from Linux; final Apple application linking and runtime qualification
|
||||||
|
still require the appropriate Apple toolchain and devices. Check publication
|
||||||
|
output and the registry rather than assuming a target was skipped.
|
||||||
|
|
||||||
|
`bin/pubdocs` generates Dokka and uploads it to the existing Kiloparsec documentation
|
||||||
|
site. For development-only Maven Local publication without configuring the remote
|
||||||
|
repository, pass `-PlocalPublishingOnly=true`.
|
||||||
|
|
||||||
|
## Verify Kotlin and TypeScript together
|
||||||
|
|
||||||
|
Requires JDK 21, Node.js 22+, and the Android SDK configuration used by this
|
||||||
|
multiplatform build. Install the module's pinned npm dependencies once:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
npm ci --prefix typescript --ignore-scripts
|
||||||
|
bin/test-all.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
The script runs JVM and Kotlin/JS Node tests, TypeScript unit tests, then cross-language tests against
|
||||||
|
a disposable localhost JVM server built from this checkout. It does not publish
|
||||||
|
or contact deployment hosts. Additional Gradle options can be passed to the script.
|
||||||
|
For TypeScript-only commands and examples, see [the module README](typescript/README.md).
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
# Kiloparsec 0.8.0
|
||||||
|
|
||||||
|
Stable release of authenticated protocol 2 and the TypeScript/WASM client source.
|
||||||
|
|
||||||
|
- Authenticate RPC kind, correlation and priority; confirm accepted client identity with an encrypted server-finished response.
|
||||||
|
- Discard duplicate and stale authenticated packets without closing healthy sessions or consuming pending response waiters.
|
||||||
|
- Bound priority overtaking with the nonce-aware outgoing queue. Serialize encryption and queue admission, retaining progress for older low-priority messages.
|
||||||
|
- Preserve sessions after local send failures and use a bounded bitmap for replay tracking.
|
||||||
|
- Honor application initialization rejection on both peers, including subclasses of security and connection-break exceptions.
|
||||||
|
|
||||||
|
Protocol 2 requires coordinated peer upgrades from protocol 1. The fixes preserve the protocol-2 wire encoding. The TypeScript client retains synchronous FIFO WebSocket sending; its private npm package is distributed as source in this release.
|
||||||
|
|
||||||
|
Validation: 64 JVM tests, 47 Kotlin/JS Node tests, 38 TypeScript unit tests and live TypeScript/JVM interoperability passed. Real loopback TCP/UDP tests cover bidirectional calls and UDP duplication/reordering. All 13 Maven publications built; a separate consumer using staged release artifacts passed interoperability without source substitution. Browser, Android and Apple runtimes were not qualified in this release run.
|
||||||
|
|
||||||
|
See [the review](REVIEW-237d404.md) for issue resolutions and validation limits, and [priority semantics](PRIORITY.md) for scheduling guarantees.
|
||||||
@@ -0,0 +1,207 @@
|
|||||||
|
# Review of authenticated protocol 2
|
||||||
|
|
||||||
|
Reviewed commit: `237d404bcd4d52e015b5e0d7cd4feaec4bd848ff` — Add authenticated protocol 2 and TypeScript WASM client.
|
||||||
|
|
||||||
|
Review date: 2026-10-21. Baseline: parent commit `88ceeb2`.
|
||||||
|
|
||||||
|
This document records findings for separate discussion and repair. Issue numbers are stable. Implementation changes and their validation are recorded under closed issues. Proposed remedies for open issues are discussion options, not an agreed redesign.
|
||||||
|
|
||||||
|
## Assessment
|
||||||
|
|
||||||
|
The reviewed commit fixed real authentication gaps, particularly unprotected RPC response correlation, but introduced availability regressions. The findings below preserve the original analysis. I1–I5 are now fixed for release 0.8.0; I6–I7 were closed as non-defects. No review issues remain open.
|
||||||
|
|
||||||
|
The nonce itself was already present in protocol 1. Receiver-side replay tracking, the fixed window, and counter-exhaustion checks are new. These changes should be evaluated separately from authenticated RPC metadata and the server-finished acknowledgement.
|
||||||
|
|
||||||
|
## Reason for the original change
|
||||||
|
|
||||||
|
The committed assessment says the TypeScript port exposed two protocol-1 weaknesses. Inspection of the parent code supports both mechanisms:
|
||||||
|
|
||||||
|
1. Encrypted results had inner `forId = 0`; their actual request correlation was only in the plaintext outer transport ID. An intermediary could swap two outer IDs and associate authentic answers with the wrong concurrent calls when result codecs were compatible. Protocol 2 authenticates kind, correlation and priority inside encryption.
|
||||||
|
2. `L0ClientId` returned plaintext `Unit`. An intermediary could forge that completion without the server accepting the identity message. Protocol 2 returns an encrypted server-finished record echoing the exact accepted identity bytes.
|
||||||
|
|
||||||
|
Other changes include separate client/server signature domains, fresh server exchange keys per connection, repeated-handshake rejection, nonce-state preservation during identity completion, and counter-exhaustion checks. These are distinct design decisions and need not be discussed as one indivisible feature.
|
||||||
|
|
||||||
|
## What server-finished means
|
||||||
|
|
||||||
|
It is the response to the existing `L0ClientId` RPC, not an additional network round trip or an acknowledgement of every UDP packet.
|
||||||
|
|
||||||
|
Previously: client sends encrypted identity; server replies with plaintext Unit. Now: client sends encrypted identity; server replies with encrypted `ProtectedMessage(SERVER_FINISHED, 0, 0, identityBytes)`.
|
||||||
|
|
||||||
|
The client decrypts it and checks the kind, zero correlation/priority, and exact identity payload. With an honest authenticated server, this establishes that the session-key holder processed and accepted that identity message before the client announces connection completion. It does not establish application authorization, authenticate an otherwise untrusted server key, or acknowledge subsequent RPC execution.
|
||||||
|
|
||||||
|
The server completes its local established state before sending this response. Losing the response can therefore leave the server established while the client is still waiting. This is an acknowledgement, not an atomic agreement or a delivery-recovery mechanism.
|
||||||
|
|
||||||
|
## Existing nonces versus new replay checks
|
||||||
|
|
||||||
|
Protocol 1 already contained `Package(nonce: ULong, encryptedMessage)`, `private var nonce = 0UL`, and `val n = protectedOp.invoke { nonce++ }`. It derived the cipher nonce from the session token and that counter. Each sending direction has its own encryption key/counter context.
|
||||||
|
|
||||||
|
The encryption nonce selects a unique encryption instance under a key. It is not secret, is not the RPC ID, and does not require packets to arrive in order. Reusing a nonce for distinct plaintexts under the same key is unsafe. Retransmitting an already-produced ciphertext is a different question from encrypting new plaintext with a reused nonce.
|
||||||
|
|
||||||
|
Protocol 1 decrypted using the counter supplied with each packet, without remembering which counters it had already seen. Consequently, a captured valid encrypted call could be replayed and reach application execution again.
|
||||||
|
|
||||||
|
Protocol 2 adds receiver memory: highest authenticated nonce plus the set of seen nonces in a 4,096-position window. This recognizes repeats and bounds memory, at the cost of rejecting sufficiently old unseen packets. Only successfully authenticated packets advance the window; a forged large counter cannot move it forward.
|
||||||
|
|
||||||
|
The tasks are distinct: nonce uniqueness protects encryption; replay tracking prevents repeated acceptance; authenticated RPC correlation binds an answer to its request. Neither correlation nor server-finished intrinsically requires this particular replay-window size or session-closing policy.
|
||||||
|
|
||||||
|
## Repair validation (2026-10-21)
|
||||||
|
|
||||||
|
- 42 focused JVM tests passed, including existing security, priority and transport tests and the new replay/queue/admission regressions.
|
||||||
|
- TypeScript: 38 passed; the normally skipped interop fixture was run separately and passed against this checkout's JVM server.
|
||||||
|
- Release validation: all 64 JVM and 47 Kotlin/JS Node tests passed. Real loopback UDP exercised reordered and duplicated packets and concurrent bidirectional RPCs; real TCP exercised concurrent bidirectional RPCs and priority. The new carrier test cancels its collector before closing the listener.
|
||||||
|
- All 13 Maven publications and Dokka built successfully. A standalone consumer resolved staged 0.8.0 artifacts without source substitution and passed the TypeScript interoperability suite (authentication, duplex, pushes, errors, concurrent calls and reconnect).
|
||||||
|
- Kotlin Wasm compilation passed. Browser, Android and Apple runtime qualification was not performed. Apple KLIB publication does not qualify final Apple application linking or runtime.
|
||||||
|
- Protocol-2 wire encoding remains unchanged; older protocol-2 peers still retain their own previous replay-disconnect behavior until upgraded.
|
||||||
|
- The encrypted backlog test validates all 4098 messages, including an old low-priority message, decrypt successfully after scheduling. Concurrent real JVM preparation exercises both directions and calls, replies, pushes and handshake messages.
|
||||||
|
- A temporary preparation benchmark (source retained at `/tmp/PreparationBenchmarkTest.kt`) ran concurrent 1 MiB and 1 KiB payloads under the preparation mutex. Measured medians including lock waiting were 86.86 ms and 86.60 ms, with maxima 117.40 ms and 117.65 ms. This is a local JVM observation including serialization and allocation; large-message preparation can delay small messages before queue scheduling. The benchmark source was removed from the checkout.
|
||||||
|
- Historical probe/test counts below describe the original review, not the final repair run.
|
||||||
|
|
||||||
|
## Original review validation and limits
|
||||||
|
|
||||||
|
- 14 focused JVM tests passed: 7 existing authenticated-envelope tests, 3 security-boundary tests, and 4 temporary review probes.
|
||||||
|
- The review probes checked replay-window boundaries, adjacent reordering survival, deep reordering session closure, and local send failure session closure.
|
||||||
|
- Follow-up I5 check: 3 additional focused JVM probes passed, reproducing ignored client/server initialization rejection and confirming rejection through the application `execute` gate. Probe source saved at `/tmp/ReviewI5Test.kt` and removed from the checkout.
|
||||||
|
- TypeScript tests: 35 passed, 1 interoperability test skipped.
|
||||||
|
- No live UDP impairment, browser qualification, full cryptographic audit, or sustained-load benchmark was performed.
|
||||||
|
- Temporary probe source was saved at `/tmp/Review237d404Test.kt` and removed from the checkout. This path is ephemeral.
|
||||||
|
- Existing `.idea/misc.xml` changes and untracked `kotlin-js-store/` were left untouched.
|
||||||
|
|
||||||
|
All review issues are closed: I1–I5 are included in release 0.8.0; I6–I7 require no remediation.
|
||||||
|
|
||||||
|
## Closed issues
|
||||||
|
|
||||||
|
### Issue 1 — Duplicate or stale packets terminate the session
|
||||||
|
|
||||||
|
**Resolution (2026-10-21):** Done — duplicate/stale encrypted packets are silently discarded on Kotlin and TypeScript. Incoming calls/pushes are not executed again; response authentication/replay checks run before consuming the pending waiter. A valid later reply can still complete it. Authentication/routing failures remain fatal. No automatic retry was added.
|
||||||
|
|
||||||
|
**Original finding (before repair):**
|
||||||
|
|
||||||
|
**Priority:** High for UDP. **Status:** Confirmed regression; reproduced.
|
||||||
|
|
||||||
|
`KiloParams.decrypt` rejects a previously received nonce, or an unseen nonce at least 4,096 positions behind the highest authenticated nonce. `KiloL0Interface.executeTransportBlock` turns rejection into `SecurityException`, a subclass of `BreakConnectionException`, and the transport closes.
|
||||||
|
|
||||||
|
Observed behavior:
|
||||||
|
|
||||||
|
| Delivery | Result |
|
||||||
|
| --- | --- |
|
||||||
|
| Adjacent packets reversed | Both accepted |
|
||||||
|
| Unseen nonce 4,095 positions behind highest | Accepted |
|
||||||
|
| Unseen nonce 4,096 positions behind highest | Rejected |
|
||||||
|
| Duplicate incoming call or push | Rejected; session closes |
|
||||||
|
|
||||||
|
Duplicate responses are different: the outer transport normally ignores responses whose pending request was already removed. A stale response for a still-pending call reaches authentication and can close the session.
|
||||||
|
|
||||||
|
A controlled test held an encrypted push, delivered 4,096 newer pushes, then delivered the original. The valid original packet caused session closure. An adjacent-reordering test survived. The existing duplicate-call regression also explicitly expects connection termination.
|
||||||
|
|
||||||
|
**Impact:** ordinary datagram duplication or sufficiently deep reordering becomes a session-wide failure, affecting unrelated calls. This is an availability issue, not evidence of broken encryption.
|
||||||
|
|
||||||
|
**Discussion direction:** distinguish duplicate/stale packet disposition from fatal errors; discard without repeating application execution. If reliable delivery is desired, separately specify timeouts, retransmission and response caching. Discarding duplicates alone does not implement reliable RPC.
|
||||||
|
|
||||||
|
References: [KiloParams.kt](src/commonMain/kotlin/net/sergeych/kiloparsec/KiloParams.kt), [KiloL0Interface.kt](src/commonMain/kotlin/net/sergeych/kiloparsec/KiloL0Interface.kt), [Transport.kt](src/commonMain/kotlin/net/sergeych/kiloparsec/Transport.kt), [AuthenticatedEnvelopeTest.kt](src/commonTest/kotlin/AuthenticatedEnvelopeTest.kt).
|
||||||
|
|
||||||
|
### Issue 2 — Priority scheduling can exceed the replay window locally
|
||||||
|
|
||||||
|
**Resolution (2026-10-21):** Done — `OutQueue` enforces the 2730-position allowance; one preparation mutex covers nonce allocation, sealing, encoding and admission. The transport owns the nonce-aware writer and submits serially to the existing adapter, preserving its selected order. Encryption stays in secure-layer callbacks. Full queues reject immediately rather than wait under the mutex.
|
||||||
|
|
||||||
|
**Original finding (before repair):**
|
||||||
|
|
||||||
|
**Priority:** High under sustained priority traffic. **Status:** Code-established interaction; actual scheduler saturation not reproduced.
|
||||||
|
|
||||||
|
Encryption allocates a nonce before `PriorityBlockWriter` selects transmission order. A low-priority encrypted packet can remain queued while newer high-priority packets overtake it. There is no fairness or maximum-overtaking guarantee. The 128-item queue bound limits simultaneous occupancy, not the total number of packets that can overtake one waiting packet.
|
||||||
|
|
||||||
|
If overtaking spans 4,096 nonce positions, eventual delivery triggers issue 1. This can occur even with ordered TCP/WebSocket delivery: the reordering happens before the carrier sends the bytes. Calls, replies and pushes share one nonce sequence per sending direction.
|
||||||
|
|
||||||
|
**Agreed design (2026-10-21):** introduce a specific `OutQueue` with `push(message, nonce, priority)` and `pop()`. Preserve encryption in its existing layer. Pass nonce metadata explicitly to the queue rather than decoding encrypted-package structures in the scheduler.
|
||||||
|
|
||||||
|
For receiver window `W = 4096`, use a local overtaking allowance `B = floor(2 * W / 3) = 2730`:
|
||||||
|
|
||||||
|
```text
|
||||||
|
pop():
|
||||||
|
oldest = minimum queued nonce
|
||||||
|
eligible = messages with nonce - oldest <= B
|
||||||
|
select highest priority among eligible
|
||||||
|
break priority ties by smallest nonce
|
||||||
|
```
|
||||||
|
|
||||||
|
Use subtraction after establishing the minimum to avoid addition overflow. The allowance is based on nonce distance, not the number of successful sends. This accommodates gaps from failed or cancelled messages and prevents starvation by indefinitely newer high-priority traffic.
|
||||||
|
|
||||||
|
One mutex per sending direction covers nonce allocation, encryption/encoding, and queue insertion as one ordered preparation/admission operation. Queue insertion and selection must themselves be synchronized. This prevents an older allocated nonce from remaining outside the queue while newer packets are transmitted. All encrypted message paths sharing that sending key must participate, including calls, replies, pushes, and handshake ciphertexts.
|
||||||
|
|
||||||
|
Wait for transmission completion outside the mutex. Queue-capacity waiting must not prevent the writer from draining the queue; coordinate capacity reservation/admission accordingly. Failed preparation may consume a nonce, which must never be reused. Cancellation and close must release reservations and completion waiters.
|
||||||
|
|
||||||
|
The queue and writer must preserve the selected transmission order. This bounds scheduler-induced reordering while leaving roughly one third of the receiver window for subsequent network/receive-processing reordering. It does not guarantee acceptance after arbitrarily deep external reordering; issue 1 remains a separate fix.
|
||||||
|
|
||||||
|
**Validation targets:** priority selection inside the permitted range; oldest-message progress under sustained higher-priority traffic; exact window boundary; nonce gaps; concurrent preparation/admission; cancellation, capacity and close behavior; and an integration test showing a delayed low-priority encrypted message arrives without becoming stale. Measure preparation-lock contention with large messages rather than assuming encryption cost is negligible.
|
||||||
|
|
||||||
|
**Implementation status:** implemented and verified. A 4098-message encrypted backlog, concurrent duplex admission, queue capacity/cancellation/close and existing saturated-link responsiveness tests pass. Network reordering beyond the receiver window remains discardable, without closing the session.
|
||||||
|
|
||||||
|
References: [KiloParams.kt](src/commonMain/kotlin/net/sergeych/kiloparsec/KiloParams.kt), [PriorityBlockWriter.kt](src/commonMain/kotlin/net/sergeych/kiloparsec/adapter/PriorityBlockWriter.kt).
|
||||||
|
|
||||||
|
### Issue 3 — Local send failures are misclassified as authentication failures
|
||||||
|
|
||||||
|
**Resolution (2026-10-21):** Done — plaintext remote errors are explicitly distinguished at the receive boundary. Local preparation/admission/write failures retain their original errors and do not abort the healthy session. A local reply-send failure is logged without fabricating a plaintext remote error; the caller retains its timeout/cancellation policy.
|
||||||
|
|
||||||
|
**Original finding (before repair):**
|
||||||
|
|
||||||
|
**Priority:** Medium. **Status:** Confirmed regression; reproduced.
|
||||||
|
|
||||||
|
`KiloRemoteInterface.call` catches almost every exception from `transport.callWithId`, closes the transport, and throws `SecurityException("unauthenticated outer error")`. That operation includes local encryption and sending, not only receipt of a plaintext remote error.
|
||||||
|
|
||||||
|
The priority writer throws `RemoteInterface.Exception("Outgoing block queue is full")` on admission failure. Injecting that same local send exception reproduced an authentication error and termination of both peers.
|
||||||
|
|
||||||
|
**Impact:** local congestion closes healthy sessions and unrelated pending calls; diagnostics incorrectly suggest a remote security failure.
|
||||||
|
|
||||||
|
**Discussion direction:** explicitly distinguish plaintext remote errors at the receive boundary from local encoding, admission and send failures.
|
||||||
|
|
||||||
|
References: [KiloRemoteInterface.kt](src/commonMain/kotlin/net/sergeych/kiloparsec/KiloRemoteInterface.kt), [PriorityBlockWriter.kt](src/commonMain/kotlin/net/sergeych/kiloparsec/adapter/PriorityBlockWriter.kt).
|
||||||
|
|
||||||
|
### Issue 4 — Replay tracking adds a full-window scan per advancing packet
|
||||||
|
|
||||||
|
**Resolution (2026-10-21):** Done — Kotlin and TypeScript use 4096-bit circular replay windows. Normal in-order advancement clears one bit, large jumps clear a fixed bitmap, and only successfully authenticated packets update history.
|
||||||
|
|
||||||
|
**Original finding (before repair):**
|
||||||
|
|
||||||
|
**Priority:** Medium performance concern. **Status:** Confirmed algorithmic cost; throughput impact not benchmarked.
|
||||||
|
|
||||||
|
Kotlin uses `received.removeAll` when the high watermark advances; TypeScript scans its received set. In steady in-order traffic with a populated window, this is approximately 4,096 age checks per packet. Kotlin performs this under the lock also used for nonce allocation and decryption.
|
||||||
|
|
||||||
|
**Impact:** bounded memory, but avoidable CPU work and contention for a high-throughput transport.
|
||||||
|
|
||||||
|
**Discussion direction:** if retaining windowed replay protection, use a circular bitmap or another bounded representation with inexpensive advancement.
|
||||||
|
|
||||||
|
References: [KiloParams.kt](src/commonMain/kotlin/net/sergeych/kiloparsec/KiloParams.kt), [client.ts](typescript/src/client.ts). Algorithm background: [RFC 6479](https://www.rfc-editor.org/rfc/rfc6479.html).
|
||||||
|
|
||||||
|
### Issue 5 — Connection-init policy rejection is swallowed
|
||||||
|
|
||||||
|
**Status:** Done on 2026-10-21 — initialization rejection now propagates on both ends.
|
||||||
|
|
||||||
|
**Design decision:** preserve Kotlin's code-based remote-party authorization through the local interface and initialization handlers. Both peers receive verified identity and session data through `KiloScope`. No trusted-key-list constructor parameter is required; the earlier proposal to add one is withdrawn.
|
||||||
|
|
||||||
|
**Original defect:** the shared `invokeAll` helper discarded every handler exception using `runCatching`, including deliberate security/connection rejection. This defect predates commit `237d404`. Follow-up probes reproduced successful connection and application execution despite rejection on either peer.
|
||||||
|
|
||||||
|
**Fix:** replace `runCatching` with explicit `try/catch`. Rethrow `LocalInterface.BreakConnectionException` and all subclasses, including `RemoteInterface.SecurityException`; continue ignoring other handler failures as before. Rejection stops subsequent handlers. The shared helper also propagates this exception family when invoked for disconnect handlers.
|
||||||
|
|
||||||
|
**Validation:** `ConnectionInitializationTest` covers client and server initialization rejection using a custom `SecurityException` subclass and a custom `BreakConnectionException` subclass. Each case verifies that the policy sees the verified remote identity, both connection runs finish, later init handlers do not run, connected state is not announced, and a subsequent client RPC fails as closed. A fifth test verifies that ordinary handler failures still allow initialization and a successful RPC. The four rejection cases failed before the fix and passed after it. All 15 focused JVM tests passed, including `AuthenticatedEnvelopeTest` and `SecurityBoundaryTest`.
|
||||||
|
|
||||||
|
**Scope:** this completes the requested exception-propagation repair. Parameter publication order and initialization-time RPC semantics were not changed; these tests do not establish a general concurrent-dispatch barrier before initialization completes.
|
||||||
|
|
||||||
|
References: [KiloClientConnection.kt](src/commonMain/kotlin/net/sergeych/kiloparsec/KiloClientConnection.kt), [ConnectionInitializationTest.kt](src/commonTest/kotlin/ConnectionInitializationTest.kt).
|
||||||
|
|
||||||
|
### Issue 6 — Protocol 2 requires coordinated peer upgrades
|
||||||
|
|
||||||
|
**Status:** Closed — intentional compatibility decision, not a defect; no remediation required.
|
||||||
|
|
||||||
|
Both peers require protocol 2, with no automatic v1 fallback. The new envelope and identity acknowledgement deliberately break wire compatibility with v1. Coordinated peer upgrades were an agreed design decision, not an outstanding issue.
|
||||||
|
|
||||||
|
The original issue number is retained for reference.
|
||||||
|
|
||||||
|
References: [KiloProtocol.kt](src/commonMain/kotlin/net/sergeych/kiloparsec/KiloProtocol.kt), [SECURITY.md](typescript/docs/SECURITY.md).
|
||||||
|
|
||||||
|
### Issue 7 — Replay protection is not business-operation deduplication
|
||||||
|
|
||||||
|
**Status:** Closed on 2026-10-21 — not a protocol defect; excluded from remediation.
|
||||||
|
|
||||||
|
Kiloparsec protects against replayed encrypted packets and forged or altered protocol messages. A new valid RPC issued by application code, on the same connection or after reconnecting, is a new request. The protocol cannot determine whether repeating that operation is intentional or an application mistake.
|
||||||
|
|
||||||
|
Business-operation deduplication requires application-defined semantics, such as a durable operation identifier and an explicit idempotency contract. It belongs to business logic and should not have been classified as a Kiloparsec issue.
|
||||||
|
|
||||||
|
**Resolution:** no protocol change required. The original issue number is retained for reference.
|
||||||
Executable
+15
@@ -0,0 +1,15 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
#
|
||||||
|
# Copyright (c) 2025. Sergey S. Chernov - All Rights Reserved
|
||||||
|
#
|
||||||
|
# You may use, distribute and modify this code under the
|
||||||
|
# terms of the private license, which you must obtain from the author
|
||||||
|
#
|
||||||
|
# To obtain the license, contact the author: https://t.me/real_sergeych or email to
|
||||||
|
# real dot sergeych at gmail.
|
||||||
|
#
|
||||||
|
|
||||||
|
set -e
|
||||||
|
# Dokka needs more Metaspace than the default Gradle daemon on this KMP project.
|
||||||
|
./gradlew '-Dorg.gradle.jvmargs=-Xmx2g -XX:MaxMetaspaceSize=1g' dokkaGeneratePublicationHtml
|
||||||
|
rsync -avz ./build/dokka/* code.sergeych.net:/bigstore/sergeych_pub/code/docs/kiloparsec
|
||||||
Executable
+6
@@ -0,0 +1,6 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Local-only verification; no publishing or deployment.
|
||||||
|
set -euo pipefail
|
||||||
|
repo_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||||
|
"$repo_dir/gradlew" -p "$repo_dir" jvmTest jsNodeTest typescriptTest "$@"
|
||||||
|
npm --prefix "$repo_dir/typescript" run test:interop
|
||||||
+131
-46
@@ -1,104 +1,159 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2025-2026. Sergey S. Chernov - All Rights Reserved
|
||||||
|
*
|
||||||
|
* You may use, distribute and modify this code under the
|
||||||
|
* terms of the private license, which you must obtain from the author
|
||||||
|
*
|
||||||
|
* To obtain the license, contact the author: https://t.me/real_sergeych or email to
|
||||||
|
* real dot sergeych at gmail.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import org.jetbrains.kotlin.gradle.ExperimentalWasmDsl
|
||||||
|
|
||||||
plugins {
|
plugins {
|
||||||
kotlin("multiplatform") version "2.0.0"
|
kotlin("multiplatform") version "2.2.21"
|
||||||
id("org.jetbrains.kotlin.plugin.serialization") version "2.0.0"
|
id("org.jetbrains.kotlin.plugin.serialization") version "2.2.21"
|
||||||
|
id("com.android.library") version "8.7.2" apply true
|
||||||
`maven-publish`
|
`maven-publish`
|
||||||
|
id("org.jetbrains.dokka") version "2.2.0"
|
||||||
}
|
}
|
||||||
|
|
||||||
group = "net.sergeych"
|
group = "net.sergeych"
|
||||||
version = "0.2.2-SNAPSHOT"
|
version = "0.8.0"
|
||||||
|
|
||||||
repositories {
|
repositories {
|
||||||
|
google()
|
||||||
mavenCentral()
|
mavenCentral()
|
||||||
mavenLocal()
|
mavenLocal()
|
||||||
maven("https://maven.universablockchain.com/")
|
maven("https://maven.universablockchain.com/")
|
||||||
maven("https://gitea.sergeych.net/api/packages/SergeychWorks/maven")
|
maven("https://gitea.sergeych.net/api/packages/SergeychWorks/maven")
|
||||||
|
maven("https://gitea.sergeych.net/api/packages/YoungBlood/maven")
|
||||||
}
|
}
|
||||||
|
|
||||||
kotlin {
|
kotlin {
|
||||||
|
jvmToolchain(21)
|
||||||
jvm()
|
jvm()
|
||||||
js(IR) {
|
js {
|
||||||
browser {
|
browser()
|
||||||
// commonWebpackConfig {
|
nodejs {
|
||||||
// cssSupport {
|
// Replay-window tests deliberately process more than 4096 messages.
|
||||||
// enabled.set(true)
|
testTask { useMocha { timeout = "30s" } }
|
||||||
// }
|
|
||||||
// }
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// val hostOs = System.getProperty("os.name")
|
|
||||||
// val isArm64 = System.getProperty("os.arch") == "aarch64"
|
|
||||||
// val isMingwX64 = hostOs.startsWith("Windows")
|
|
||||||
// @Suppress("UNUSED_VARIABLE")
|
|
||||||
// val nativeTarget = when {
|
|
||||||
// hostOs == "Mac OS X" && isArm64 -> macosArm64("native")
|
|
||||||
// hostOs == "Mac OS X" && !isArm64 -> macosX64("native")
|
|
||||||
// hostOs == "Linux" && isArm64 -> linuxArm64("native")
|
|
||||||
// hostOs == "Linux" && !isArm64 -> linuxX64("native")
|
|
||||||
// isMingwX64 -> mingwX64("native")
|
|
||||||
// else -> throw GradleException("Host OS is not supported in Kotlin/Native.")
|
|
||||||
// }
|
|
||||||
|
|
||||||
// macosArm64()
|
|
||||||
// iosX64()
|
|
||||||
// iosArm64()
|
|
||||||
// iosSimulatorArm64()
|
|
||||||
linuxX64()
|
linuxX64()
|
||||||
linuxArm64()
|
linuxArm64()
|
||||||
// macosX64()
|
|
||||||
|
|
||||||
|
macosArm64()
|
||||||
|
macosX64()
|
||||||
|
iosX64()
|
||||||
|
iosArm64()
|
||||||
|
iosSimulatorArm64()
|
||||||
|
|
||||||
val ktor_version = "2.3.6"
|
mingwX64()
|
||||||
|
|
||||||
|
androidTarget {
|
||||||
|
publishLibraryVariants("release")
|
||||||
|
}
|
||||||
|
@OptIn(ExperimentalWasmDsl::class)
|
||||||
|
wasmJs {
|
||||||
|
browser()
|
||||||
|
}
|
||||||
|
|
||||||
|
val ktor_version = "3.1.1"
|
||||||
|
|
||||||
sourceSets {
|
sourceSets {
|
||||||
all {
|
all {
|
||||||
languageSettings.optIn("kotlinx.serialization.ExperimentalSerializationApi")
|
languageSettings.optIn("kotlinx.serialization.ExperimentalSerializationApi")
|
||||||
languageSettings.optIn("kotlinx.coroutines.ExperimentalCoroutinesApi")
|
languageSettings.optIn("kotlinx.coroutines.ExperimentalCoroutinesApi")
|
||||||
languageSettings.optIn("kotlin.ExperimentalUnsignedTypes")
|
languageSettings.optIn("kotlin.ExperimentalUnsignedTypes")
|
||||||
|
languageSettings.optIn("kotlin.time.ExperimentalTime")
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
val commonMain by getting {
|
val commonMain by getting {
|
||||||
dependencies {
|
dependencies {
|
||||||
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.3")
|
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.2")
|
||||||
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.1")
|
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.9.0")
|
||||||
|
|
||||||
// api("com.ionspin.kotlin:bignum:0.3.9")
|
|
||||||
api("io.ktor:ktor-client-core:$ktor_version")
|
api("io.ktor:ktor-client-core:$ktor_version")
|
||||||
|
api("net.sergeych:crypto2:0.9.0")
|
||||||
// api("net.sergeych:mp_bintools:0.1.1")
|
|
||||||
// api("net.sergeych:mp_stools:1.4.7")
|
|
||||||
api("net.sergeych:crypto2:0.4.1-SNAPSHOT")
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
val androidMain by getting {
|
||||||
|
dependencies {
|
||||||
|
implementation("io.ktor:ktor-client-okhttp:$ktor_version")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val ktorSocketMain by creating {
|
||||||
|
dependsOn(commonMain)
|
||||||
|
dependencies {
|
||||||
|
implementation("io.ktor:ktor-network:$ktor_version")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
androidMain.dependsOn(ktorSocketMain)
|
||||||
val commonTest by getting {
|
val commonTest by getting {
|
||||||
dependencies {
|
dependencies {
|
||||||
implementation(kotlin("test"))
|
implementation(kotlin("test"))
|
||||||
implementation("org.slf4j:slf4j-simple:2.0.9")
|
implementation("org.slf4j:slf4j-simple:2.0.17")
|
||||||
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.7.3")
|
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.10.2")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
val ktorSocketTest by creating {
|
||||||
|
dependsOn(commonTest)
|
||||||
|
}
|
||||||
val jvmMain by getting {
|
val jvmMain by getting {
|
||||||
dependencies {
|
dependencies {
|
||||||
implementation("io.ktor:ktor-server-core:$ktor_version")
|
implementation("io.ktor:ktor-server-core:$ktor_version")
|
||||||
implementation("io.ktor:ktor-server-core-jvm:$ktor_version")
|
implementation("io.ktor:ktor-server-core-jvm:$ktor_version")
|
||||||
implementation("io.ktor:ktor-server-websockets-jvm:$ktor_version")
|
implementation("io.ktor:ktor-server-websockets-jvm:$ktor_version")
|
||||||
|
implementation("io.ktor:ktor-server-websockets:${ktor_version}")
|
||||||
implementation("io.ktor:ktor-server-netty:$ktor_version")
|
implementation("io.ktor:ktor-server-netty:$ktor_version")
|
||||||
api("io.ktor:ktor-client-cio:$ktor_version")
|
api("io.ktor:ktor-client-cio:$ktor_version")
|
||||||
}
|
}
|
||||||
|
dependsOn(ktorSocketMain)
|
||||||
|
}
|
||||||
|
val jvmTest by getting {
|
||||||
|
dependsOn(ktorSocketTest)
|
||||||
}
|
}
|
||||||
val jvmTest by getting
|
|
||||||
val jsMain by getting {
|
val jsMain by getting {
|
||||||
dependencies {
|
dependencies {
|
||||||
implementation("io.ktor:ktor-client-js:$ktor_version")
|
implementation("io.ktor:ktor-client-js:$ktor_version")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
val jsTest by getting
|
val jsTest by getting
|
||||||
// val nativeMain by getting {
|
val macosArm64Main by getting {
|
||||||
// dependencies {
|
dependsOn(ktorSocketMain)
|
||||||
// implementation("io.ktor:ktor-client-cio:$ktor_version")
|
}
|
||||||
// }
|
val macosArm64Test by getting {
|
||||||
// }
|
dependsOn(ktorSocketTest)
|
||||||
// val nativeTest by getting
|
}
|
||||||
|
val macosX64Main by getting {
|
||||||
|
dependsOn(ktorSocketMain)
|
||||||
|
}
|
||||||
|
val iosX64Main by getting {
|
||||||
|
dependsOn(ktorSocketMain)
|
||||||
|
}
|
||||||
|
val iosX64Test by getting {
|
||||||
|
dependsOn(ktorSocketTest)
|
||||||
|
}
|
||||||
|
val iosArm64Main by getting {
|
||||||
|
dependsOn(ktorSocketMain)
|
||||||
|
}
|
||||||
|
val iosArm64Test by getting {
|
||||||
|
dependsOn(ktorSocketTest)
|
||||||
|
}
|
||||||
|
val linuxArm64Main by getting {
|
||||||
|
dependsOn(ktorSocketMain)
|
||||||
|
}
|
||||||
|
val linuxArm64Test by getting {
|
||||||
|
dependsOn(ktorSocketTest)
|
||||||
|
}
|
||||||
|
val linuxX64Main by getting {
|
||||||
|
dependsOn(ktorSocketMain)
|
||||||
|
}
|
||||||
|
val linuxX64Test by getting {
|
||||||
|
dependsOn(ktorSocketTest)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
publishing {
|
publishing {
|
||||||
@@ -106,6 +161,7 @@ kotlin {
|
|||||||
File("${System.getProperty("user.home")}/.gitea_token").readText()
|
File("${System.getProperty("user.home")}/.gitea_token").readText()
|
||||||
}
|
}
|
||||||
repositories {
|
repositories {
|
||||||
|
if (!providers.gradleProperty("localPublishingOnly").map(String::toBoolean).getOrElse(false)) {
|
||||||
maven {
|
maven {
|
||||||
credentials(HttpHeaderCredentials::class) {
|
credentials(HttpHeaderCredentials::class) {
|
||||||
name = "Authorization"
|
name = "Authorization"
|
||||||
@@ -119,3 +175,32 @@ kotlin {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
dokka {
|
||||||
|
dokkaPublications.html {
|
||||||
|
outputDirectory.set(layout.buildDirectory.dir("dokka"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
android {
|
||||||
|
namespace = "net.sergeych.kiloparsec"
|
||||||
|
compileSdk = 34
|
||||||
|
defaultConfig {
|
||||||
|
minSdk = 24
|
||||||
|
}
|
||||||
|
compileOptions {
|
||||||
|
sourceCompatibility = JavaVersion.VERSION_17
|
||||||
|
targetCompatibility = JavaVersion.VERSION_17
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// This task stays local: the interoperability build is run sequentially by
|
||||||
|
// bin/test-all.sh, avoiding a nested Gradle build of the same checkout.
|
||||||
|
tasks.register<Exec>("typescriptTest") {
|
||||||
|
group = "verification"
|
||||||
|
description = "Build and test the TypeScript/WASM client (run npm ci first)."
|
||||||
|
workingDir(layout.projectDirectory.dir("typescript"))
|
||||||
|
commandLine("npm", "test")
|
||||||
|
}
|
||||||
@@ -1 +1,20 @@
|
|||||||
|
#
|
||||||
|
# Copyright (c) 2025. Sergey S. Chernov - All Rights Reserved
|
||||||
|
#
|
||||||
|
# You may use, distribute and modify this code under the
|
||||||
|
# terms of the private license, which you must obtain from the author
|
||||||
|
#
|
||||||
|
# To obtain the license, contact the author: https://t.me/real_sergeych or email to
|
||||||
|
# real dot sergeych at gmail.
|
||||||
|
#
|
||||||
|
|
||||||
kotlin.code.style=official
|
kotlin.code.style=official
|
||||||
|
kotlin.mpp.applyDefaultHierarchyTemplate=false
|
||||||
|
|
||||||
|
kotlin.daemon.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
|
||||||
|
kotlin.native.ignoreDisabledTargets=true
|
||||||
|
|
||||||
|
org.gradle.parallel=true
|
||||||
|
org.gradle.configuration-cache=true
|
||||||
|
org.gradle.caching=true
|
||||||
|
|
||||||
+11
-1
@@ -1,5 +1,15 @@
|
|||||||
|
#
|
||||||
|
# Copyright (c) 2025. Sergey S. Chernov - All Rights Reserved
|
||||||
|
#
|
||||||
|
# You may use, distribute and modify this code under the
|
||||||
|
# terms of the private license, which you must obtain from the author
|
||||||
|
#
|
||||||
|
# To obtain the license, contact the author: https://t.me/real_sergeych or email to
|
||||||
|
# real dot sergeych at gmail.
|
||||||
|
#
|
||||||
|
|
||||||
distributionBase=GRADLE_USER_HOME
|
distributionBase=GRADLE_USER_HOME
|
||||||
distributionPath=wrapper/dists
|
distributionPath=wrapper/dists
|
||||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.2-bin.zip
|
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
|
||||||
zipStoreBase=GRADLE_USER_HOME
|
zipStoreBase=GRADLE_USER_HOME
|
||||||
zipStorePath=wrapper/dists
|
zipStorePath=wrapper/dists
|
||||||
@@ -1,19 +1,13 @@
|
|||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
|
|
||||||
#
|
#
|
||||||
# Copyright © 2015-2021 the original authors.
|
# Copyright (c) 2025. Sergey S. Chernov - All Rights Reserved
|
||||||
#
|
#
|
||||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
# You may use, distribute and modify this code under the
|
||||||
# you may not use this file except in compliance with the License.
|
# terms of the private license, which you must obtain from the author
|
||||||
# You may obtain a copy of the License at
|
|
||||||
#
|
#
|
||||||
# https://www.apache.org/licenses/LICENSE-2.0
|
# To obtain the license, contact the author: https://t.me/real_sergeych or email to
|
||||||
#
|
# real dot sergeych at gmail.
|
||||||
# Unless required by applicable law or agreed to in writing, software
|
|
||||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
# See the License for the specific language governing permissions and
|
|
||||||
# limitations under the License.
|
|
||||||
#
|
#
|
||||||
|
|
||||||
##############################################################################
|
##############################################################################
|
||||||
|
|||||||
@@ -1,5 +1,16 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2025. Sergey S. Chernov - All Rights Reserved
|
||||||
|
*
|
||||||
|
* You may use, distribute and modify this code under the
|
||||||
|
* terms of the private license, which you must obtain from the author
|
||||||
|
*
|
||||||
|
* To obtain the license, contact the author: https://t.me/real_sergeych or email to
|
||||||
|
* real dot sergeych at gmail.
|
||||||
|
*/
|
||||||
|
|
||||||
pluginManagement {
|
pluginManagement {
|
||||||
repositories {
|
repositories {
|
||||||
|
google()
|
||||||
mavenCentral()
|
mavenCentral()
|
||||||
gradlePluginPortal()
|
gradlePluginPortal()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2025. Sergey S. Chernov - All Rights Reserved
|
||||||
|
*
|
||||||
|
* You may use, distribute and modify this code under the
|
||||||
|
* terms of the private license, which you must obtain from the author
|
||||||
|
*
|
||||||
|
* To obtain the license, contact the author: https://t.me/real_sergeych or email to
|
||||||
|
* real dot sergeych at gmail.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package net.sergeych.kiloparsec
|
||||||
|
|
||||||
|
import io.ktor.utils.io.*
|
||||||
|
|
||||||
|
object AsyncVarint {
|
||||||
|
suspend fun encodeUnsigned(value: ULong, output: ByteWriteChannel) {
|
||||||
|
var rest = value
|
||||||
|
do {
|
||||||
|
val x = (rest and 127u).toInt()
|
||||||
|
rest = rest shr 7
|
||||||
|
if (rest > 0u)
|
||||||
|
output.writeByte(x or 0x80)
|
||||||
|
else
|
||||||
|
output.writeByte(x)
|
||||||
|
|
||||||
|
} while (rest > 0u)
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun decodeUnsigned(source: ByteReadChannel): ULong {
|
||||||
|
var result: ULong = 0u
|
||||||
|
var count = 0
|
||||||
|
while (true) {
|
||||||
|
val x = source.readUByte().toInt()
|
||||||
|
result = result or ((x and 0x7F).toULong() shl count)
|
||||||
|
if ((x and 0x80) == 0)
|
||||||
|
break
|
||||||
|
count += 7
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun ByteReadChannel.readUByte(): UByte = this.readByte().toUByte()
|
||||||
|
|
||||||
|
suspend fun ByteWriteChannel.writeByte(byte: Int) {
|
||||||
|
this.writeByte(byte.toByte())
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2025. Sergey S. Chernov - All Rights Reserved
|
||||||
|
*
|
||||||
|
* You may use, distribute and modify this code under the
|
||||||
|
* terms of the private license, which you must obtain from the author
|
||||||
|
*
|
||||||
|
* To obtain the license, contact the author: https://t.me/real_sergeych or email to
|
||||||
|
* real dot sergeych at gmail.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package net.sergeych.kiloparsec
|
||||||
|
|
||||||
|
import kotlinx.coroutines.sync.Mutex
|
||||||
|
import kotlinx.coroutines.sync.withLock
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Multiplatform atomically mutable value to be used in [kotlinx.coroutines],
|
||||||
|
* with suspending mutating operations, see [mutate].
|
||||||
|
*
|
||||||
|
* Actual value can be either changed in a block of [mutate] when
|
||||||
|
* new value _depends on the current value_ or with [reset].
|
||||||
|
*
|
||||||
|
* [value] getter is suspended because it waits until the mutation finishes
|
||||||
|
*/
|
||||||
|
open class AtomicAsyncValue<T>(initialValue: T) {
|
||||||
|
private var actualValue = initialValue
|
||||||
|
private val access = Mutex()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Change the value: get the current and set to the returned, all in the
|
||||||
|
* atomic suspend operation. All other mutating requests including assigning to [value]
|
||||||
|
* will be blocked and queued.
|
||||||
|
* @return result of the mutation. Note that immediate call to property [value]
|
||||||
|
* could already return modified bu some other thread value!
|
||||||
|
*/
|
||||||
|
suspend fun mutate(mutator: suspend (T) -> T): T = access.withLock {
|
||||||
|
actualValue = mutator(actualValue)
|
||||||
|
actualValue
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Atomic get or set the value. Atomic get means if there is a [mutate] in progress
|
||||||
|
* it will wait until the mutation finishes and then return the correct result.
|
||||||
|
*/
|
||||||
|
suspend fun value() = access.withLock { actualValue }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the new value without checking it. Shortcut to
|
||||||
|
* ```mutate { value = newValue }```
|
||||||
|
*/
|
||||||
|
suspend fun reset(value: T) = mutate { value }
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package net.sergeych.kiloparsec
|
||||||
|
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import kotlin.coroutines.AbstractCoroutineContextElement
|
||||||
|
import kotlin.coroutines.CoroutineContext
|
||||||
|
|
||||||
|
/** Local propagation through the encrypted RPC layers; serialized on the outer transport block. */
|
||||||
|
internal class CallPriority(val value: Int) : AbstractCoroutineContextElement(Key) {
|
||||||
|
companion object Key : CoroutineContext.Key<CallPriority>
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Larger values are sent first. Existing two-argument calls remain priority zero. */
|
||||||
|
suspend fun <A, R> RemoteInterface.call(cmd: Command<A, R>, args: A, priority: Int): R =
|
||||||
|
withContext(CallPriority(priority)) { call(cmd, args) }
|
||||||
|
suspend fun <R> RemoteInterface.call(cmd: Command<Unit, R>, priority: Int): R = call(cmd, Unit, priority)
|
||||||
|
suspend fun <A> RemoteInterface.push(cmd: Command<A, Unit>, args: A, priority: Int) =
|
||||||
|
withContext(CallPriority(priority)) { push(cmd, args) }
|
||||||
|
suspend fun RemoteInterface.push(cmd: Command<Unit, Unit>, priority: Int) = push(cmd, Unit, priority)
|
||||||
@@ -1,3 +1,13 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2025. Sergey S. Chernov - All Rights Reserved
|
||||||
|
*
|
||||||
|
* You may use, distribute and modify this code under the
|
||||||
|
* terms of the private license, which you must obtain from the author
|
||||||
|
*
|
||||||
|
* To obtain the license, contact the author: https://t.me/real_sergeych or email to
|
||||||
|
* real dot sergeych at gmail.
|
||||||
|
*/
|
||||||
|
|
||||||
package net.sergeych.kiloparsec
|
package net.sergeych.kiloparsec
|
||||||
|
|
||||||
import kotlinx.serialization.KSerializer
|
import kotlinx.serialization.KSerializer
|
||||||
@@ -5,15 +15,28 @@ import kotlinx.serialization.Serializable
|
|||||||
import net.sergeych.bintools.toDataSource
|
import net.sergeych.bintools.toDataSource
|
||||||
import net.sergeych.bipack.BipackDecoder
|
import net.sergeych.bipack.BipackDecoder
|
||||||
import net.sergeych.bipack.BipackEncoder
|
import net.sergeych.bipack.BipackEncoder
|
||||||
|
import net.sergeych.kiloparsec.Command.Companion.unpackCall
|
||||||
import net.sergeych.utools.unpack
|
import net.sergeych.utools.unpack
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Typesafe command definition. Command is a universal entity in Divan: it is used
|
* Typesafe command definition. Command is a universal entity in kiloparsec (and also diwan): it is used
|
||||||
* in node-2-node protocols and client API, and most importantly in calling smart contract
|
* in node-2-node protocols and client API, and most importantly in calling smart contract
|
||||||
* methods. This is essentially a Kotlin binding to typesafe serialize command calls and
|
* methods. This is essentially a Kotlin binding to typesafe serialize command calls and
|
||||||
* deserialize results.
|
* deserialize results.
|
||||||
|
*
|
||||||
|
* To create command instances, it is recommended to use [command] that returns [CommandDelegate].
|
||||||
|
*
|
||||||
|
* Use [packCall] to serialize the command call with some arguments.
|
||||||
|
*
|
||||||
|
* Note that `Command` instances themselves are not serialized, instead, the call is serialized,
|
||||||
|
* in the form of [Call], containing name and properly serialized arguments.
|
||||||
|
*
|
||||||
|
* [unpackCall] deserialized result of the [packCall] so the proper handler for the command could
|
||||||
|
* be used. Then the result of the execution could be packed with [exec] and then unpacked with
|
||||||
|
* [unpackResult].
|
||||||
|
*
|
||||||
*/
|
*/
|
||||||
class Command<A, R>(
|
open class Command<A, R>(
|
||||||
val name: String,
|
val name: String,
|
||||||
val argsSerializer: KSerializer<A>,
|
val argsSerializer: KSerializer<A>,
|
||||||
val resultSerializer: KSerializer<R>
|
val resultSerializer: KSerializer<R>
|
||||||
@@ -21,13 +44,29 @@ class Command<A, R>(
|
|||||||
@Serializable
|
@Serializable
|
||||||
data class Call(val name: String,val serializedArgs: UByteArray)
|
data class Call(val name: String,val serializedArgs: UByteArray)
|
||||||
|
|
||||||
fun packCall(args: A): UByteArray = BipackEncoder.encode(
|
/**
|
||||||
Call(name, BipackEncoder.encode(argsSerializer, args).toUByteArray())
|
* Pack command invocation with specified arguments.
|
||||||
).toUByteArray()
|
*/
|
||||||
|
fun packCall(args: A): UByteArray = BipackEncoder.encode(createCall(args)).toUByteArray()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create [Call] instance for specified args vy serializing it properly
|
||||||
|
*/
|
||||||
|
fun createCall(args: A): Call = Call(name, BipackEncoder.encode(argsSerializer, args).toUByteArray())
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unpack result, obtained by [exec].
|
||||||
|
*/
|
||||||
fun unpackResult(packedResult: UByteArray): R =
|
fun unpackResult(packedResult: UByteArray): R =
|
||||||
unpack(resultSerializer, packedResult)
|
unpack(resultSerializer, packedResult)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute a command unpacking args.
|
||||||
|
*
|
||||||
|
* @param packedArgs arguments, as provided by [packCall] in the [Call] instance
|
||||||
|
* @param handler actual code to execute the command
|
||||||
|
* @return properly serialized result to be unpacked with [unpackResult].
|
||||||
|
*/
|
||||||
suspend fun exec(packedArgs: UByteArray, handler: suspend (A) -> R): UByteArray =
|
suspend fun exec(packedArgs: UByteArray, handler: suspend (A) -> R): UByteArray =
|
||||||
BipackEncoder.encode(
|
BipackEncoder.encode(
|
||||||
resultSerializer,
|
resultSerializer,
|
||||||
@@ -36,6 +75,10 @@ class Command<A, R>(
|
|||||||
).toUByteArray()
|
).toUByteArray()
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
|
/**
|
||||||
|
* Unpack command invocation instance from [packCall]. Use [exec] to deserialize arguments and
|
||||||
|
* perform command.
|
||||||
|
*/
|
||||||
fun unpackCall(packedCall: UByteArray): Call = BipackDecoder.decode(packedCall.toDataSource())
|
fun unpackCall(packedCall: UByteArray): Call = BipackDecoder.decode(packedCall.toDataSource())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,3 +1,13 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2025. Sergey S. Chernov - All Rights Reserved
|
||||||
|
*
|
||||||
|
* You may use, distribute and modify this code under the
|
||||||
|
* terms of the private license, which you must obtain from the author
|
||||||
|
*
|
||||||
|
* To obtain the license, contact the author: https://t.me/real_sergeych or email to
|
||||||
|
* real dot sergeych at gmail.
|
||||||
|
*/
|
||||||
|
|
||||||
package net.sergeych.kiloparsec
|
package net.sergeych.kiloparsec
|
||||||
|
|
||||||
import kotlinx.serialization.KSerializer
|
import kotlinx.serialization.KSerializer
|
||||||
@@ -19,6 +29,11 @@ inline fun <reified A, reified R> command(overrideName: String? = null): Command
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Declare a Push: Unit-returning command usually used with [RemoteInterface.push]
|
||||||
|
*/
|
||||||
|
inline fun <reified A> push(overrideName: String? = null): CommandDelegate<A, Unit> = command(overrideName)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Delegate to create [Command] via property
|
* Delegate to create [Command] via property
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -1,3 +1,13 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2025. Sergey S. Chernov - All Rights Reserved
|
||||||
|
*
|
||||||
|
* You may use, distribute and modify this code under the
|
||||||
|
* terms of the private license, which you must obtain from the author
|
||||||
|
*
|
||||||
|
* To obtain the license, contact the author: https://t.me/real_sergeych or email to
|
||||||
|
* real dot sergeych at gmail.
|
||||||
|
*/
|
||||||
|
|
||||||
package net.sergeych.kiloparsec
|
package net.sergeych.kiloparsec
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
package net.sergeych.kiloparsec
|
||||||
|
|
||||||
|
import kotlinx.serialization.builtins.serializer
|
||||||
|
|
||||||
|
/** Opt-in end-to-end encrypted heartbeat, independent of the carrier's keepalive. */
|
||||||
|
data class ConnectionHealth(
|
||||||
|
val intervalMillis: Long = 15_000,
|
||||||
|
val timeoutMillis: Long = 5_000,
|
||||||
|
) {
|
||||||
|
init { require(intervalMillis > 0 && timeoutMillis > 0) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Null attempt limit preserves legacy unlimited reconnect behavior. */
|
||||||
|
data class ReconnectionOptions(
|
||||||
|
val health: ConnectionHealth? = null,
|
||||||
|
val maxAttempts: Int? = null,
|
||||||
|
val connectTimeoutMillis: Long = 15_000,
|
||||||
|
val retryDelayMillis: Long = 700,
|
||||||
|
) {
|
||||||
|
init {
|
||||||
|
require(maxAttempts == null || maxAttempts > 0)
|
||||||
|
require(connectTimeoutMillis > 0 && retryDelayMillis >= 0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reserved inner command: encrypted with the current session and handled before application dispatch.
|
||||||
|
internal val connectionPing = Command("@kiloparsec/ping", Long.serializer(), Long.serializer())
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2025. Sergey S. Chernov - All Rights Reserved
|
||||||
|
*
|
||||||
|
* You may use, distribute and modify this code under the
|
||||||
|
* terms of the private license, which you must obtain from the author
|
||||||
|
*
|
||||||
|
* To obtain the license, contact the author: https://t.me/real_sergeych or email to
|
||||||
|
* real dot sergeych at gmail.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package net.sergeych.kiloparsec
|
||||||
|
|
||||||
|
/**
|
||||||
|
* External errors wich needs to be encoded with a specific code
|
||||||
|
* should implement this interface so it will be serialized properly.
|
||||||
|
*/
|
||||||
|
interface ExceptionWithCode {
|
||||||
|
val code: String
|
||||||
|
val message: String?
|
||||||
|
}
|
||||||
@@ -1,33 +1,75 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2025. Sergey S. Chernov - All Rights Reserved
|
||||||
|
*
|
||||||
|
* You may use, distribute and modify this code under the
|
||||||
|
* terms of the private license, which you must obtain from the author
|
||||||
|
*
|
||||||
|
* To obtain the license, contact the author: https://t.me/real_sergeych or email to
|
||||||
|
* real dot sergeych at gmail.
|
||||||
|
*/
|
||||||
|
|
||||||
package net.sergeych.kiloparsec
|
package net.sergeych.kiloparsec
|
||||||
|
|
||||||
import kotlinx.coroutines.CancellationException
|
import kotlinx.coroutines.CancellationException
|
||||||
import kotlinx.coroutines.CompletableDeferred
|
import kotlinx.coroutines.CompletableDeferred
|
||||||
import kotlinx.coroutines.delay
|
import kotlinx.coroutines.delay
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.asStateFlow
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
import kotlinx.coroutines.isActive
|
import kotlinx.coroutines.isActive
|
||||||
import kotlinx.coroutines.sync.Mutex
|
import kotlinx.coroutines.sync.Mutex
|
||||||
import kotlinx.coroutines.sync.withLock
|
import kotlinx.coroutines.sync.withLock
|
||||||
import net.sergeych.crypto2.SigningKey
|
import net.sergeych.crypto2.SigningKey
|
||||||
|
import net.sergeych.crypto2.VerifyingKey
|
||||||
import net.sergeych.crypto2.VerifyingPublicKey
|
import net.sergeych.crypto2.VerifyingPublicKey
|
||||||
import net.sergeych.mp_logger.LogTag
|
import net.sergeych.mp_logger.LogTag
|
||||||
import net.sergeych.mp_logger.Loggable
|
import net.sergeych.mp_logger.Loggable
|
||||||
import net.sergeych.mp_logger.debug
|
import net.sergeych.mp_logger.debug
|
||||||
import net.sergeych.mp_logger.exception
|
|
||||||
import net.sergeych.mp_tools.globalLaunch
|
import net.sergeych.mp_tools.globalLaunch
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The auto-connecting client that reconnects to the kiloparsec server
|
* The auto-connecting client that reconnects to the kiloparsec server,
|
||||||
|
* [KiloServer],
|
||||||
* and maintain connection state flow. Client factory launches a disconnected
|
* and maintain connection state flow. Client factory launches a disconnected
|
||||||
* set of coroutines to support automatic reconnection, so you _must_ [close]
|
* set of coroutines to support automatic reconnection (unlimited by default; see [options]), so you _must_ [close]
|
||||||
* it manually when it is not needed, otherwise it will continue to reconnect.
|
* it manually when it is unnecessary, otherwise it will continue to reconnect.
|
||||||
|
*
|
||||||
|
* ## Usage
|
||||||
|
*
|
||||||
|
* Suppose we have TCP/IP server as in the [KiloServer] usage sample. Then we can connect
|
||||||
|
* to it providing TCP/IP connector like:
|
||||||
|
*
|
||||||
|
* ```kotlin
|
||||||
|
* val client = KiloClient<Unit>() {
|
||||||
|
* connect { connectTcpDevice("localhost:$port") }
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* // now we can invoke remote commands:
|
||||||
|
* assertEquals("unknown", client.call(cmdLoad))
|
||||||
|
*
|
||||||
|
* client.call(cmdSave, "foobar")
|
||||||
|
* assertEquals("foobar", client.call(cmdLoad))
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* ## See also
|
||||||
|
*
|
||||||
|
* [KiloServer]
|
||||||
|
*
|
||||||
*/
|
*/
|
||||||
class KiloClient<S>(
|
class KiloClient<S>(
|
||||||
val localInterface: KiloInterface<S>,
|
val localInterface: KiloInterface<S>,
|
||||||
secretKey: SigningKey? = null,
|
secretKey: SigningKey? = null,
|
||||||
|
val options: ReconnectionOptions = ReconnectionOptions(),
|
||||||
connectionDataFactory: ConnectionDataFactory<S>,
|
connectionDataFactory: ConnectionDataFactory<S>,
|
||||||
) : RemoteInterface,
|
) : RemoteInterface,
|
||||||
Loggable by LogTag("CLIF") {
|
Loggable by LogTag("CLIF") {
|
||||||
|
constructor(localInterface: KiloInterface<S>, secretKey: SigningKey? = null, connectionDataFactory: ConnectionDataFactory<S>)
|
||||||
|
: this(localInterface, secretKey, ReconnectionOptions(), connectionDataFactory)
|
||||||
|
|
||||||
|
private val stopped = MutableStateFlow(false)
|
||||||
|
private val exhausted = MutableStateFlow(false)
|
||||||
|
/** True when the finite attempt budget has ended. Create a new client for another carrier. */
|
||||||
|
val reconnectExhausted = exhausted.asStateFlow()
|
||||||
|
|
||||||
val _state = MutableStateFlow(false)
|
val _state = MutableStateFlow(false)
|
||||||
|
|
||||||
@@ -38,48 +80,76 @@ class KiloClient<S>(
|
|||||||
@Suppress("unused")
|
@Suppress("unused")
|
||||||
val connectedStateFlow = _state.asStateFlow()
|
val connectedStateFlow = _state.asStateFlow()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The verifying, or public, key identifying client sessions. It could be used to
|
||||||
|
* restore environment on reconnection. This is what remote side, e.g. server, sees as
|
||||||
|
* [KiloScope.remoteIdentity].
|
||||||
|
*/
|
||||||
|
@Suppress("unused")
|
||||||
|
val localIdentity: VerifyingKey? = secretKey?.verifyingKey
|
||||||
|
|
||||||
private var deferredClient = CompletableDeferred<KiloClientConnection<S>>()
|
private var deferredClient = CompletableDeferred<KiloClientConnection<S>>()
|
||||||
|
|
||||||
|
private val defMutex = Mutex()
|
||||||
|
|
||||||
private val job =
|
private val job =
|
||||||
globalLaunch {
|
globalLaunch {
|
||||||
debug { "starting connector" }
|
debug { "starting connector" }
|
||||||
while (isActive) {
|
var attempts = 0
|
||||||
try {
|
try {
|
||||||
debug { "getting connection" }
|
while (isActive && (options.maxAttempts == null || attempts < options.maxAttempts)) {
|
||||||
val kc = connectionDataFactory()
|
attempts++
|
||||||
debug { "get device and session" }
|
var connectedAt: kotlin.time.TimeMark? = null
|
||||||
val client = KiloClientConnection(localInterface, kc, secretKey)
|
try {
|
||||||
|
val client = kotlinx.coroutines.withTimeout(options.connectTimeoutMillis) {
|
||||||
|
KiloClientConnection(localInterface, connectionDataFactory(), secretKey)
|
||||||
|
}
|
||||||
deferredClient.complete(client)
|
deferredClient.complete(client)
|
||||||
client.run {
|
kotlinx.coroutines.coroutineScope {
|
||||||
|
val setupDeadline = launch {
|
||||||
|
delay(options.connectTimeoutMillis)
|
||||||
|
throw RemoteInterface.ClosedException()
|
||||||
|
}
|
||||||
|
val onState: (Boolean) -> Unit = {
|
||||||
_state.value = it
|
_state.value = it
|
||||||
|
if (it) {
|
||||||
|
connectedAt = kotlin.time.TimeSource.Monotonic.markNow()
|
||||||
|
setupDeadline.cancel()
|
||||||
}
|
}
|
||||||
resetDeferredClient()
|
|
||||||
debug { "client run finished" }
|
|
||||||
} catch (_: RemoteInterface.ClosedException) {
|
|
||||||
debug { "remote closed" }
|
|
||||||
delay(1000)
|
|
||||||
} catch (_: CancellationException) {
|
|
||||||
debug { "cancelled" }
|
|
||||||
break
|
|
||||||
} catch (t: Throwable) {
|
|
||||||
exception { "unexpected exception" to t }
|
|
||||||
delay(1000)
|
|
||||||
}
|
}
|
||||||
|
if (options.health == null) client.run(onState)
|
||||||
|
else client.run(options.health, onState)
|
||||||
|
setupDeadline.cancel()
|
||||||
|
}
|
||||||
|
} catch (t: kotlinx.coroutines.TimeoutCancellationException) {
|
||||||
|
debug { "connection setup timed out" }
|
||||||
|
} catch (t: CancellationException) { throw t }
|
||||||
|
catch (t: Throwable) { debug { "connection ended: $t" } }
|
||||||
|
finally {
|
||||||
_state.value = false
|
_state.value = false
|
||||||
resetDeferredClient()
|
resetDeferredClient()
|
||||||
delay(100)
|
}
|
||||||
|
// Short authenticated-but-dead sessions must still exhaust the budget.
|
||||||
|
val stableMillis = options.health?.let { 3 * (it.intervalMillis + it.timeoutMillis) } ?: 30_000L
|
||||||
|
if ((connectedAt?.elapsedNow()?.inWholeMilliseconds ?: 0) > stableMillis) attempts = 0
|
||||||
|
if (options.maxAttempts == null || attempts < options.maxAttempts) delay(options.retryDelayMillis)
|
||||||
|
}
|
||||||
|
exhausted.value = true
|
||||||
|
} finally {
|
||||||
|
_state.value = false
|
||||||
|
deferredClient.completeExceptionally(RemoteInterface.ClosedException())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun close() {
|
fun close() {
|
||||||
|
stopped.value = true
|
||||||
job.cancel()
|
job.cancel()
|
||||||
debug { "client is closed" }
|
debug { "client is closed" }
|
||||||
}
|
}
|
||||||
|
|
||||||
private val defMutex = Mutex()
|
|
||||||
private suspend fun resetDeferredClient() {
|
private suspend fun resetDeferredClient() {
|
||||||
defMutex.withLock {
|
defMutex.withLock {
|
||||||
if (!deferredClient.isActive) {
|
if (!deferredClient.isActive && !exhausted.value && !stopped.value) {
|
||||||
deferredClient = CompletableDeferred()
|
deferredClient = CompletableDeferred()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -94,6 +164,18 @@ class KiloClient<S>(
|
|||||||
throw t
|
throw t
|
||||||
}
|
}
|
||||||
|
|
||||||
|
override suspend fun <A> push(cmd: Command<A, Unit>, args: A) {
|
||||||
|
try {
|
||||||
|
deferredClient.await().push(cmd, args)
|
||||||
|
} catch (t: RemoteInterface.ClosedException) {
|
||||||
|
resetDeferredClient()
|
||||||
|
throw t
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Perform an encrypted liveness round trip on the active connection. */
|
||||||
|
suspend fun ping() = deferredClient.await().ping()
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Current session token. This is a per-connection unique random value same on the client and server part so
|
* Current session token. This is a per-connection unique random value same on the client and server part so
|
||||||
* it could be used as a nonce to pair MITM and like attacks, be sure that the server is actually
|
* it could be used as a nonce to pair MITM and like attacks, be sure that the server is actually
|
||||||
@@ -109,7 +191,7 @@ class KiloClient<S>(
|
|||||||
* a key. Connection is established either with a properly authenticated key or no key at all.
|
* a key. Connection is established either with a properly authenticated key or no key at all.
|
||||||
*/
|
*/
|
||||||
@Suppress("unused")
|
@Suppress("unused")
|
||||||
suspend fun remoteId(): VerifyingPublicKey? = deferredClient.await().remoteId()
|
suspend fun remoteIdentity(): VerifyingPublicKey? = deferredClient.await().remoteId()
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
class Builder<S>() {
|
class Builder<S>() {
|
||||||
@@ -121,11 +203,24 @@ class KiloClient<S>(
|
|||||||
}
|
}
|
||||||
private var connectionBuilder: (suspend () -> Transport.Device)? = null
|
private var connectionBuilder: (suspend () -> Transport.Device)? = null
|
||||||
|
|
||||||
|
var reconnectionOptions: ReconnectionOptions = ReconnectionOptions()
|
||||||
|
|
||||||
var secretIdKey: SigningKey? = null
|
var secretIdKey: SigningKey? = null
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Build local command implementations (remotely callable ones), exception
|
* Build local command implementations, those callable from the server, exception
|
||||||
* class handlers, etc.
|
* class handlers, and anything else [KiloInterface] allows. Usage sample:
|
||||||
|
*
|
||||||
|
* ```kotlin
|
||||||
|
* val client = KiloClient {
|
||||||
|
* connect { connectTcpDevice("localhost:$port") }
|
||||||
|
* local {
|
||||||
|
* on(cmdPing) {
|
||||||
|
* "pong! $it"
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
*/
|
*/
|
||||||
fun local(f: KiloInterface<S>.() -> Unit) {
|
fun local(f: KiloInterface<S>.() -> Unit) {
|
||||||
interfaceBuilder = f
|
interfaceBuilder = f
|
||||||
@@ -164,7 +259,7 @@ class KiloClient<S>(
|
|||||||
for (ep in errorProviders) i.addErrorProvider(ep)
|
for (ep in errorProviders) i.addErrorProvider(ep)
|
||||||
interfaceBuilder?.let { i.it() }
|
interfaceBuilder?.let { i.it() }
|
||||||
val connector = connectionBuilder ?: throw IllegalArgumentException("connect handler was not set")
|
val connector = connectionBuilder ?: throw IllegalArgumentException("connect handler was not set")
|
||||||
return KiloClient(i, secretIdKey) {
|
return KiloClient(i, secretIdKey, reconnectionOptions) {
|
||||||
KiloConnectionData(connector(), sessionBuilder())
|
KiloConnectionData(connector(), sessionBuilder())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,13 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2025. Sergey S. Chernov - All Rights Reserved
|
||||||
|
*
|
||||||
|
* You may use, distribute and modify this code under the
|
||||||
|
* terms of the private license, which you must obtain from the author
|
||||||
|
*
|
||||||
|
* To obtain the license, contact the author: https://t.me/real_sergeych or email to
|
||||||
|
* real dot sergeych at gmail.
|
||||||
|
*/
|
||||||
|
|
||||||
package net.sergeych.kiloparsec
|
package net.sergeych.kiloparsec
|
||||||
|
|
||||||
import kotlinx.coroutines.*
|
import kotlinx.coroutines.*
|
||||||
@@ -9,6 +19,7 @@ import net.sergeych.mp_logger.Loggable
|
|||||||
import net.sergeych.mp_logger.debug
|
import net.sergeych.mp_logger.debug
|
||||||
import net.sergeych.mp_logger.info
|
import net.sergeych.mp_logger.info
|
||||||
import net.sergeych.utools.pack
|
import net.sergeych.utools.pack
|
||||||
|
import net.sergeych.utools.unpack
|
||||||
|
|
||||||
private var clientIds = 0
|
private var clientIds = 0
|
||||||
|
|
||||||
@@ -33,71 +44,115 @@ class KiloClientConnection<S>(
|
|||||||
* will stop the transport, or the calling scope will be canceled.
|
* will stop the transport, or the calling scope will be canceled.
|
||||||
* Cancelling the scope where server is running is a preferred way to stop the client.
|
* Cancelling the scope where server is running is a preferred way to stop the client.
|
||||||
*/
|
*/
|
||||||
suspend fun run(onConnectedStateChanged: ((Boolean) -> Unit)? = null) {
|
suspend fun run(onConnectedStateChanged: ((Boolean) -> Unit)? = null) = runConfigured(null, onConnectedStateChanged)
|
||||||
|
|
||||||
|
suspend fun run(health: ConnectionHealth, onConnectedStateChanged: ((Boolean) -> Unit)? = null) =
|
||||||
|
runConfigured(health, onConnectedStateChanged)
|
||||||
|
|
||||||
|
private suspend fun runConfigured(health: ConnectionHealth?, onConnectedStateChanged: ((Boolean) -> Unit)?) {
|
||||||
coroutineScope {
|
coroutineScope {
|
||||||
var job: Job? = null
|
var job: Job? = null
|
||||||
|
var connectedScope: KiloScope<S>? = null
|
||||||
try {
|
try {
|
||||||
// in parallel: keys and connection
|
// in parallel: keys and connection
|
||||||
val deferredKeyPair = async { SafeKeyExchange() }
|
val deferredKeyPair = async { SafeKeyExchange() }
|
||||||
debug { "opening device" }
|
|
||||||
debug { "got a transport device $device" }
|
debug { "got a transport device $device" }
|
||||||
|
|
||||||
|
|
||||||
// client transport has no dedicated commands (unlike the server's),
|
// client transport has no dedicated commands (unlike the server's),
|
||||||
// it is a calling party:
|
// it is a calling party:
|
||||||
val l0Interface = KiloL0Interface(clientInterface, deferredParams)
|
val l0Interface = KiloL0Interface(clientInterface, deferredParams, allowHandshakeCallbacks = true)
|
||||||
val transport = Transport(device, l0Interface, Unit)
|
val transport = Transport(device, l0Interface, Unit)
|
||||||
|
|
||||||
job = launch { transport.run() }
|
job = launch { transport.run() }
|
||||||
debug { "transport started" }
|
debug { "transport started" }
|
||||||
|
|
||||||
val pair = deferredKeyPair.await()
|
val pair = deferredKeyPair.await()
|
||||||
debug { "keypair ready" }
|
debug { "keypair ready (1)" }
|
||||||
|
|
||||||
val serverHe = transport.call(L0Request, Handshake(1u, pair.publicKey))
|
val serverHe = transport.call(L0Request, Handshake(KILO_PROTOCOL_VERSION, pair.publicKey))
|
||||||
|
|
||||||
|
debug { "got server HE (2)" }
|
||||||
|
if (serverHe.version != KILO_PROTOCOL_VERSION)
|
||||||
|
throw RemoteInterface.SecurityException("unsupported Kiloparsec protocol")
|
||||||
val sk = pair.clientSessionKey(serverHe.publicKey)
|
val sk = pair.clientSessionKey(serverHe.publicKey)
|
||||||
var params = KiloParams(false, transport, sk, session, null, this@KiloClientConnection)
|
var params = KiloParams(false, transport, sk, session, null, this@KiloClientConnection)
|
||||||
|
|
||||||
// Check ID if any
|
// Check ID if any
|
||||||
serverHe.signature?.let { s ->
|
serverHe.signature?.let { s ->
|
||||||
if (!s.isValid(params.token))
|
if (!s.isValid(serverAuthentication(params.token)))
|
||||||
throw RemoteInterface.SecurityException("wrong signature")
|
throw RemoteInterface.SecurityException("wrong signature")
|
||||||
params = params.copy(remoteIdentity = s.publicKey)
|
params = params.authenticated(s.publicKey)
|
||||||
}
|
}
|
||||||
|
|
||||||
transport.call(
|
val identity = pack(ClientIdentity(secretIdKey?.verifyingKey,
|
||||||
L0ClientId, params.encrypt(
|
secretIdKey?.sign(clientAuthentication(params.token))))
|
||||||
pack(
|
val finished = unpack<ProtectedMessage>(transport.callWithId(L0ClientId,
|
||||||
ClientIdentity(
|
readResponse = params::decrypt) { params.encode(identity) })
|
||||||
secretIdKey?.verifyingKey,
|
if (finished.kind != ProtectedKind.SERVER_FINISHED || finished.correlation != 0uL ||
|
||||||
secretIdKey?.sign(params.token)
|
finished.priority != 0 || !finished.payload.contentEquals(identity))
|
||||||
)
|
throw RemoteInterface.SecurityException("invalid server finished")
|
||||||
)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
deferredParams.complete(params)
|
deferredParams.complete(params)
|
||||||
kiloRemoteInterface.complete(
|
kiloRemoteInterface.complete(
|
||||||
KiloRemoteInterface(deferredParams, clientInterface)
|
KiloRemoteInterface(deferredParams, clientInterface)
|
||||||
)
|
)
|
||||||
clientInterface.onConnectHandler?.invoke(params.scope)
|
connectedScope = params.scope
|
||||||
|
clientInterface.onConnectHandlers.invokeAll(connectedScope)
|
||||||
onConnectedStateChanged?.invoke(true)
|
onConnectedStateChanged?.invoke(true)
|
||||||
job.join()
|
val heartbeat = health?.let { options ->
|
||||||
|
launch {
|
||||||
|
while (isActive) {
|
||||||
|
delay(options.intervalMillis)
|
||||||
|
if (withTimeoutOrNull(options.timeoutMillis) {
|
||||||
|
withContext(CallPriority(100)) { ping() }; true
|
||||||
|
} != true) throw RemoteInterface.ClosedException()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try { job.join() }
|
||||||
|
finally { heartbeat?.cancelAndJoin() }
|
||||||
|
|
||||||
} catch (x: CancellationException) {
|
} catch (x: CancellationException) {
|
||||||
info { "client is cancelled" }
|
info { "client is cancelled" }
|
||||||
} catch (x: RemoteInterface.ClosedException) {
|
} catch (x: RemoteInterface.ClosedException) {
|
||||||
x.printStackTrace()
|
debug { "connection closed/refused by remote" }
|
||||||
info { "connection closed by remote" }
|
|
||||||
} finally {
|
} finally {
|
||||||
|
if (!deferredParams.isCompleted) deferredParams.completeExceptionally(RemoteInterface.ClosedException())
|
||||||
|
if (!kiloRemoteInterface.isCompleted) kiloRemoteInterface.completeExceptionally(RemoteInterface.ClosedException())
|
||||||
|
connectedScope?.let { clientInterface.onDisconnectHandlers.invokeAll(it) }
|
||||||
onConnectedStateChanged?.invoke(false)
|
onConnectedStateChanged?.invoke(false)
|
||||||
job?.cancel()
|
withContext(NonCancellable) {
|
||||||
|
job?.cancelAndJoin()
|
||||||
device.apply { runCatching { close() } }
|
device.apply { runCatching { close() } }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Encrypted round trip. Older peers' encrypted UnknownCommand also proves liveness. */
|
||||||
|
suspend fun ping() {
|
||||||
|
val nonce = kotlin.random.Random.nextLong()
|
||||||
|
try { check(call(connectionPing, nonce) == nonce) { "Invalid heartbeat response" } }
|
||||||
|
catch (_: RemoteInterface.UnknownCommand) { /* Compatible with peers predating native ping. */ }
|
||||||
|
}
|
||||||
|
|
||||||
suspend fun token() = deferredParams.await().token
|
suspend fun token() = deferredParams.await().token
|
||||||
override suspend fun <A, R> call(cmd: Command<A, R>, args: A): R =
|
override suspend fun <A, R> call(cmd: Command<A, R>, args: A): R =
|
||||||
kiloRemoteInterface.await().call(cmd, args)
|
kiloRemoteInterface.await().call(cmd, args)
|
||||||
|
|
||||||
|
override suspend fun <A> push(cmd: Command<A, Unit>, args: A) {
|
||||||
|
kiloRemoteInterface.await().push(cmd, args)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun <S>Collection<KiloHandler<S>>.invokeAll(scope: KiloScope<S>) =
|
||||||
|
forEach { handler ->
|
||||||
|
try {
|
||||||
|
scope.handler()
|
||||||
|
} catch (e: LocalInterface.BreakConnectionException) {
|
||||||
|
// Includes SecurityException and application-defined rejection subclasses.
|
||||||
|
throw e
|
||||||
|
} catch (_: Throwable) {
|
||||||
|
// Preserve best-effort notification for other handler failures.
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,26 +1,62 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2025. Sergey S. Chernov - All Rights Reserved
|
||||||
|
*
|
||||||
|
* You may use, distribute and modify this code under the
|
||||||
|
* terms of the private license, which you must obtain from the author
|
||||||
|
*
|
||||||
|
* To obtain the license, contact the author: https://t.me/real_sergeych or email to
|
||||||
|
* real dot sergeych at gmail.
|
||||||
|
*/
|
||||||
|
|
||||||
package net.sergeych.kiloparsec
|
package net.sergeych.kiloparsec
|
||||||
|
|
||||||
|
typealias KiloHandler<S> = KiloScope<S>.()->Unit
|
||||||
/**
|
/**
|
||||||
* The local interface to provice functions, register errors for Kiloparsec users. Use it
|
* The local interface to provide functions, register errors for Kiloparsec users. Use it
|
||||||
* with [KiloClient], [KiloClientConnection], [KiloServerConnection], etc.
|
* with [KiloClient], [KiloClientConnection], [KiloServerConnection], etc.
|
||||||
*
|
*
|
||||||
* BAse implementation registers relevant exceptions.
|
* Base class implementation does the following:
|
||||||
|
*
|
||||||
|
* - It registers common exceptions from [RemoteInterface] and kotlin/java `IllegalArgumentException` and
|
||||||
|
* `IllegalStateException`
|
||||||
|
* - It provides [onConnected] and [onDisconnected] handlers
|
||||||
|
*
|
||||||
|
* See [KiloServer] for usage sample.
|
||||||
*/
|
*/
|
||||||
open class KiloInterface<S> : LocalInterface<KiloScope<S>>() {
|
open class KiloInterface<S> : LocalInterface<KiloScope<S>>() {
|
||||||
|
|
||||||
internal var onConnectHandler: (KiloScope<S>.()->Unit) ? = null
|
internal val onConnectHandlers = mutableListOf<KiloHandler<S>>()
|
||||||
|
internal val onDisconnectHandlers = mutableListOf<KiloHandler<S>>()
|
||||||
|
|
||||||
fun onConnected(f: KiloScope<S>.()->Unit) { onConnectHandler = f }
|
/**
|
||||||
|
* Registers handler [f] for [onConnected] event, to the head or the end of a handler list.
|
||||||
|
*
|
||||||
|
* @param addFirst if true, [f] will be added to the beginning of the list of handlers
|
||||||
|
*/
|
||||||
|
fun onConnected(addFirst: Boolean = false, f: KiloScope<S>.()->Unit) {
|
||||||
|
if( addFirst ) onConnectHandlers.add(0, f) else onConnectHandlers += f
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Registers handler [f] for [onDisconnected] event, to the head or the end of a handler list.
|
||||||
|
*
|
||||||
|
* It is called with the same connection [KiloScope] as [onConnected], after an established
|
||||||
|
* connection is closed.
|
||||||
|
*
|
||||||
|
* @param addFirst if true, [f] will be added to the beginning of the list of handlers
|
||||||
|
*/
|
||||||
|
fun onDisconnected(addFirst: Boolean = false, f: KiloScope<S>.()->Unit) {
|
||||||
|
if( addFirst ) onDisconnectHandlers.add(0, f) else onDisconnectHandlers += f
|
||||||
|
}
|
||||||
|
|
||||||
init {
|
init {
|
||||||
registerError { RemoteInterface.UnknownCommand() }
|
registerError { RemoteInterface.UnknownCommand(it) }
|
||||||
registerError { RemoteInterface.InternalError(it) }
|
registerError { RemoteInterface.InternalError(it) }
|
||||||
registerError { RemoteInterface.ClosedException(it) }
|
registerError { RemoteInterface.ClosedException(it) }
|
||||||
// registerError { RemoteInterface.SecurityException(it) }
|
registerError { RemoteInterface.SecurityException(it) }
|
||||||
registerError { RemoteInterface.InvalidDataException(it) }
|
registerError { RemoteInterface.InvalidDataException(it) }
|
||||||
registerError { RemoteInterface.RemoteException(it) }
|
registerError { RemoteInterface.RemoteException(it) }
|
||||||
registerError { IllegalStateException() }
|
registerError { IllegalStateException() }
|
||||||
registerError { IllegalArgumentException(it) }
|
registerError { IllegalArgumentException(it) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1,45 +1,52 @@
|
|||||||
|
/* Copyright (c) 2026 Sergey S. Chernov. Private license; see README. */
|
||||||
package net.sergeych.kiloparsec
|
package net.sergeych.kiloparsec
|
||||||
|
|
||||||
|
import kotlinx.coroutines.CancellationException
|
||||||
import kotlinx.coroutines.CompletableDeferred
|
import kotlinx.coroutines.CompletableDeferred
|
||||||
import net.sergeych.tools.AtomicCounter
|
import net.sergeych.tools.AtomicCounter
|
||||||
import net.sergeych.utools.pack
|
import net.sergeych.utools.pack
|
||||||
|
import net.sergeych.utools.unpack
|
||||||
|
|
||||||
private val idCounter = AtomicCounter(0)
|
private val idCounter = AtomicCounter(0)
|
||||||
|
|
||||||
/**
|
/** Authenticates dispatch metadata before looking up or deserializing an application command. */
|
||||||
* This class is not normally used directly. This is a local interface that supports
|
|
||||||
* secure transport command layer (encrypted calls/results) to work with [KiloRemoteInterface].
|
|
||||||
*
|
|
||||||
* It is recommended to use [KiloClientConnection] and [KiloServerConnection] instead.
|
|
||||||
*/
|
|
||||||
internal class KiloL0Interface<T>(
|
internal class KiloL0Interface<T>(
|
||||||
private val clientInterface: LocalInterface<KiloScope<T>>,
|
private val clientInterface: LocalInterface<KiloScope<T>>,
|
||||||
private val deferredParams: CompletableDeferred<KiloParams<T>>,
|
private val deferredParams: CompletableDeferred<KiloParams<T>>,
|
||||||
|
private val allowHandshakeCallbacks: Boolean = false,
|
||||||
) : LocalInterface<Unit>() {
|
) : LocalInterface<Unit>() {
|
||||||
|
|
||||||
override var logTag: String = "KL0:${idCounter.incrementAndGet()}"
|
override var logTag: String = "KL0:${idCounter.incrementAndGet()}"
|
||||||
|
init { addErrorProvider(clientInterface) }
|
||||||
|
// Plaintext transport errors must never use application exception constructors.
|
||||||
|
override fun getErrorBuilder(code: String): ((String, UByteArray?) -> Throwable)? = null
|
||||||
|
|
||||||
init {
|
override suspend fun executeTransportBlock(scope: Unit, block: Transport.Block.Call): PreparedPayload {
|
||||||
// local interface uses the same session as a client:
|
if (block.name != L0Call.name) return super.executeTransportBlock(scope, block)
|
||||||
addErrorProvider(clientInterface)
|
if (!allowHandshakeCallbacks && !deferredParams.isCompleted)
|
||||||
|
throw RemoteInterface.SecurityException("application call before authentication")
|
||||||
on(L0Call) {
|
|
||||||
val params = deferredParams.await()
|
val params = deferredParams.await()
|
||||||
val call = Command.unpackCall(params.decrypt(it))
|
val frame: ProtectedMessage = try { params.decryptMessage(unpack(block.packedArgs)) }
|
||||||
// tricky part: we need to encrypt a result or error: we can't allow default
|
catch (e: DiscardPacket) { throw e }
|
||||||
// error transport (as it is not encrypted), so we re-use transport blocks here:
|
catch (e: Throwable) { throw RemoteInterface.SecurityException("invalid authenticated call") }
|
||||||
|
val expected = if (block.id == 0u) ProtectedKind.PUSH else ProtectedKind.CALL
|
||||||
|
if (frame.kind != expected || frame.correlation != block.id.toULong() || frame.priority != block.priority)
|
||||||
|
throw RemoteInterface.SecurityException("authenticated routing mismatch")
|
||||||
|
val call = try { Command.unpackCall(frame.payload) }
|
||||||
|
catch (e: Throwable) { throw RemoteInterface.SecurityException("invalid command encoding") }
|
||||||
val result: Transport.Block = try {
|
val result: Transport.Block = try {
|
||||||
Transport.Block.Response(
|
Transport.Block.Response(0u,
|
||||||
0u,
|
if (call.name == connectionPing.name) connectionPing.exec(call.serializedArgs) { it }
|
||||||
clientInterface.execute(params.scope, call.name, call.serializedArgs)
|
else clientInterface.execute(params.scope, call.name, call.serializedArgs))
|
||||||
)
|
} catch (e: BreakConnectionException) { throw e }
|
||||||
} catch(t: BreakConnectionException) {
|
catch (e: CancellationException) { throw e }
|
||||||
throw t
|
catch (e: Throwable) { clientInterface.encodeError(0u, e) }
|
||||||
}
|
// Push has no reply; its authenticated kind cannot be changed by rewriting id=0.
|
||||||
catch (t: Throwable) {
|
if (frame.kind == ProtectedKind.PUSH) return PreparedPayload { OutgoingData(pack(Unit)) }
|
||||||
clientInterface.encodeError(0u, t)
|
val kind = if (result is Transport.Block.Error) ProtectedKind.ERROR else ProtectedKind.RESPONSE
|
||||||
}
|
val payload = pack(result)
|
||||||
params.encrypt(pack(result))
|
return PreparedPayload {
|
||||||
|
val encoded = params.encodeMessage(ProtectedMessage(kind, frame.correlation, frame.priority, payload))
|
||||||
|
OutgoingData(pack(encoded.bytes), encoded.nonce)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,3 +1,13 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2025. Sergey S. Chernov - All Rights Reserved
|
||||||
|
*
|
||||||
|
* You may use, distribute and modify this code under the
|
||||||
|
* terms of the private license, which you must obtain from the author
|
||||||
|
*
|
||||||
|
* To obtain the license, contact the author: https://t.me/real_sergeych or email to
|
||||||
|
* real dot sergeych at gmail.
|
||||||
|
*/
|
||||||
|
|
||||||
package net.sergeych.kiloparsec
|
package net.sergeych.kiloparsec
|
||||||
|
|
||||||
import kotlinx.serialization.Serializable
|
import kotlinx.serialization.Serializable
|
||||||
@@ -35,6 +45,7 @@ data class KiloParams<S>(
|
|||||||
)
|
)
|
||||||
|
|
||||||
private var nonce = 0UL
|
private var nonce = 0UL
|
||||||
|
private var received = ReplayWindow()
|
||||||
|
|
||||||
val scope: KiloScope<S> by lazy {
|
val scope: KiloScope<S> by lazy {
|
||||||
object : KiloScope<S> {
|
object : KiloScope<S> {
|
||||||
@@ -56,24 +67,48 @@ data class KiloParams<S>(
|
|||||||
/**
|
/**
|
||||||
* Encrypt using send keys and proper nonce
|
* Encrypt using send keys and proper nonce
|
||||||
*/
|
*/
|
||||||
fun encrypt(message: UByteArray, fillFactor: Float = 0f): UByteArray {
|
fun encrypt(message: UByteArray, fillFactor: Float = 0f): UByteArray = encode(message, fillFactor).bytes
|
||||||
|
|
||||||
|
internal fun encode(message: UByteArray, fillFactor: Float = 0f): OutgoingData {
|
||||||
val fill = if (fillFactor > 0f)
|
val fill = if (fillFactor > 0f)
|
||||||
0..(message.size * fillFactor).roundToInt()
|
0..(message.size * fillFactor).roundToInt()
|
||||||
else
|
else
|
||||||
null
|
null
|
||||||
|
|
||||||
val n = protectedOp.invoke { nonce++ }
|
val n = protectedOp.invoke {
|
||||||
|
if (nonce == ULong.MAX_VALUE) throw RemoteInterface.SecurityException("session nonce exhausted")
|
||||||
return pack(
|
nonce++
|
||||||
Package(n, sessionKey.encryptWithNonce(message, numericNonce.withULong(n), fill))
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// fun decryptString(cipherText: UByteArray): String = decrypt(cipherText).decodeFromUByteArray()
|
return OutgoingData(pack(
|
||||||
fun decrypt(encryptedMessage: UByteArray): UByteArray =
|
Package(n, sessionKey.encryptWithNonce(message, numericNonce.withULong(n), fill))
|
||||||
protectDecryption {
|
), n)
|
||||||
val p: Package = BipackDecoder.decode(encryptedMessage.toDataSource())
|
}
|
||||||
|
|
||||||
|
/** Authenticate and consume one incoming nonce, allowing bounded out-of-order delivery. */
|
||||||
|
fun decrypt(encryptedMessage: UByteArray): UByteArray {
|
||||||
|
val p = protectDecryption { BipackDecoder.decode<Package>(encryptedMessage.toDataSource()) }
|
||||||
|
return protectedOp.invoke {
|
||||||
|
if (received.containsOrStale(p.nonce)) throw DiscardPacket()
|
||||||
|
val clear = protectDecryption {
|
||||||
sessionKey.decryptWithNonce(p.encryptedMessage, numericNonce.withULong(p.nonce))
|
sessionKey.decryptWithNonce(p.encryptedMessage, numericNonce.withULong(p.nonce))
|
||||||
}
|
}
|
||||||
|
received.record(p.nonce)
|
||||||
|
clear
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Identity completion must not reset counters/replay history already used by the handshake. */
|
||||||
|
internal fun authenticated(identity: VerifyingPublicKey): KiloParams<S> = protectedOp.invoke {
|
||||||
|
copy(remoteIdentity = identity).also {
|
||||||
|
it.nonce = nonce
|
||||||
|
it.received = received.copy()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun encodeMessage(message: ProtectedMessage): OutgoingData = encode(pack(message))
|
||||||
|
|
||||||
|
internal fun encryptMessage(message: ProtectedMessage): UByteArray = encrypt(pack(message))
|
||||||
|
internal fun decryptMessage(message: UByteArray): ProtectedMessage =
|
||||||
|
net.sergeych.utools.unpack(decrypt(message))
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
/* Copyright (c) 2026 Sergey S. Chernov. Private license; see README. */
|
||||||
|
package net.sergeych.kiloparsec
|
||||||
|
|
||||||
|
import kotlinx.serialization.Serializable
|
||||||
|
import net.sergeych.bipack.Unsigned
|
||||||
|
|
||||||
|
/** Protocol 2 never falls back to the unauthenticated v1 RPC envelope. */
|
||||||
|
internal const val KILO_PROTOCOL_VERSION: UInt = 2u
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
internal enum class ProtectedKind { CALL, PUSH, RESPONSE, ERROR, SERVER_FINISHED }
|
||||||
|
|
||||||
|
/** All dispatch/correlation metadata is authenticated by the session cipher. */
|
||||||
|
@Serializable
|
||||||
|
internal data class ProtectedMessage(
|
||||||
|
val kind: ProtectedKind,
|
||||||
|
@Unsigned val correlation: ULong,
|
||||||
|
val priority: Int,
|
||||||
|
val payload: UByteArray,
|
||||||
|
)
|
||||||
|
|
||||||
|
internal fun serverAuthentication(token: UByteArray): UByteArray =
|
||||||
|
"kiloparsec/v2/server\u0000".encodeToByteArray().toUByteArray() + token
|
||||||
|
internal fun clientAuthentication(token: UByteArray): UByteArray =
|
||||||
|
"kiloparsec/v2/client\u0000".encodeToByteArray().toUByteArray() + token
|
||||||
@@ -1,39 +1,63 @@
|
|||||||
|
/* Copyright (c) 2026 Sergey S. Chernov. Private license; see README. */
|
||||||
package net.sergeych.kiloparsec
|
package net.sergeych.kiloparsec
|
||||||
|
|
||||||
import kotlinx.coroutines.CompletableDeferred
|
import kotlinx.coroutines.CompletableDeferred
|
||||||
import net.sergeych.mp_logger.LogTag
|
import kotlinx.coroutines.CancellationException
|
||||||
import net.sergeych.mp_logger.Loggable
|
import kotlinx.coroutines.currentCoroutineContext
|
||||||
import net.sergeych.utools.unpack
|
import net.sergeych.utools.unpack
|
||||||
|
|
||||||
private var L1IdCounter = 0
|
/** Full-duplex remote interface with authenticated request/result correlation. */
|
||||||
|
|
||||||
/**
|
|
||||||
* Represents a remote interface for interacting with a Kiloparsec service.
|
|
||||||
*
|
|
||||||
* @param S the scope type of the Kiloparsec service which will be used to call local functions remotely
|
|
||||||
* @property deferredParams a [CompletableDeferred] that resolves to the parameters required for making remote calls
|
|
||||||
* @property clientInterface a [LocalInterface] used to communicate with the local client
|
|
||||||
*/
|
|
||||||
class KiloRemoteInterface<S>(
|
class KiloRemoteInterface<S>(
|
||||||
private val deferredParams: CompletableDeferred<KiloParams<S>>,
|
private val deferredParams: CompletableDeferred<KiloParams<S>>,
|
||||||
private val clientInterface: LocalInterface<KiloScope<S>>,
|
private val clientInterface: LocalInterface<KiloScope<S>>,
|
||||||
) : RemoteInterface, Loggable by LogTag("L1TR:${++L1IdCounter}") {
|
) : RemoteInterface {
|
||||||
|
|
||||||
override suspend fun <A, R> call(cmd: Command<A, R>, args: A): R {
|
override suspend fun <A, R> call(cmd: Command<A, R>, args: A): R {
|
||||||
val params = deferredParams.await()
|
val params = deferredParams.await()
|
||||||
val block: Transport.Block = unpack(
|
val transport = params.transport as Transport<*>
|
||||||
params.decrypt(
|
val priority = currentCoroutineContext()[CallPriority]?.value ?: 0
|
||||||
params.transport.call(L0Call, params.encrypt(cmd.packCall(args)))
|
var requestId = 0u
|
||||||
)
|
val call = cmd.packCall(args)
|
||||||
)
|
val encoded = try {
|
||||||
|
transport.callWithId(L0Call, readResponse = params::decrypt) { id ->
|
||||||
|
requestId = id
|
||||||
|
params.encodeMessage(ProtectedMessage(ProtectedKind.CALL, id.toULong(), priority, call))
|
||||||
|
}
|
||||||
|
} catch (e: CancellationException) { throw e }
|
||||||
|
catch (e: RemoteInterface.ClosedException) { throw e }
|
||||||
|
catch (e: RemoteInterface.SecurityException) {
|
||||||
|
transport.abortSecurity()
|
||||||
|
throw e
|
||||||
|
}
|
||||||
|
val frame: ProtectedMessage
|
||||||
|
val block: Transport.Block
|
||||||
|
try {
|
||||||
|
frame = unpack(encoded)
|
||||||
|
if (frame.correlation != requestId.toULong() || frame.priority != priority)
|
||||||
|
throw RemoteInterface.SecurityException("authenticated response routing mismatch")
|
||||||
|
block = unpack(frame.payload)
|
||||||
|
when (block) {
|
||||||
|
is Transport.Block.Response -> if (frame.kind != ProtectedKind.RESPONSE || block.forId != 0u)
|
||||||
|
throw RemoteInterface.SecurityException("invalid response kind")
|
||||||
|
is Transport.Block.Error -> if (frame.kind != ProtectedKind.ERROR || block.forId != 0u)
|
||||||
|
throw RemoteInterface.SecurityException("invalid error kind")
|
||||||
|
else -> throw RemoteInterface.SecurityException("unexpected response frame")
|
||||||
|
}
|
||||||
|
} catch (e: Throwable) {
|
||||||
|
transport.abortSecurity()
|
||||||
|
throw RemoteInterface.SecurityException("invalid authenticated response")
|
||||||
|
}
|
||||||
return when (block) {
|
return when (block) {
|
||||||
is Transport.Block.Response -> {
|
is Transport.Block.Response -> cmd.unpackResult(block.packedResult)
|
||||||
cmd.unpackResult(block.packedResult)
|
|
||||||
}
|
|
||||||
|
|
||||||
is Transport.Block.Error -> clientInterface.decodeAndThrow(block)
|
is Transport.Block.Error -> clientInterface.decodeAndThrow(block)
|
||||||
else -> throw RemoteInterface.Exception("unexpected block type: $block")
|
else -> error("unreachable")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
override suspend fun <A> push(cmd: Command<A, Unit>, args: A) {
|
||||||
|
val params = deferredParams.await()
|
||||||
|
val priority = currentCoroutineContext()[CallPriority]?.value ?: 0
|
||||||
|
val payload = cmd.packCall(args)
|
||||||
|
(params.transport as Transport<*>).pushPrepared(L0Call.name, priority) {
|
||||||
|
params.encodeMessage(ProtectedMessage(ProtectedKind.PUSH, 0uL, priority, payload))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1,3 +1,13 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2025. Sergey S. Chernov - All Rights Reserved
|
||||||
|
*
|
||||||
|
* You may use, distribute and modify this code under the
|
||||||
|
* terms of the private license, which you must obtain from the author
|
||||||
|
*
|
||||||
|
* To obtain the license, contact the author: https://t.me/real_sergeych or email to
|
||||||
|
* real dot sergeych at gmail.
|
||||||
|
*/
|
||||||
|
|
||||||
package net.sergeych.kiloparsec
|
package net.sergeych.kiloparsec
|
||||||
|
|
||||||
import net.sergeych.crypto2.SigningKey
|
import net.sergeych.crypto2.SigningKey
|
||||||
|
|||||||
@@ -1,10 +1,19 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2025-2026. Sergey S. Chernov - All Rights Reserved
|
||||||
|
*
|
||||||
|
* You may use, distribute and modify this code under the
|
||||||
|
* terms of the private license, which you must obtain from the author
|
||||||
|
*
|
||||||
|
* To obtain the license, contact the author: https://t.me/real_sergeych or email to
|
||||||
|
* real dot sergeych at gmail.
|
||||||
|
*/
|
||||||
|
|
||||||
package net.sergeych.kiloparsec
|
package net.sergeych.kiloparsec
|
||||||
|
|
||||||
import kotlinx.coroutines.CancellationException
|
import kotlinx.coroutines.CancellationException
|
||||||
import kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import net.sergeych.crypto2.SigningKey
|
import net.sergeych.crypto2.SigningKey
|
||||||
import net.sergeych.kiloparsec.adapter.InetTransportDevice
|
|
||||||
import net.sergeych.mp_logger.LogTag
|
import net.sergeych.mp_logger.LogTag
|
||||||
import net.sergeych.mp_logger.debug
|
import net.sergeych.mp_logger.debug
|
||||||
import net.sergeych.mp_logger.exception
|
import net.sergeych.mp_logger.exception
|
||||||
@@ -13,10 +22,97 @@ import net.sergeych.mp_tools.globalLaunch
|
|||||||
import net.sergeych.tools.AtomicCounter
|
import net.sergeych.tools.AtomicCounter
|
||||||
|
|
||||||
private val instances = AtomicCounter()
|
private val instances = AtomicCounter()
|
||||||
@Suppress("unused")
|
|
||||||
|
/**
|
||||||
|
* The Kiloparsec server.
|
||||||
|
* Server accepts incoming connections and serves them using the same [clientInterface].
|
||||||
|
*
|
||||||
|
* ## Incoming connections
|
||||||
|
*
|
||||||
|
* Server collecting incoming connections provided by [connections] `Flow`. For each incoming connection
|
||||||
|
* the Kiloparsec handshake is performed, then the session object is created, see below, and connection is
|
||||||
|
* served with [clientInterface] until closed.
|
||||||
|
*
|
||||||
|
* ## Session param [S]
|
||||||
|
*
|
||||||
|
* After the successful handshake server creates new session for each connection calling the [sessionBuilder].
|
||||||
|
* Then it creates a [KiloScope] so [KiloScope.session] holds this connection-specific instance. Then
|
||||||
|
* [KiloInterface.onConnected] is called with this scope. Session can be used to hold connection state. Session
|
||||||
|
* objects are not persistent, but could be initialized in [KiloInterface.onConnected] where the remote side
|
||||||
|
* [KiloScope.remoteIdentity] is already verified and set.
|
||||||
|
*
|
||||||
|
* ## Usage:
|
||||||
|
*
|
||||||
|
* Create a shared library between you server and clients, to specify the interface (otherwise you can
|
||||||
|
* share sources).
|
||||||
|
*
|
||||||
|
* Suppose we have session with a state:
|
||||||
|
* ```kotlin
|
||||||
|
* data class Session(
|
||||||
|
* var data: String,
|
||||||
|
* )
|
||||||
|
*```
|
||||||
|
*
|
||||||
|
* And some commands to access and change it, in the shared library too:
|
||||||
|
*
|
||||||
|
* ```kotlin
|
||||||
|
* val cmdSave by command<String, Unit>()
|
||||||
|
* val cmdLoad by command<Unit, String>()
|
||||||
|
* val cmdDrop by command<Unit, Unit>()
|
||||||
|
* val cmdException by command<Unit, Unit>()
|
||||||
|
* ```
|
||||||
|
* Then the server code (TCP/IP variant) could look like:
|
||||||
|
*
|
||||||
|
* ```kotlin
|
||||||
|
* // The server implementation (could be shared between server instances connected
|
||||||
|
* // to different protocol adapters):
|
||||||
|
*
|
||||||
|
* val cli = KiloInterface<Session>().apply {
|
||||||
|
* // Suppose we want to throw this exception at the caller site, so we need to register it:
|
||||||
|
* registerError { SomeException() }
|
||||||
|
*
|
||||||
|
* // Session initialization. If you need a sessino to depend initially on the client's identity.
|
||||||
|
* // you can do it here:
|
||||||
|
* onConnected {
|
||||||
|
* // check the remoteIdentity
|
||||||
|
* session.data = if( remoteIdentity == somePublicVerifyingKey )
|
||||||
|
* "known"
|
||||||
|
* else
|
||||||
|
* "unknown"
|
||||||
|
* }
|
||||||
|
* on(cmdSave) { session.data = it }
|
||||||
|
* on(cmdLoad) {
|
||||||
|
* session.data
|
||||||
|
* }
|
||||||
|
* on(cmdException) {
|
||||||
|
* throw TestException()
|
||||||
|
* }
|
||||||
|
* on(cmdDrop) {
|
||||||
|
* throw LocalInterface.BreakConnectionException()
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* // Create the server instance that accepts incoming TCP/IP connections on all local interfaces using the
|
||||||
|
* // specified port:
|
||||||
|
*
|
||||||
|
* val server = KiloServer(cli, acceptTcpDevice(port)) {
|
||||||
|
* // This creates a new session
|
||||||
|
* Session("unknown")
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* See [KiloClient] to connect to the server.
|
||||||
|
*
|
||||||
|
* @param S the type of the server session object, returned by [sessionBuilder]. See above
|
||||||
|
* @param clientInterface the interface available for remote calls
|
||||||
|
* @param connections flow of incoming connections. Server stops when the flow is fully collected (normally
|
||||||
|
* it shouldn't)
|
||||||
|
* @param serverSecretKey the [SigningKey] used to identify this server during Kiloparsec handshake.
|
||||||
|
* @param sessionBuilder callback that creates session objects for successful incoming connections
|
||||||
|
*/
|
||||||
class KiloServer<S>(
|
class KiloServer<S>(
|
||||||
private val clientInterface: KiloInterface<S>,
|
private val clientInterface: KiloInterface<S>,
|
||||||
private val connections: Flow<InetTransportDevice>,
|
private val connections: Flow<Transport.Device>,
|
||||||
private val serverSecretKey: SigningKey? = null,
|
private val serverSecretKey: SigningKey? = null,
|
||||||
private val sessionBuilder: () -> S,
|
private val sessionBuilder: () -> S,
|
||||||
) : LogTag("KS:${instances.incrementAndGet()}") {
|
) : LogTag("KS:${instances.incrementAndGet()}") {
|
||||||
@@ -29,20 +125,28 @@ class KiloServer<S>(
|
|||||||
KiloServerConnection(clientInterface, device, sessionBuilder(), serverSecretKey)
|
KiloServerConnection(clientInterface, device, sessionBuilder(), serverSecretKey)
|
||||||
.apply { debug { "server connection is ready" } }
|
.apply { debug { "server connection is ready" } }
|
||||||
.run()
|
.run()
|
||||||
}
|
} catch (_: CancellationException) {
|
||||||
catch(_: CancellationException) {
|
} catch (cce: LocalInterface.BreakConnectionException) {
|
||||||
}
|
|
||||||
catch(cce: LocalInterface.BreakConnectionException) {
|
|
||||||
info { "Closed exception caught, closing (${cce.flushSendQueue}" }
|
info { "Closed exception caught, closing (${cce.flushSendQueue}" }
|
||||||
}
|
} catch (t: Throwable) {
|
||||||
catch (t: Throwable) {
|
|
||||||
exception { "unexpected while creating kiloclient" to t }
|
exception { "unexpected while creating kiloclient" to t }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stop the server and cancel all pending sessions. Unlike finishing the flow passed
|
||||||
|
* for [KiloServer.connections], it will cancel all currently active sessions.
|
||||||
|
*/
|
||||||
fun close() {
|
fun close() {
|
||||||
job.cancel()
|
job.cancel()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Server is closed either if [close] was called or all [KiloServer.connections] were collected and flow was
|
||||||
|
* closed.
|
||||||
|
*/
|
||||||
|
@Suppress("unused")
|
||||||
|
val isClosed: Boolean get() = job.isCompleted
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,18 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2025. Sergey S. Chernov - All Rights Reserved
|
||||||
|
*
|
||||||
|
* You may use, distribute and modify this code under the
|
||||||
|
* terms of the private license, which you must obtain from the author
|
||||||
|
*
|
||||||
|
* To obtain the license, contact the author: https://t.me/real_sergeych or email to
|
||||||
|
* real dot sergeych at gmail.
|
||||||
|
*/
|
||||||
|
|
||||||
package net.sergeych.kiloparsec
|
package net.sergeych.kiloparsec
|
||||||
|
|
||||||
import kotlinx.coroutines.CompletableDeferred
|
import kotlinx.coroutines.CompletableDeferred
|
||||||
|
import kotlinx.coroutines.sync.Mutex
|
||||||
|
import kotlinx.coroutines.sync.withLock
|
||||||
import net.sergeych.crypto2.SafeKeyExchange
|
import net.sergeych.crypto2.SafeKeyExchange
|
||||||
import net.sergeych.crypto2.SigningKey
|
import net.sergeych.crypto2.SigningKey
|
||||||
import net.sergeych.mp_logger.LogTag
|
import net.sergeych.mp_logger.LogTag
|
||||||
@@ -43,55 +55,66 @@ class KiloServerConnection<S>(
|
|||||||
suspend fun run() {
|
suspend fun run() {
|
||||||
val deferredParams = CompletableDeferred<KiloParams<S>>()
|
val deferredParams = CompletableDeferred<KiloParams<S>>()
|
||||||
val deferredTransport = CompletableDeferred<Transport<*>>()
|
val deferredTransport = CompletableDeferred<Transport<*>>()
|
||||||
|
var connectedScope: KiloScope<S>? = null
|
||||||
|
|
||||||
val l0Interface = KiloL0Interface(clientInterface, deferredParams).apply {
|
val l0Interface = KiloL0Interface(clientInterface, deferredParams).apply {
|
||||||
var params: KiloParams<S>? = null
|
var params: KiloParams<S>? = null
|
||||||
on(L0Request) {
|
val handshakeLock = Mutex()
|
||||||
val sk = pair.serverSessionKey(it.publicKey)
|
var established = false
|
||||||
|
val pair = SafeKeyExchange()
|
||||||
|
on(L0Request) { request -> handshakeLock.withLock {
|
||||||
|
if (request.version != KILO_PROTOCOL_VERSION || params != null || established)
|
||||||
|
throw RemoteInterface.SecurityException("unsupported or repeated handshake")
|
||||||
|
val sk = pair.serverSessionKey(request.publicKey)
|
||||||
|
params = KiloParams(true, deferredTransport.await(), sk, session, null, this@KiloServerConnection)
|
||||||
|
Handshake(KILO_PROTOCOL_VERSION, pair.publicKey,
|
||||||
|
serverSigningKey?.seal(serverAuthentication(params!!.token)))
|
||||||
|
} }
|
||||||
|
|
||||||
params = KiloParams(
|
onPrepared(L0ClientId) { encoded -> handshakeLock.withLock {
|
||||||
true,
|
var p = params ?: throw RemoteInterface.SecurityException("wrong handshake sequence")
|
||||||
deferredTransport.await(),
|
val identity = p.decrypt(encoded)
|
||||||
sk,
|
if (established) throw RemoteInterface.SecurityException("repeated client identity")
|
||||||
session,
|
val ci = unpack<ClientIdentity>(identity)
|
||||||
null,
|
if ((ci.clientIdKey == null) != (ci.signature == null))
|
||||||
this@KiloServerConnection
|
throw RemoteInterface.SecurityException("incomplete client identity")
|
||||||
)
|
|
||||||
Handshake(1u, pair.publicKey, serverSigningKey?.seal(params!!.token))
|
|
||||||
}
|
|
||||||
|
|
||||||
on(L0ClientId) {
|
|
||||||
var p = params ?: throw RemoteInterface.ClosedException("wrong handshake sequence")
|
|
||||||
val ci = unpack<ClientIdentity>(p.decrypt(it))
|
|
||||||
if (ci.clientIdKey != null) {
|
if (ci.clientIdKey != null) {
|
||||||
if( ci.signature == null )
|
if (!ci.clientIdKey.verify(ci.signature!!, clientAuthentication(p.token)))
|
||||||
throw RemoteInterface.SecurityException("missing signature")
|
|
||||||
if( !ci.clientIdKey.verify(ci.signature, params!!.token))
|
|
||||||
throw RemoteInterface.SecurityException("wrong signature")
|
throw RemoteInterface.SecurityException("wrong signature")
|
||||||
p = p.copy(remoteIdentity = ci.clientIdKey)
|
p = p.authenticated(ci.clientIdKey)
|
||||||
params = p
|
params = p
|
||||||
}
|
}
|
||||||
|
established = true
|
||||||
deferredParams.complete(p)
|
deferredParams.complete(p)
|
||||||
kiloRemoteInterface.complete(
|
kiloRemoteInterface.complete(KiloRemoteInterface(deferredParams, clientInterface))
|
||||||
KiloRemoteInterface(deferredParams, clientInterface)
|
connectedScope = p.scope
|
||||||
)
|
clientInterface.onConnectHandlers.invokeAll(connectedScope)
|
||||||
clientInterface.onConnectHandler?.invoke(p.scope)
|
PreparedPayload {
|
||||||
|
val result = p.encodeMessage(ProtectedMessage(ProtectedKind.SERVER_FINISHED, 0uL, 0, identity))
|
||||||
|
OutgoingData(net.sergeych.utools.pack(result.bytes), result.nonce)
|
||||||
}
|
}
|
||||||
|
} }
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
val transport = Transport(device, l0Interface, Unit)
|
val transport = Transport(device, l0Interface, Unit)
|
||||||
deferredTransport.complete(transport)
|
deferredTransport.complete(transport)
|
||||||
kiloRemoteInterface.complete(KiloRemoteInterface(deferredParams,clientInterface))
|
kiloRemoteInterface.complete(KiloRemoteInterface(deferredParams,clientInterface))
|
||||||
debug { "starting the transport"}
|
debug { "starting the transport"}
|
||||||
|
try {
|
||||||
transport.run()
|
transport.run()
|
||||||
debug { "server transport finished" }
|
debug { "server transport finished" }
|
||||||
|
} finally {
|
||||||
|
connectedScope?.let { clientInterface.onDisconnectHandlers.invokeAll(it) }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
companion object {
|
|
||||||
val pair = SafeKeyExchange()
|
|
||||||
}
|
|
||||||
|
|
||||||
override suspend fun <A, R> call(cmd: Command<A, R>, args: A): R {
|
override suspend fun <A, R> call(cmd: Command<A, R>, args: A): R {
|
||||||
return kiloRemoteInterface.await().call(cmd, args)
|
return kiloRemoteInterface.await().call(cmd, args)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
override suspend fun <A> push(cmd: Command<A, Unit>, args: A) {
|
||||||
|
kiloRemoteInterface.await().push(cmd, args)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,3 +1,13 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2025. Sergey S. Chernov - All Rights Reserved
|
||||||
|
*
|
||||||
|
* You may use, distribute and modify this code under the
|
||||||
|
* terms of the private license, which you must obtain from the author
|
||||||
|
*
|
||||||
|
* To obtain the license, contact the author: https://t.me/real_sergeych or email to
|
||||||
|
* real dot sergeych at gmail.
|
||||||
|
*/
|
||||||
|
|
||||||
package net.sergeych.kiloparsec
|
package net.sergeych.kiloparsec
|
||||||
|
|
||||||
import net.sergeych.mp_logger.LogTag
|
import net.sergeych.mp_logger.LogTag
|
||||||
@@ -6,6 +16,7 @@ import net.sergeych.mp_logger.exception
|
|||||||
import net.sergeych.mp_logger.info
|
import net.sergeych.mp_logger.info
|
||||||
import net.sergeych.tools.AtomicCounter
|
import net.sergeych.tools.AtomicCounter
|
||||||
import net.sergeych.utools.firstNonNull
|
import net.sergeych.utools.firstNonNull
|
||||||
|
import net.sergeych.utools.unpack
|
||||||
import kotlin.reflect.KClass
|
import kotlin.reflect.KClass
|
||||||
|
|
||||||
private typealias RawCommandHandler<C> = suspend (C, UByteArray) -> UByteArray
|
private typealias RawCommandHandler<C> = suspend (C, UByteArray) -> UByteArray
|
||||||
@@ -62,19 +73,38 @@ open class LocalInterface<S> : Loggable by LogTag("LocalInterface${idCounter.inc
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun execute(
|
/** Override to gate dispatch before command lookup and argument deserialization. */
|
||||||
|
open suspend fun execute(
|
||||||
scope: S,
|
scope: S,
|
||||||
name: String,
|
name: String,
|
||||||
packedArgs: UByteArray,
|
packedArgs: UByteArray,
|
||||||
): UByteArray =
|
): UByteArray =
|
||||||
(commands[name] ?: throw RemoteInterface.UnknownCommand())
|
(commands[name] ?: throw RemoteInterface.UnknownCommand(name))
|
||||||
.invoke(scope, packedArgs)
|
.invoke(scope, packedArgs)
|
||||||
|
|
||||||
|
|
||||||
|
private val preparedHandlers = mutableMapOf<String, suspend (S, UByteArray) -> PreparedPayload>()
|
||||||
|
|
||||||
|
/** Secure handshake replies can defer sealing until atomic outgoing admission. */
|
||||||
|
internal fun <A> onPrepared(command: Command<A, UByteArray>, handler: suspend S.(A) -> PreparedPayload) {
|
||||||
|
preparedHandlers[command.name] = { scope, args -> scope.handler(unpack(command.argsSerializer, args)) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Dispatch now; encode/seal the result later under the outgoing admission mutex. */
|
||||||
|
internal open suspend fun executeTransportBlock(scope: S, block: Transport.Block.Call): PreparedPayload {
|
||||||
|
preparedHandlers[block.name]?.let { return it(scope, block.packedArgs) }
|
||||||
|
val result = execute(scope, block.name, block.packedArgs)
|
||||||
|
return PreparedPayload { OutgoingData(result) }
|
||||||
|
}
|
||||||
|
|
||||||
private val errorByClass = mutableMapOf<KClass<*>, String>()
|
private val errorByClass = mutableMapOf<KClass<*>, String>()
|
||||||
private val errorBuilder = mutableMapOf<String, (String, UByteArray?) -> Throwable>()
|
private val errorBuilder = mutableMapOf<String, (String, UByteArray?) -> Throwable>()
|
||||||
|
|
||||||
fun <T : Throwable> registerError(
|
/**
|
||||||
|
* Register exception for automatic transmission over the kiloparsec connection using its [klass]
|
||||||
|
* and possibly override code. In most cases it is simpler to use [registerError].
|
||||||
|
*/
|
||||||
|
fun <T : Throwable> registerErrorClass(
|
||||||
klass: KClass<T>, code: String = klass.simpleName!!,
|
klass: KClass<T>, code: String = klass.simpleName!!,
|
||||||
exceptionBuilder: (String, UByteArray?) -> T,
|
exceptionBuilder: (String, UByteArray?) -> T,
|
||||||
) {
|
) {
|
||||||
@@ -82,10 +112,17 @@ open class LocalInterface<S> : Loggable by LogTag("LocalInterface${idCounter.inc
|
|||||||
errorBuilder[code] = exceptionBuilder
|
errorBuilder[code] = exceptionBuilder
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Register an exception to be transmitted automatically over the kiloparsec connection.
|
||||||
|
* Example:
|
||||||
|
* ```kotlin
|
||||||
|
* localInterface.registerError { IllegalArgumentException(it) }
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
inline fun <reified T : Throwable> registerError(
|
inline fun <reified T : Throwable> registerError(
|
||||||
noinline exceptionBuilder: (String) -> T,
|
noinline exceptionBuilder: (String) -> T,
|
||||||
) {
|
) {
|
||||||
registerError(T::class) { msg, _ -> exceptionBuilder(msg) }
|
registerErrorClass(T::class) { msg, _ -> exceptionBuilder(msg) }
|
||||||
}
|
}
|
||||||
|
|
||||||
val errorProviders = mutableListOf<LocalInterface<*>>()
|
val errorProviders = mutableListOf<LocalInterface<*>>()
|
||||||
@@ -95,7 +132,8 @@ open class LocalInterface<S> : Loggable by LogTag("LocalInterface${idCounter.inc
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun getErrorCode(t: Throwable): String? =
|
fun getErrorCode(t: Throwable): String? =
|
||||||
errorByClass[t::class] ?: errorProviders.firstNonNull { it.getErrorCode(t) }
|
(t as? ExceptionWithCode)?.code
|
||||||
|
?: errorByClass[t::class] ?: errorProviders.firstNonNull { it.getErrorCode(t) }
|
||||||
|
|
||||||
fun encodeError(forId: UInt, t: Throwable): Transport.Block.Error =
|
fun encodeError(forId: UInt, t: Throwable): Transport.Block.Error =
|
||||||
if (t is RemoteInterface.ClosedException) {
|
if (t is RemoteInterface.ClosedException) {
|
||||||
|
|||||||
@@ -1,3 +1,13 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2025. Sergey S. Chernov - All Rights Reserved
|
||||||
|
*
|
||||||
|
* You may use, distribute and modify this code under the
|
||||||
|
* terms of the private license, which you must obtain from the author
|
||||||
|
*
|
||||||
|
* To obtain the license, contact the author: https://t.me/real_sergeych or email to
|
||||||
|
* real dot sergeych at gmail.
|
||||||
|
*/
|
||||||
|
|
||||||
package net.sergeych.kiloparsec
|
package net.sergeych.kiloparsec
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -40,14 +50,37 @@ interface RemoteInterface {
|
|||||||
/**
|
/**
|
||||||
* Command is not supported by the remote party
|
* Command is not supported by the remote party
|
||||||
*/
|
*/
|
||||||
class UnknownCommand : RemoteException("UnknownCommand")
|
class UnknownCommand(commandName: String) : RemoteException("UnknownCommand: $commandName")
|
||||||
|
|
||||||
open class InternalError(code: String="0"): RemoteException("Internal error: $code")
|
open class InternalError(code: String="0"): RemoteException("Internal error: $code")
|
||||||
|
|
||||||
suspend fun <R> call(cmd: Command<Unit, R>): R = call(cmd, Unit)
|
suspend fun <R> call(cmd: Command<Unit, R>): R = call(cmd, Unit)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Call the remote procedure with specified args and return its result
|
* Call the remote procedure with specified [args] and return its result of type [R]. The calling coroutine
|
||||||
|
* suspends until the request is performed on the remote side and the result value (also `Unit`) will be received.
|
||||||
|
*
|
||||||
|
* When it is not necessary to wait for the return value and/or command execution, it is recommended to
|
||||||
|
* use [push] instead.
|
||||||
|
*
|
||||||
|
* @throws RemoteException if the execution caused exception on the remote size
|
||||||
|
* @throws Exception for registered exceptions, see [LocalInterface.registerError], etc.
|
||||||
*/
|
*/
|
||||||
suspend fun <A, R> call(cmd: Command<A, R>, args: A): R
|
suspend fun <A, R> call(cmd: Command<A, R>, args: A): R
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Push the notification without waiting for reception or processing.
|
||||||
|
* It returns immediately after sending data to the transport (e.g., to the network).
|
||||||
|
* Use [call] if it is necessary to wait until the command will be received and processed by the remote.
|
||||||
|
*
|
||||||
|
* Push is onlu available for commands without returned value.
|
||||||
|
*/
|
||||||
|
suspend fun <A> push(cmd: Command<A, Unit>, args: A)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Push the command with no args.
|
||||||
|
* It returns immediately after sending data to the transport (e.g., to the network).
|
||||||
|
* Use [call] if it is necessary to wait until the command will be received and processed by the remote.
|
||||||
|
*/
|
||||||
|
suspend fun push(cmd: Command<Unit,Unit>) = push(cmd,Unit)
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
package net.sergeych.kiloparsec
|
||||||
|
|
||||||
|
internal const val REPLAY_WINDOW_SIZE = 4096
|
||||||
|
internal const val MAX_NONCE_OVERTAKING = REPLAY_WINDOW_SIZE * 2 / 3
|
||||||
|
|
||||||
|
/** A packet disposition, not a session failure. Never dispatched or replied to. */
|
||||||
|
internal class DiscardPacket : RuntimeException("Duplicate or stale encrypted packet")
|
||||||
|
|
||||||
|
/** Fixed circular bitmap. Callers serialize check/authenticate/record as one operation. */
|
||||||
|
internal class ReplayWindow {
|
||||||
|
private val bits = LongArray(REPLAY_WINDOW_SIZE / 64)
|
||||||
|
private var highest: ULong? = null
|
||||||
|
fun copy(): ReplayWindow = ReplayWindow().also {
|
||||||
|
bits.copyInto(it.bits)
|
||||||
|
it.highest = highest
|
||||||
|
}
|
||||||
|
private fun index(n: ULong) = (n % REPLAY_WINDOW_SIZE.toULong()).toInt()
|
||||||
|
fun containsOrStale(n: ULong): Boolean {
|
||||||
|
val h = highest ?: return false
|
||||||
|
if (n > h) return false
|
||||||
|
if (h - n >= REPLAY_WINDOW_SIZE.toULong()) return true
|
||||||
|
val i = index(n)
|
||||||
|
return bits[i / 64] and (1L shl (i % 64)) != 0L
|
||||||
|
}
|
||||||
|
fun record(n: ULong) {
|
||||||
|
val h = highest
|
||||||
|
if (h == null || n > h) {
|
||||||
|
if (h == null || n - h >= REPLAY_WINDOW_SIZE.toULong()) bits.fill(0)
|
||||||
|
else {
|
||||||
|
// Clear only newly entered positions, not every remembered nonce.
|
||||||
|
var next = h
|
||||||
|
repeat((n - h).toInt()) {
|
||||||
|
val i = index(++next)
|
||||||
|
bits[i / 64] = bits[i / 64] and (1L shl (i % 64)).inv()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
highest = n
|
||||||
|
}
|
||||||
|
val i = index(n)
|
||||||
|
bits[i / 64] = bits[i / 64] or (1L shl (i % 64))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Local-only metadata; does not change wire encoding. */
|
||||||
|
internal data class OutgoingData(val bytes: UByteArray, val nonce: ULong? = null)
|
||||||
|
internal fun interface PreparedPayload { fun encode(): OutgoingData }
|
||||||
|
internal class UnauthenticatedOuterError : RemoteInterface.SecurityException("Unauthenticated outer error")
|
||||||
@@ -1,3 +1,13 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2025. Sergey S. Chernov - All Rights Reserved
|
||||||
|
*
|
||||||
|
* You may use, distribute and modify this code under the
|
||||||
|
* terms of the private license, which you must obtain from the author
|
||||||
|
*
|
||||||
|
* To obtain the license, contact the author: https://t.me/real_sergeych or email to
|
||||||
|
* real dot sergeych at gmail.
|
||||||
|
*/
|
||||||
|
|
||||||
package net.sergeych.kiloparsec
|
package net.sergeych.kiloparsec
|
||||||
|
|
||||||
import kotlinx.coroutines.*
|
import kotlinx.coroutines.*
|
||||||
@@ -15,14 +25,14 @@ import kotlinx.serialization.descriptors.SerialDescriptor
|
|||||||
import kotlinx.serialization.encoding.Decoder
|
import kotlinx.serialization.encoding.Decoder
|
||||||
import kotlinx.serialization.encoding.Encoder
|
import kotlinx.serialization.encoding.Encoder
|
||||||
import kotlinx.serialization.serializer
|
import kotlinx.serialization.serializer
|
||||||
import net.sergeych.crypto2.toDump
|
import net.sergeych.bipack.Unsigned
|
||||||
import net.sergeych.kiloparsec.Transport.Device
|
import net.sergeych.kiloparsec.adapter.PriorityBlockWriter
|
||||||
import net.sergeych.mp_logger.*
|
import net.sergeych.mp_logger.*
|
||||||
import net.sergeych.utools.pack
|
import net.sergeych.utools.pack
|
||||||
import net.sergeych.utools.unpack
|
import net.sergeych.utools.unpack
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Divan channel that operates some block [Device] exporting a given [localInterface]
|
* Kiloparsec channel that operates some block [Device] exporting a given [localInterface]
|
||||||
* to remote callers. [LocalInterface] allows session managing, transmitting exceptions
|
* to remote callers. [LocalInterface] allows session managing, transmitting exceptions
|
||||||
* in a scure and multiplatform way and provide local command execution (typed RPC)
|
* in a scure and multiplatform way and provide local command execution (typed RPC)
|
||||||
*/
|
*/
|
||||||
@@ -58,12 +68,25 @@ class Transport<S>(
|
|||||||
suspend fun close()
|
suspend fun close()
|
||||||
|
|
||||||
suspend fun flush() {}
|
suspend fun flush() {}
|
||||||
|
|
||||||
|
/** Adapter admission; legacy devices retain their existing output-channel behavior. */
|
||||||
|
suspend fun send(block: UByteArray) { output.send(block) }
|
||||||
}
|
}
|
||||||
|
|
||||||
@Serializable(TransportBlockSerializer::class)
|
@Serializable(TransportBlockSerializer::class)
|
||||||
sealed class Block {
|
sealed class Block {
|
||||||
|
// Kept outside the legacy generated body serializer. Only the outer custom
|
||||||
|
// serializer appends it, so old field positions and constructors stay intact.
|
||||||
|
@kotlinx.serialization.Transient
|
||||||
|
var priority: Int = 0
|
||||||
|
|
||||||
@Serializable
|
@Serializable
|
||||||
data class Call(val id: UInt, val name: String, val packedArgs: UByteArray) : Block() {
|
data class Call(
|
||||||
|
@Unsigned
|
||||||
|
val id: UInt,
|
||||||
|
val name: String,
|
||||||
|
val packedArgs: UByteArray
|
||||||
|
) : Block() {
|
||||||
override fun equals(other: Any?): Boolean {
|
override fun equals(other: Any?): Boolean {
|
||||||
if (this === other) return true
|
if (this === other) return true
|
||||||
if (other !is Call) return false
|
if (other !is Call) return false
|
||||||
@@ -83,52 +106,123 @@ class Transport<S>(
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Serializable
|
@Serializable
|
||||||
data class Response(val forId: UInt, val packedResult: UByteArray) : Block()
|
data class Response(@Unsigned val forId: UInt, val packedResult: UByteArray) : Block()
|
||||||
|
|
||||||
@Serializable
|
@Serializable
|
||||||
data class Error(val forId: UInt, val code: String, val text: String? = null, val extra: UByteArray? = null) :
|
data class Error(@Unsigned val forId: UInt, val code: String, val text: String? = null, val extra: UByteArray? = null) :
|
||||||
Block() {
|
Block() {
|
||||||
val message by lazy { text ?: "remote exception: $code" }
|
val message by lazy { text ?: "remote exception: $code" }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private val outgoing = Mutex()
|
||||||
|
private val writerReady = CompletableDeferred<PriorityBlockWriter>()
|
||||||
|
private val responseReaders = mutableMapOf<UInt, (UByteArray) -> UByteArray>()
|
||||||
private val access = Mutex()
|
private val access = Mutex()
|
||||||
private var lastId = 0u
|
private var lastId = 0u
|
||||||
private val calls = mutableMapOf<UInt, CompletableDeferred<UByteArray>>()
|
private val calls = mutableMapOf<UInt, CompletableDeferred<UByteArray>>()
|
||||||
var isClosed: Boolean = false
|
var isClosed: Boolean = false
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Send a call block for a command and packed args and return packed result if it is not an error
|
* Send a call block for a command and packed args and return packed result if it is not an error. It suspends
|
||||||
|
* until receiving answer from the remote side, even if returns `Unit`.
|
||||||
* @throws RemoteInterface.RemoteException if the remote call caused an exception. Normally use [call] instead.
|
* @throws RemoteInterface.RemoteException if the remote call caused an exception. Normally use [call] instead.
|
||||||
* @throws RemoteInterface.ClosedException
|
* @throws RemoteInterface.ClosedException
|
||||||
*/
|
*/
|
||||||
private suspend fun sendCallBlock(name: String, packedArgs: UByteArray): UByteArray {
|
private suspend fun sendCallBlock(name: String, packedArgs: UByteArray): UByteArray =
|
||||||
|
sendBoundCallBlock(name) { OutgoingData(packedArgs) }
|
||||||
|
|
||||||
|
/** Allocate the outer ID before sealing its authenticated inner counterpart. */
|
||||||
|
private suspend fun sendBoundCallBlock(
|
||||||
|
name: String,
|
||||||
|
readResponse: ((UByteArray) -> UByteArray)? = null,
|
||||||
|
packedArgs: (UInt) -> OutgoingData,
|
||||||
|
): UByteArray {
|
||||||
if (isClosed) throw RemoteInterface.ClosedException()
|
if (isClosed) throw RemoteInterface.ClosedException()
|
||||||
|
|
||||||
val b: Block
|
val id: UInt
|
||||||
|
val priority = currentCoroutineContext()[CallPriority]?.value ?: 0
|
||||||
val deferred = CompletableDeferred<UByteArray>()
|
val deferred = CompletableDeferred<UByteArray>()
|
||||||
|
|
||||||
// We need to shield calls and lastID with mutex, but nothing more:
|
// We need to shield calls and lastID with mutex, but nothing more:
|
||||||
access.withLock {
|
access.withLock {
|
||||||
if (isClosed) throw RemoteInterface.ClosedException()
|
if (isClosed) throw RemoteInterface.ClosedException()
|
||||||
b = Block.Call(++lastId, name, packedArgs)
|
// the order is important: first id in use MUST BE >= 1, not zero:
|
||||||
calls[b.id] = deferred
|
if (lastId == UInt.MAX_VALUE) throw RemoteInterface.ClosedException("RPC ID space exhausted")
|
||||||
|
id = ++lastId
|
||||||
|
calls[id] = deferred
|
||||||
|
if (readResponse != null) responseReaders[id] = readResponse
|
||||||
}
|
}
|
||||||
|
|
||||||
// now we have mutex freed so we can call:
|
// Suspend on actual channel backpressure; never poll or delay a successful send.
|
||||||
val r = runCatching { device.output.send(pack(b).also { debug { ">>>\n${it.toDump()}" } }) }
|
try {
|
||||||
if (!r.isSuccess) {
|
sendPrepared {
|
||||||
r.exceptionOrNull()?.let {
|
val payload = packedArgs(id)
|
||||||
exception { "failed to send output block" to it }
|
OutgoingData(pack<Block>(Block.Call(id, name, payload.bytes).also { it.priority = priority }), payload.nonce)
|
||||||
} ?: run {
|
|
||||||
error { "It should not happen: empty exception on block send failure" }
|
|
||||||
throw RuntimeException("unexpected failure in sending block")
|
|
||||||
}
|
}
|
||||||
deferred.completeExceptionally(RemoteInterface.ClosedException())
|
|
||||||
}
|
|
||||||
|
|
||||||
// it returns packed result or throws a proper error:
|
|
||||||
return deferred.await()
|
return deferred.await()
|
||||||
|
} catch (_: ClosedSendChannelException) {
|
||||||
|
throw RemoteInterface.ClosedException()
|
||||||
|
} finally {
|
||||||
|
// Cancellation must not retain a response waiter for the connection lifetime.
|
||||||
|
withContext(NonCancellable) { access.withLock { calls.remove(id); responseReaders.remove(id) } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send a call block for a command and packed args and return packed result if it is not an error. It suspends
|
||||||
|
* until receiving answer from the remote side, even if returns `Unit`.
|
||||||
|
* @throws RemoteInterface.RemoteException if the remote call caused an exception. Normally use [call] instead.
|
||||||
|
* @throws RemoteInterface.ClosedException
|
||||||
|
*/
|
||||||
|
private suspend fun sendPushBlock(name: String, packedArgs: UByteArray) {
|
||||||
|
if (isClosed) throw RemoteInterface.ClosedException()
|
||||||
|
|
||||||
|
// All push blocks have the same id == 0:
|
||||||
|
val b = Block.Call(0u, name, packedArgs).also { it.priority = currentCoroutineContext()[CallPriority]?.value ?: 0 }
|
||||||
|
val r = runCatching { send(b) }
|
||||||
|
when(val e = r.exceptionOrNull()) {
|
||||||
|
null -> return
|
||||||
|
is RemoteInterface.ClosedException, is CancellationException, is RemoteInterface.RemoteException
|
||||||
|
-> throw e
|
||||||
|
else -> throw RemoteInterface.ClosedException()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal suspend fun callWithId(
|
||||||
|
cmd: Command<UByteArray, UByteArray>,
|
||||||
|
readResponse: (UByteArray) -> UByteArray = { it },
|
||||||
|
build: (UInt) -> OutgoingData,
|
||||||
|
): UByteArray = sendBoundCallBlock(cmd.name, { raw ->
|
||||||
|
try { readResponse(unpack(cmd.resultSerializer, raw)) }
|
||||||
|
catch (e: DiscardPacket) { throw e }
|
||||||
|
catch (e: Throwable) { throw RemoteInterface.SecurityException("Invalid authenticated response") }
|
||||||
|
}) { id ->
|
||||||
|
val payload = build(id)
|
||||||
|
OutgoingData(pack(cmd.argsSerializer, payload.bytes), payload.nonce)
|
||||||
|
}
|
||||||
|
|
||||||
|
internal suspend fun pushPrepared(name: String, priority: Int, prepare: () -> OutgoingData) {
|
||||||
|
sendPrepared {
|
||||||
|
val payload = prepare()
|
||||||
|
OutgoingData(pack<Block>(Block.Call(0u, name, pack(payload.bytes)).also { it.priority = priority }), payload.nonce)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Atomic preparation/admission, with carrier completion awaited outside the mutex. */
|
||||||
|
private suspend fun sendPrepared(prepare: () -> OutgoingData) {
|
||||||
|
val writer = writerReady.await()
|
||||||
|
val awaitSent = outgoing.withLock {
|
||||||
|
if (isClosed) throw RemoteInterface.ClosedException()
|
||||||
|
val frame = prepare()
|
||||||
|
writer.enqueue(frame.bytes, frame.nonce)
|
||||||
|
}
|
||||||
|
awaitSent()
|
||||||
|
}
|
||||||
|
|
||||||
|
internal suspend fun abortSecurity() {
|
||||||
|
isClosed = true
|
||||||
|
device.close()
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -139,6 +233,10 @@ class Transport<S>(
|
|||||||
return unpack(cmd.resultSerializer, result)
|
return unpack(cmd.resultSerializer, result)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
override suspend fun <A>push(cmd: Command<A,Unit>,args: A) {
|
||||||
|
sendPushBlock(cmd.name, pack(cmd.argsSerializer, args))
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Start running the transport. This function suspends until the transport is closed
|
* Start running the transport. This function suspends until the transport is closed
|
||||||
* normally or by error. If you need to cancel it prematurely, cancel the coroutine
|
* normally or by error. If you need to cancel it prematurely, cancel the coroutine
|
||||||
@@ -148,74 +246,94 @@ class Transport<S>(
|
|||||||
*/
|
*/
|
||||||
suspend fun run() {
|
suspend fun run() {
|
||||||
coroutineScope {
|
coroutineScope {
|
||||||
|
// One ordered submission to the carrier at a time: adapter queues cannot
|
||||||
|
// undo the nonce-aware scheduling performed here.
|
||||||
|
val writer = PriorityBlockWriter(this, continueOnWriteFailure = true) { device.send(it) }
|
||||||
|
writerReady.complete(writer)
|
||||||
debug { "awaiting incoming blocks" }
|
debug { "awaiting incoming blocks" }
|
||||||
// todo: rewrite it to close the job with no exceptions at all, always
|
// todo: rewrite it to close the job with no exceptions at all, always
|
||||||
while (isActive && !isClosed) {
|
while (isActive && !isClosed) {
|
||||||
try {
|
try {
|
||||||
device.input.receive().let { packed ->
|
device.input.receive().let { packed ->
|
||||||
debug { "<<<\n${packed.toDump()}" }
|
|
||||||
val b = unpack<Block>(packed)
|
val b = unpack<Block>(packed)
|
||||||
debug { "<<$ $b" }
|
|
||||||
debug { "access state: ${access.isLocked}" }
|
|
||||||
when (b) {
|
when (b) {
|
||||||
is Block.Error -> access.withLock {
|
is Block.Error -> access.withLock {
|
||||||
val error = localInterface.decodeError(b)
|
val error = if (responseReaders.containsKey(b.forId)) UnauthenticatedOuterError() else localInterface.decodeError(b)
|
||||||
warning { "decoded error: ${error::class.simpleName}: $error" }
|
warning { "decoded error: ${error::class.simpleName}: $error" }
|
||||||
calls.remove(b.forId)?.completeExceptionally(localInterface.decodeError(b))
|
responseReaders.remove(b.forId)
|
||||||
|
calls.remove(b.forId)?.completeExceptionally(error)
|
||||||
?: warning { "error handler not found for ${b.forId}" }
|
?: warning { "error handler not found for ${b.forId}" }
|
||||||
info { "error processed" }
|
info { "error processed" }
|
||||||
}
|
}
|
||||||
|
|
||||||
is Block.Response -> access.withLock {
|
is Block.Response -> access.withLock {
|
||||||
calls.remove(b.forId)?.let {
|
val pending = calls[b.forId]
|
||||||
debug { "activating wait handle for ${b.forId}" }
|
if (pending != null) {
|
||||||
it.complete(b.packedResult)
|
try {
|
||||||
|
val result = responseReaders[b.forId]?.invoke(b.packedResult) ?: b.packedResult
|
||||||
|
calls.remove(b.forId)
|
||||||
|
responseReaders.remove(b.forId)
|
||||||
|
pending.complete(result)
|
||||||
|
} catch (_: DiscardPacket) {
|
||||||
|
// Keep the waiter: a valid response may still arrive.
|
||||||
|
} catch (failure: Throwable) {
|
||||||
|
calls.remove(b.forId)
|
||||||
|
responseReaders.remove(b.forId)
|
||||||
|
pending.completeExceptionally(failure)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
?: warning { "wait handle not found for ${b.forId}" }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
is Block.Call -> launch {
|
is Block.Call -> launch {
|
||||||
try {
|
try {
|
||||||
send(
|
val result = localInterface.executeTransportBlock(commandContext, b)
|
||||||
Block.Response(
|
if (b.id != 0u) {
|
||||||
b.id,
|
try {
|
||||||
localInterface.execute(commandContext, b.name, b.packedArgs)
|
sendPrepared {
|
||||||
)
|
val encoded = result.encode()
|
||||||
)
|
OutgoingData(pack<Block>(Block.Response(b.id, encoded.bytes).also { it.priority = b.priority }), encoded.nonce)
|
||||||
|
}
|
||||||
|
} catch (failure: CancellationException) { throw failure }
|
||||||
|
catch (failure: LocalInterface.BreakConnectionException) { throw failure }
|
||||||
|
catch (failure: Throwable) {
|
||||||
|
// Local reply admission/I/O failure is not a plaintext
|
||||||
|
// remote business error. Leave peer timeout policy intact.
|
||||||
|
warning { "Reply send failed: ${failure.message}" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (_: DiscardPacket) {
|
||||||
|
// Duplicate/stale input is silently discarded, including pushes.
|
||||||
} catch (x: LocalInterface.BreakConnectionException) {
|
} catch (x: LocalInterface.BreakConnectionException) {
|
||||||
// handler forced close
|
// handler forced close
|
||||||
warning { "handler requested closing of the connection (${x.flushSendQueue}" }
|
warning { "handler requested closing of the connection (${x.flushSendQueue}" }
|
||||||
isClosed = true
|
isClosed = true
|
||||||
if( x.flushSendQueue ) device.flush()
|
if (x.flushSendQueue) { writer.flush(); device.flush() }
|
||||||
device.close()
|
device.close()
|
||||||
|
} catch (x: CancellationException) {
|
||||||
|
throw x
|
||||||
} catch (x: RemoteInterface.RemoteException) {
|
} catch (x: RemoteInterface.RemoteException) {
|
||||||
send(Block.Error(b.id, x.code, x.text, x.extra))
|
send(Block.Error(b.id, x.code, x.text, x.extra).also { it.priority = b.priority })
|
||||||
} catch (t: Throwable) {
|
} catch (t: Throwable) {
|
||||||
send(Block.Error(b.id, "UnknownError", t.message))
|
send(Block.Error(b.id, "UnknownError", t.message).also { it.priority = b.priority })
|
||||||
}
|
|
||||||
.also { debug { "command executed: ${b.name}" } }
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
debug { "=---------------------------------------------"}
|
|
||||||
}
|
}
|
||||||
debug { "input step performed closed=$isClosed active=$isActive"}
|
}
|
||||||
|
// debug { "input step performed closed=$isClosed active=$isActive" }
|
||||||
} catch (_: ClosedSendChannelException) {
|
} catch (_: ClosedSendChannelException) {
|
||||||
info { "closed send channel" }
|
info { "closed send channel" }
|
||||||
isClosed = true
|
isClosed = true
|
||||||
} catch (_: ClosedReceiveChannelException) {
|
} catch (_: ClosedReceiveChannelException) {
|
||||||
info { "closed receive channel" }
|
info { "closed receive channel" }
|
||||||
isClosed = true
|
isClosed = true
|
||||||
}
|
} catch (cce: LocalInterface.BreakConnectionException) {
|
||||||
catch(cce: LocalInterface.BreakConnectionException) {
|
|
||||||
info { "closing connection by local request ($cce)" }
|
info { "closing connection by local request ($cce)" }
|
||||||
device.close()
|
device.close()
|
||||||
}
|
} catch (_: RemoteInterface.ClosedException) {
|
||||||
catch(t: RemoteInterface.ClosedException) {
|
|
||||||
// it is ok: we just exit the coroutine normally
|
// it is ok: we just exit the coroutine normally
|
||||||
// and mark we're closing
|
// and mark we're closing
|
||||||
isClosed = true
|
isClosed = true
|
||||||
}
|
} catch (_: CancellationException) {
|
||||||
catch (_: CancellationException) {
|
|
||||||
info { "loop is cancelled with CancellationException" }
|
info { "loop is cancelled with CancellationException" }
|
||||||
isClosed = true
|
isClosed = true
|
||||||
} catch (t: Throwable) {
|
} catch (t: Throwable) {
|
||||||
@@ -233,18 +351,21 @@ class Transport<S>(
|
|||||||
for (c in calls.values)
|
for (c in calls.values)
|
||||||
c.completeExceptionally(RemoteInterface.ClosedException())
|
c.completeExceptionally(RemoteInterface.ClosedException())
|
||||||
calls.clear()
|
calls.clear()
|
||||||
|
responseReaders.clear()
|
||||||
|
writer.close()
|
||||||
debug { "calls clear has been called" }
|
debug { "calls clear has been called" }
|
||||||
|
// Closing a device also releases dispatch children waiting on unfinished handshakes.
|
||||||
|
currentCoroutineContext().cancelChildren()
|
||||||
}
|
}
|
||||||
debug { "no more active: $isActive / ${calls.size}" }
|
debug { "no more active: $isActive / ${calls.size}" }
|
||||||
}
|
}
|
||||||
info { "exiting transport loop" }
|
debug { "exiting transport loop" }
|
||||||
}
|
}
|
||||||
|
|
||||||
private suspend fun send(block: Block) {
|
private suspend fun send(block: Block) {
|
||||||
try {
|
try {
|
||||||
device.output.send(pack(block))
|
sendPrepared { OutgoingData(pack(block)) }
|
||||||
}
|
} catch (_: ClosedSendChannelException) {
|
||||||
catch(_: ClosedSendChannelException) {
|
|
||||||
throw RemoteInterface.ClosedException()
|
throw RemoteInterface.ClosedException()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -271,14 +392,26 @@ object TransportBlockSerializer : KSerializer<Transport.Block> {
|
|||||||
encoder.encodeSerializableValue(serializer<Transport.Block.Response>(), value)
|
encoder.encodeSerializableValue(serializer<Transport.Block.Response>(), value)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// Fixed-size trailer is omitted for zero, preserving exact legacy bytes.
|
||||||
|
if (value.priority != 0) {
|
||||||
|
for (shift in 24 downTo 0 step 8) encoder.encodeByte((value.priority ushr shift).toByte())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
override fun deserialize(decoder: Decoder): Transport.Block =
|
override fun deserialize(decoder: Decoder): Transport.Block {
|
||||||
when( val id = decoder.decodeByte().toInt()) {
|
val block = when (val id = decoder.decodeByte().toInt()) {
|
||||||
0 -> decoder.decodeSerializableValue(serializer<Transport.Block.Call>())
|
0 -> decoder.decodeSerializableValue(serializer<Transport.Block.Call>())
|
||||||
1 -> decoder.decodeSerializableValue(serializer<Transport.Block.Error>())
|
1 -> decoder.decodeSerializableValue(serializer<Transport.Block.Error>())
|
||||||
2 -> decoder.decodeSerializableValue(serializer<Transport.Block.Response>())
|
2 -> decoder.decodeSerializableValue(serializer<Transport.Block.Response>())
|
||||||
else -> throw RemoteInterface.InvalidDataException("wrong block type: $id")
|
else -> throw RemoteInterface.InvalidDataException("wrong block type: $id")
|
||||||
}
|
}
|
||||||
|
val first = try { decoder.decodeByte().toInt() and 255 }
|
||||||
|
catch (_: net.sergeych.bintools.DataSource.EndOfData) { return block }
|
||||||
|
// A present but truncated trailer is malformed, not a legacy priority-zero block.
|
||||||
|
var priority = first
|
||||||
|
repeat(3) { priority = (priority shl 8) or (decoder.decodeByte().toInt() and 255) }
|
||||||
|
block.priority = priority
|
||||||
|
return block
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,3 +1,13 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2025. Sergey S. Chernov - All Rights Reserved
|
||||||
|
*
|
||||||
|
* You may use, distribute and modify this code under the
|
||||||
|
* terms of the private license, which you must obtain from the author
|
||||||
|
*
|
||||||
|
* To obtain the license, contact the author: https://t.me/real_sergeych or email to
|
||||||
|
* real dot sergeych at gmail.
|
||||||
|
*/
|
||||||
|
|
||||||
package net.sergeych.kiloparsec.adapter
|
package net.sergeych.kiloparsec.adapter
|
||||||
|
|
||||||
import kotlinx.coroutines.channels.Channel
|
import kotlinx.coroutines.channels.Channel
|
||||||
|
|||||||
@@ -1,56 +1,23 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2025. Sergey S. Chernov - All Rights Reserved
|
||||||
|
*
|
||||||
|
* You may use, distribute and modify this code under the
|
||||||
|
* terms of the private license, which you must obtain from the author
|
||||||
|
*
|
||||||
|
* To obtain the license, contact the author: https://t.me/real_sergeych or email to
|
||||||
|
* real dot sergeych at gmail.
|
||||||
|
*/
|
||||||
|
|
||||||
package net.sergeych.kiloparsec.adapter
|
package net.sergeych.kiloparsec.adapter
|
||||||
|
|
||||||
import kotlinx.coroutines.channels.ReceiveChannel
|
|
||||||
import kotlinx.coroutines.flow.Flow
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Multiplatform implementation of an internet address.
|
* Multiplatform internet address.
|
||||||
* Notice to implementors. It must provide correct and effective [equals] and [hashCode].
|
|
||||||
*/
|
*/
|
||||||
interface NetworkAddress {
|
data class NetworkAddress(
|
||||||
val host: String
|
val host: String,
|
||||||
val port: Int
|
val port: Int
|
||||||
|
) {
|
||||||
|
override fun toString(): String {
|
||||||
|
return "$host:$port"
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Multiplatform datagram abstraction
|
|
||||||
*/
|
|
||||||
interface Datagram {
|
|
||||||
/**
|
|
||||||
* Received message
|
|
||||||
*/
|
|
||||||
val message: UByteArray
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Address from where the message was sent
|
|
||||||
*/
|
|
||||||
val address: NetworkAddress
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@OptIn(ExperimentalStdlibApi::class)
|
|
||||||
interface DatagramConnector: AutoCloseable {
|
|
||||||
|
|
||||||
val incoming: ReceiveChannel<Datagram>
|
|
||||||
suspend fun send(message: UByteArray, networkAddress: NetworkAddress)
|
|
||||||
@Suppress("unused")
|
|
||||||
suspend fun send(message: UByteArray, datagramAddress: String) {
|
|
||||||
send(message, datagramAddress.toNetworkAddress())
|
|
||||||
}
|
|
||||||
|
|
||||||
suspend fun send(message: UByteArray,host: String,port: Int) =
|
|
||||||
send(message, NetworkAddress(host,port))
|
|
||||||
override fun close()
|
|
||||||
}
|
|
||||||
|
|
||||||
expect fun NetworkAddress(host: String,port: Int): NetworkAddress
|
|
||||||
|
|
||||||
fun String.toNetworkAddress() : NetworkAddress {
|
|
||||||
val (host, port) = this.split(":").map { it.trim()}
|
|
||||||
return NetworkAddress(host, port.toInt())
|
|
||||||
}
|
|
||||||
|
|
||||||
expect fun acceptTcpDevice(port: Int): Flow<InetTransportDevice>
|
|
||||||
|
|
||||||
expect suspend fun connectTcpDevice(address: NetworkAddress): InetTransportDevice
|
|
||||||
|
|
||||||
suspend fun connectTcpDevice(address: String) = connectTcpDevice(address.toNetworkAddress())
|
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package net.sergeych.kiloparsec.adapter
|
||||||
|
|
||||||
|
import net.sergeych.kiloparsec.MAX_NONCE_OVERTAKING
|
||||||
|
|
||||||
|
/** Externally synchronized. Nonces belong to one sending-key stream. */
|
||||||
|
internal class OutQueue<T>(private val allowance: ULong = MAX_NONCE_OVERTAKING.toULong()) {
|
||||||
|
private data class Entry<T>(val value: T, val nonce: ULong?, val priority: Int)
|
||||||
|
private val entries = mutableListOf<Entry<T>>()
|
||||||
|
val values get() = entries.map { it.value }
|
||||||
|
fun push(value: T, nonce: ULong?, priority: Int) { entries.add(Entry(value, nonce, priority)) }
|
||||||
|
fun pop(): T? {
|
||||||
|
val oldest = entries.mapNotNull { it.nonce }.minOrNull()
|
||||||
|
var best: Entry<T>? = null
|
||||||
|
for (entry in entries) {
|
||||||
|
if (oldest != null && entry.nonce != null && entry.nonce - oldest > allowance) continue
|
||||||
|
val previous = best
|
||||||
|
if (previous == null || entry.priority > previous.priority ||
|
||||||
|
(entry.priority == previous.priority && entry.nonce != null && previous.nonce != null && entry.nonce < previous.nonce)) best = entry
|
||||||
|
}
|
||||||
|
return best?.also { entries.remove(it) }?.value
|
||||||
|
}
|
||||||
|
fun remove(value: T) { entries.removeAll { it.value === value } }
|
||||||
|
fun removeAll(predicate: (T) -> Boolean) { entries.removeAll { predicate(it.value) } }
|
||||||
|
fun clear() { entries.clear() }
|
||||||
|
}
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
package net.sergeych.kiloparsec.adapter
|
||||||
|
|
||||||
|
import kotlinx.coroutines.*
|
||||||
|
import kotlinx.coroutines.channels.Channel
|
||||||
|
import kotlinx.coroutines.sync.Mutex
|
||||||
|
import kotlinx.coroutines.sync.withLock
|
||||||
|
import net.sergeych.bintools.DataSource
|
||||||
|
import net.sergeych.kiloparsec.RemoteInterface
|
||||||
|
|
||||||
|
/** Reads only headers and skips length-delimited payloads; never copies or decrypts payload data. */
|
||||||
|
internal fun blockPriority(bytes: UByteArray): Int {
|
||||||
|
val source = object : DataSource {
|
||||||
|
var position = 0
|
||||||
|
override fun readByte(): Byte {
|
||||||
|
if (position >= bytes.size) throw DataSource.EndOfData()
|
||||||
|
return bytes[position++].toByte()
|
||||||
|
}
|
||||||
|
fun skipBlob() {
|
||||||
|
val size = readSmartUInt().toLong()
|
||||||
|
require(size <= bytes.size - position)
|
||||||
|
position += size.toInt()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return try {
|
||||||
|
val tag = source.readUByte().toInt()
|
||||||
|
source.readSmartUInt() // call ID or response ID
|
||||||
|
when (tag) {
|
||||||
|
0 -> { source.skipBlob(); source.skipBlob() }
|
||||||
|
1 -> {
|
||||||
|
source.skipBlob()
|
||||||
|
if (source.readByte() != 0.toByte()) source.skipBlob()
|
||||||
|
if (source.readByte() != 0.toByte()) source.skipBlob()
|
||||||
|
}
|
||||||
|
2 -> source.skipBlob()
|
||||||
|
else -> return 0 // Opaque legacy device users need not send RPC blocks.
|
||||||
|
}
|
||||||
|
if (bytes.size - source.position != 4) return 0
|
||||||
|
var result = 0
|
||||||
|
repeat(4) { result = (result shl 8) or source.readUByte().toInt() }
|
||||||
|
result
|
||||||
|
} catch (_: Exception) { 0 }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One adapter writer. Send completes after its write callback, not after an RPC reply.
|
||||||
|
* Queue ordering is nonce-bounded numeric priority; unnumbered ties remain FIFO. Cancellation removes queued work;
|
||||||
|
* bytes already being written cannot be recalled. No rate limit or idle batching delay.
|
||||||
|
*/
|
||||||
|
internal class PriorityBlockWriter(
|
||||||
|
scope: CoroutineScope,
|
||||||
|
private val maxQueuedItems: Int = 128,
|
||||||
|
private val maxQueuedBytes: Int = 32 * 1024 * 1024,
|
||||||
|
private val continueOnWriteFailure: Boolean = false,
|
||||||
|
private val write: suspend (UByteArray) -> Unit,
|
||||||
|
) {
|
||||||
|
private class Pending(val bytes: UByteArray, val priority: Int, val done: CompletableDeferred<Unit>)
|
||||||
|
private val mutex = Mutex()
|
||||||
|
private val wake = Channel<Unit>(Channel.CONFLATED)
|
||||||
|
private val pending = OutQueue<Pending>()
|
||||||
|
private var closed = false
|
||||||
|
private var writing: Pending? = null
|
||||||
|
private val job = scope.launch {
|
||||||
|
var current: Pending? = null
|
||||||
|
try {
|
||||||
|
while (isActive) {
|
||||||
|
current = mutex.withLock {
|
||||||
|
pending.removeAll { !it.done.isActive }
|
||||||
|
pending.pop().also { writing = it }
|
||||||
|
}
|
||||||
|
val entry = current
|
||||||
|
if (entry == null) { wake.receive(); continue }
|
||||||
|
try {
|
||||||
|
if (entry.done.isActive) write(entry.bytes)
|
||||||
|
entry.done.complete(Unit)
|
||||||
|
} catch (failure: Throwable) {
|
||||||
|
entry.done.completeExceptionally(failure)
|
||||||
|
if (!continueOnWriteFailure || failure is CancellationException) throw failure
|
||||||
|
}
|
||||||
|
mutex.withLock { writing = null }
|
||||||
|
current = null
|
||||||
|
}
|
||||||
|
} catch (failure: Throwable) {
|
||||||
|
current?.done?.completeExceptionally(failure)
|
||||||
|
throw failure
|
||||||
|
} finally {
|
||||||
|
withContext(NonCancellable) {
|
||||||
|
mutex.withLock {
|
||||||
|
closed = true
|
||||||
|
pending.values.forEach { it.done.completeExceptionally(RemoteInterface.ClosedException()) }
|
||||||
|
pending.clear()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Admission never waits for the carrier. Caller may hold its preparation mutex here. */
|
||||||
|
suspend fun enqueue(bytes: UByteArray, nonce: ULong? = null): suspend () -> Unit {
|
||||||
|
currentCoroutineContext().ensureActive()
|
||||||
|
val entry = Pending(bytes, blockPriority(bytes), CompletableDeferred())
|
||||||
|
mutex.withLock {
|
||||||
|
if (closed || !job.isActive) throw RemoteInterface.ClosedException()
|
||||||
|
pending.removeAll { !it.done.isActive }
|
||||||
|
if (pending.values.size >= maxQueuedItems || bytes.size > maxQueuedBytes - pending.values.sumOf { it.bytes.size })
|
||||||
|
throw RemoteInterface.Exception("Outgoing block queue is full")
|
||||||
|
pending.push(entry, nonce, entry.priority)
|
||||||
|
}
|
||||||
|
wake.trySend(Unit)
|
||||||
|
return {
|
||||||
|
try { entry.done.await() }
|
||||||
|
finally {
|
||||||
|
entry.done.cancel()
|
||||||
|
withContext(NonCancellable) { mutex.withLock { pending.remove(entry) } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
suspend fun send(bytes: UByteArray) { enqueue(bytes).invoke() }
|
||||||
|
suspend fun flush() {
|
||||||
|
val queued = mutex.withLock { (pending.values + listOfNotNull(writing)).map { it.done } }
|
||||||
|
queued.forEach { it.await() }
|
||||||
|
}
|
||||||
|
fun close() { job.cancel() }
|
||||||
|
}
|
||||||
@@ -1,3 +1,13 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2025. Sergey S. Chernov - All Rights Reserved
|
||||||
|
*
|
||||||
|
* You may use, distribute and modify this code under the
|
||||||
|
* terms of the private license, which you must obtain from the author
|
||||||
|
*
|
||||||
|
* To obtain the license, contact the author: https://t.me/real_sergeych or email to
|
||||||
|
* real dot sergeych at gmail.
|
||||||
|
*/
|
||||||
|
|
||||||
package net.sergeych.kiloparsec.adapter
|
package net.sergeych.kiloparsec.adapter
|
||||||
|
|
||||||
import kotlinx.coroutines.channels.Channel
|
import kotlinx.coroutines.channels.Channel
|
||||||
@@ -15,16 +25,26 @@ open class ProxyDevice(
|
|||||||
private val doFlush: (suspend ()->Unit)? = null,
|
private val doFlush: (suspend ()->Unit)? = null,
|
||||||
): Transport.Device {
|
): Transport.Device {
|
||||||
|
|
||||||
|
internal var prioritizedSend: (suspend (UByteArray) -> Unit)? = null
|
||||||
|
internal var priorityWriter: PriorityBlockWriter? = null
|
||||||
|
override suspend fun send(block: UByteArray) {
|
||||||
|
prioritizedSend?.let { it(block); return }
|
||||||
|
val writer = priorityWriter
|
||||||
|
if (writer == null) output.send(block) else writer.send(block)
|
||||||
|
}
|
||||||
|
|
||||||
override val input: ReceiveChannel<UByteArray> = inputChannel
|
override val input: ReceiveChannel<UByteArray> = inputChannel
|
||||||
override val output: SendChannel<UByteArray> = outputChannel
|
override val output: SendChannel<UByteArray> = outputChannel
|
||||||
|
|
||||||
override suspend fun close() {
|
override suspend fun close() {
|
||||||
|
priorityWriter?.close()
|
||||||
kotlin.runCatching { doClose?.invoke() }
|
kotlin.runCatching { doClose?.invoke() }
|
||||||
runCatching { inputChannel.close() }
|
runCatching { inputChannel.close() }
|
||||||
runCatching { outputChannel.close() }
|
runCatching { outputChannel.close() }
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun flush() {
|
override suspend fun flush() {
|
||||||
|
priorityWriter?.flush()
|
||||||
doFlush?.invoke()
|
doFlush?.invoke()
|
||||||
var cnt = 10
|
var cnt = 10
|
||||||
while(!outputChannel.isEmpty) {
|
while(!outputChannel.isEmpty) {
|
||||||
|
|||||||
@@ -1,3 +1,13 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2025-2026. Sergey S. Chernov - All Rights Reserved
|
||||||
|
*
|
||||||
|
* You may use, distribute and modify this code under the
|
||||||
|
* terms of the private license, which you must obtain from the author
|
||||||
|
*
|
||||||
|
* To obtain the license, contact the author: https://t.me/real_sergeych or email to
|
||||||
|
* real dot sergeych at gmail.
|
||||||
|
*/
|
||||||
|
|
||||||
package net.sergeych.kiloparsec.adapter
|
package net.sergeych.kiloparsec.adapter
|
||||||
|
|
||||||
import io.ktor.client.*
|
import io.ktor.client.*
|
||||||
@@ -10,43 +20,71 @@ import kotlinx.coroutines.channels.Channel
|
|||||||
import kotlinx.coroutines.channels.ClosedReceiveChannelException
|
import kotlinx.coroutines.channels.ClosedReceiveChannelException
|
||||||
import kotlinx.coroutines.channels.ClosedSendChannelException
|
import kotlinx.coroutines.channels.ClosedSendChannelException
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.io.IOException
|
||||||
import net.sergeych.crypto2.SigningKey
|
import net.sergeych.crypto2.SigningKey
|
||||||
import net.sergeych.kiloparsec.KiloClient
|
import net.sergeych.kiloparsec.*
|
||||||
import net.sergeych.kiloparsec.KiloConnectionData
|
import net.sergeych.mp_logger.*
|
||||||
import net.sergeych.kiloparsec.KiloInterface
|
import net.sergeych.mp_tools.decodeBase64Compact
|
||||||
import net.sergeych.kiloparsec.RemoteInterface
|
import net.sergeych.mp_tools.encodeToBase64Compact
|
||||||
import net.sergeych.mp_logger.LogTag
|
|
||||||
import net.sergeych.mp_logger.exception
|
|
||||||
import net.sergeych.mp_logger.info
|
|
||||||
import net.sergeych.mp_logger.warning
|
|
||||||
import net.sergeych.mp_tools.globalLaunch
|
import net.sergeych.mp_tools.globalLaunch
|
||||||
import net.sergeych.tools.AtomicCounter
|
import net.sergeych.tools.AtomicCounter
|
||||||
|
|
||||||
private val counter = AtomicCounter()
|
private val counter = AtomicCounter()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shortcut to create websocket client. Use [websocketTransportDevice] with [KiloClient]
|
||||||
|
* for fine-grained control.
|
||||||
|
*/
|
||||||
fun <S> websocketClient(
|
fun <S> websocketClient(
|
||||||
path: String,
|
path: String,
|
||||||
clientInterface: KiloInterface<S> = KiloInterface(),
|
clientInterface: KiloInterface<S> = KiloInterface(),
|
||||||
client: HttpClient = HttpClient { install(WebSockets) },
|
|
||||||
secretKey: SigningKey? = null,
|
secretKey: SigningKey? = null,
|
||||||
|
useTextFrames: Boolean = false,
|
||||||
sessionMaker: () -> S = {
|
sessionMaker: () -> S = {
|
||||||
@Suppress("UNCHECKED_CAST")
|
@Suppress("UNCHECKED_CAST")
|
||||||
Unit as S
|
Unit as S
|
||||||
},
|
},
|
||||||
): KiloClient<S> {
|
): KiloClient<S> {
|
||||||
|
return KiloClient(clientInterface, secretKey) {
|
||||||
|
KiloConnectionData(websocketTransportDevice(path, useTextFrames), sessionMaker())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create kilopaarsec transport over websocket (ws or wss).
|
||||||
|
* @param path websocket path (must start with ws:// or wss:// and contain a path part)
|
||||||
|
* @param client optional caller-owned client. When omitted, a client with the
|
||||||
|
* [WebSockets] plugin is created for this device and closed with it.
|
||||||
|
*/
|
||||||
|
fun websocketTransportDevice(
|
||||||
|
path: String,
|
||||||
|
useTextFrames: Boolean = false,
|
||||||
|
client: HttpClient? = null,
|
||||||
|
): Transport.Device {
|
||||||
|
|
||||||
|
val ownsClient = client == null
|
||||||
|
val actualClient = client ?: HttpClient { install(WebSockets) }
|
||||||
|
|
||||||
|
val log = LogTag("WSTD")
|
||||||
var u = Url(path)
|
var u = Url(path)
|
||||||
if (u.encodedPath.length <= 1)
|
log.debug { "Creating websocket transport device at $u" }
|
||||||
|
if (u.encodedPath.length <= 1) {
|
||||||
|
log.debug {"Correcting path as up = ${u.encodedPath}" }
|
||||||
u = URLBuilder(u).apply {
|
u = URLBuilder(u).apply {
|
||||||
encodedPath = "/kp"
|
encodedPath = "/kp"
|
||||||
}.build()
|
}.build()
|
||||||
|
}
|
||||||
|
log.debug { "Url to process is $u" }
|
||||||
|
|
||||||
return KiloClient(clientInterface, secretKey) {
|
|
||||||
val input = Channel<UByteArray>()
|
val input = Channel<UByteArray>()
|
||||||
val output = Channel<UByteArray>()
|
val output = Channel<UByteArray>()
|
||||||
|
val writerReady = CompletableDeferred<PriorityBlockWriter>()
|
||||||
val closeHandle = CompletableDeferred<Boolean>()
|
val closeHandle = CompletableDeferred<Boolean>()
|
||||||
globalLaunch {
|
|
||||||
|
val connectionJob = globalLaunch {
|
||||||
val log = LogTag("KC:${counter.incrementAndGet()}")
|
val log = LogTag("KC:${counter.incrementAndGet()}")
|
||||||
client.webSocket({
|
try {
|
||||||
|
actualClient.webSocket({
|
||||||
url.protocol = u.protocol
|
url.protocol = u.protocol
|
||||||
url.host = u.host
|
url.host = u.host
|
||||||
url.port = u.port
|
url.port = u.port
|
||||||
@@ -57,30 +95,34 @@ fun <S> websocketClient(
|
|||||||
log.info { "connected to the server" }
|
log.info { "connected to the server" }
|
||||||
// println("SENDING!!!")
|
// println("SENDING!!!")
|
||||||
// send("Helluva")
|
// send("Helluva")
|
||||||
|
val writer = PriorityBlockWriter(this) { block ->
|
||||||
|
if (useTextFrames) send(Frame.Text(block.asByteArray().encodeToBase64Compact()))
|
||||||
|
else send(block.asByteArray())
|
||||||
|
flush() // Do not turn the WebSocket outgoing FIFO into an unbounded look-ahead.
|
||||||
|
}
|
||||||
|
writerReady.complete(writer)
|
||||||
launch {
|
launch {
|
||||||
try {
|
try {
|
||||||
for (block in output) {
|
for (block in output) writer.send(block)
|
||||||
send(block.toByteArray())
|
|
||||||
}
|
|
||||||
log.info { "input is closed, closing the websocket" }
|
log.info { "input is closed, closing the websocket" }
|
||||||
if (closeHandle.isActive) closeHandle.complete(true)
|
if (closeHandle.isActive) closeHandle.complete(true)
|
||||||
} catch (_: ClosedSendChannelException) {
|
} catch (_: ClosedSendChannelException) {
|
||||||
log.info { "send channel closed" }
|
log.info { "send channel closed" }
|
||||||
}
|
} catch (_: CancellationException) {
|
||||||
catch(_: CancellationException) {}
|
} catch (t: Throwable) {
|
||||||
catch(t: Throwable) {
|
|
||||||
log.info { "unexpected exception in websock sender: ${t.stackTraceToString()}" }
|
log.info { "unexpected exception in websock sender: ${t.stackTraceToString()}" }
|
||||||
closeHandle.completeExceptionally(t)
|
closeHandle.completeExceptionally(t)
|
||||||
}
|
}
|
||||||
|
writer.close()
|
||||||
if (closeHandle.isActive) closeHandle.complete(false)
|
if (closeHandle.isActive) closeHandle.complete(false)
|
||||||
}
|
}
|
||||||
launch {
|
launch {
|
||||||
try {
|
try {
|
||||||
for (f in incoming) {
|
for (f in incoming) {
|
||||||
if (f is Frame.Binary) {
|
when (f) {
|
||||||
input.send(f.readBytes().toUByteArray())
|
is Frame.Binary -> input.send(f.readBytes().toUByteArray())
|
||||||
} else {
|
is Frame.Text -> input.send(f.readText().decodeBase64Compact().toUByteArray())
|
||||||
log.warning { "ignoring unexpected frame of type ${f.frameType}" }
|
else -> log.warning { "ignoring unexpected frame of type ${f.frameType}" }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (closeHandle.isActive) closeHandle.complete(true)
|
if (closeHandle.isActive) closeHandle.complete(true)
|
||||||
@@ -98,17 +140,35 @@ fun <S> websocketClient(
|
|||||||
log.warning { "Client is closing with error" }
|
log.warning { "Client is closing with error" }
|
||||||
throw RemoteInterface.ClosedException()
|
throw RemoteInterface.ClosedException()
|
||||||
}
|
}
|
||||||
output.close()
|
runCatching { output.close() }
|
||||||
input.close()
|
runCatching { input.close() }
|
||||||
|
runCatching { close() }
|
||||||
|
}
|
||||||
|
} catch (x: IOException) {
|
||||||
|
if ("refused" in x.toString()) log.debug { "connection refused" }
|
||||||
|
else log.warning { "unexpected IO error $x" }
|
||||||
|
runCatching { output.close() }
|
||||||
|
runCatching { input.close() }
|
||||||
|
} finally {
|
||||||
|
writerReady.completeExceptionally(RemoteInterface.ClosedException())
|
||||||
|
if (ownsClient) actualClient.close()
|
||||||
}
|
}
|
||||||
log.info { "closing connection" }
|
log.info { "closing connection" }
|
||||||
}
|
}
|
||||||
val device = ProxyDevice(input, output) {
|
// Wait for connection be established or failed
|
||||||
|
val device = ProxyDevice(input, output, doClose = {
|
||||||
// we need to explicitly close the coroutine job, or it can hang for a long time
|
// we need to explicitly close the coroutine job, or it can hang for a long time
|
||||||
// leaking resources.
|
// leaking resources.
|
||||||
|
runCatching { output.close() }
|
||||||
|
runCatching { input.close() }
|
||||||
closeHandle.complete(true)
|
closeHandle.complete(true)
|
||||||
|
connectionJob.cancel()
|
||||||
// job.cancel()
|
// job.cancel()
|
||||||
|
})
|
||||||
|
device.prioritizedSend = { block ->
|
||||||
|
val writer = writerReady.await()
|
||||||
|
device.priorityWriter = writer
|
||||||
|
writer.send(block)
|
||||||
}
|
}
|
||||||
KiloConnectionData(device, sessionMaker())
|
return device
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -1,3 +1,13 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2025. Sergey S. Chernov - All Rights Reserved
|
||||||
|
*
|
||||||
|
* You may use, distribute and modify this code under the
|
||||||
|
* terms of the private license, which you must obtain from the author
|
||||||
|
*
|
||||||
|
* To obtain the license, contact the author: https://t.me/real_sergeych or email to
|
||||||
|
* real dot sergeych at gmail.
|
||||||
|
*/
|
||||||
|
|
||||||
package net.sergeych.kiloparsec
|
package net.sergeych.kiloparsec
|
||||||
|
|
||||||
import kotlinx.serialization.Serializable
|
import kotlinx.serialization.Serializable
|
||||||
@@ -15,5 +25,5 @@ data class ClientIdentity(val clientIdKey: VerifyingPublicKey?, val signature: U
|
|||||||
|
|
||||||
// Level 0 command: request key exchange
|
// Level 0 command: request key exchange
|
||||||
internal val L0Request by command<Handshake, Handshake>()
|
internal val L0Request by command<Handshake, Handshake>()
|
||||||
internal val L0ClientId by command<UByteArray, Unit>()
|
internal val L0ClientId by command<UByteArray, UByteArray>()
|
||||||
internal val L0Call by command<UByteArray,UByteArray>()
|
internal val L0Call by command<UByteArray,UByteArray>()
|
||||||
@@ -1,6 +1,34 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2025. Sergey S. Chernov - All Rights Reserved
|
||||||
|
*
|
||||||
|
* You may use, distribute and modify this code under the
|
||||||
|
* terms of the private license, which you must obtain from the author
|
||||||
|
*
|
||||||
|
* To obtain the license, contact the author: https://t.me/real_sergeych or email to
|
||||||
|
* real dot sergeych at gmail.
|
||||||
|
*/
|
||||||
|
|
||||||
package net.sergeych.kiloparsec
|
package net.sergeych.kiloparsec
|
||||||
|
|
||||||
|
import kotlinx.coroutines.sync.Mutex
|
||||||
|
import kotlinx.coroutines.sync.withLock
|
||||||
|
|
||||||
fun String.encodeToUByteArray() =
|
fun String.encodeToUByteArray() =
|
||||||
encodeToByteArray().toUByteArray()
|
encodeToByteArray().toUByteArray()
|
||||||
|
|
||||||
fun UByteArray.decodeFromUByteArray(): String = toByteArray().decodeToString()
|
class SyncValue<T>(initialValue: T) {
|
||||||
|
private val access = Mutex()
|
||||||
|
|
||||||
|
var value = initialValue
|
||||||
|
private set
|
||||||
|
|
||||||
|
suspend fun mutate(f: suspend (T)->T): T = access.withLock { f(value).also { value = it } }
|
||||||
|
|
||||||
|
@Suppress("unused")
|
||||||
|
suspend fun getAndSet(newValue: T): T = mutate {
|
||||||
|
val old = value
|
||||||
|
value = newValue
|
||||||
|
old
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,190 @@
|
|||||||
|
@file:OptIn(ExperimentalUnsignedTypes::class, kotlinx.coroutines.ExperimentalCoroutinesApi::class)
|
||||||
|
|
||||||
|
import kotlinx.coroutines.*
|
||||||
|
import kotlinx.coroutines.test.*
|
||||||
|
import net.sergeych.crypto2.SigningSecretKey
|
||||||
|
import net.sergeych.crypto2.initCrypto
|
||||||
|
import net.sergeych.kiloparsec.*
|
||||||
|
import net.sergeych.utools.pack
|
||||||
|
import net.sergeych.utools.unpack
|
||||||
|
import kotlin.test.*
|
||||||
|
import kotlin.time.Duration.Companion.seconds
|
||||||
|
|
||||||
|
/** Wire adversary regressions: mutations occur after serialization and outside the encryption layer. */
|
||||||
|
class AuthenticatedEnvelopeTest {
|
||||||
|
private fun intercept(device: Transport.Device,
|
||||||
|
mutate: suspend (Transport.Block, suspend (Transport.Block) -> Unit) -> Unit) =
|
||||||
|
object : Transport.Device by device {
|
||||||
|
override suspend fun send(block: UByteArray) {
|
||||||
|
mutate(unpack(block)) { replacement -> device.send(pack<Transport.Block>(replacement)) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun authenticatedDuplexAndSessionArePreserved() = runTest(timeout = 10.seconds) {
|
||||||
|
initCrypto()
|
||||||
|
val echo by command<String, String>()
|
||||||
|
val callback by command<String, String>()
|
||||||
|
val (a, b) = createTestDevice()
|
||||||
|
val ready = CompletableDeferred<Unit>()
|
||||||
|
val serverKey = SigningSecretKey.new()
|
||||||
|
val clientKey = SigningSecretKey.new()
|
||||||
|
val server = KiloServerConnection(KiloInterface<String>().apply {
|
||||||
|
on(echo) {
|
||||||
|
assertEquals("server-session", session)
|
||||||
|
assertEquals(clientKey.verifyingKey, remoteIdentity)
|
||||||
|
remote.call(callback, it)
|
||||||
|
}
|
||||||
|
}, b, "server-session", serverKey)
|
||||||
|
val client = KiloClientConnection(KiloInterface<String>().apply {
|
||||||
|
on(callback) {
|
||||||
|
assertEquals("client-session", session)
|
||||||
|
assertEquals(serverKey.verifyingKey, remoteIdentity)
|
||||||
|
"callback:$it"
|
||||||
|
}
|
||||||
|
}, a, "client-session", clientKey)
|
||||||
|
val jobs = listOf(launch { server.run() }, launch { client.run { if (it) ready.complete(Unit) } })
|
||||||
|
try {
|
||||||
|
ready.await()
|
||||||
|
assertEquals("callback:duplex", client.call(echo, "duplex"))
|
||||||
|
} finally { jobs.forEach { it.cancelAndJoin() } }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun swappingOuterResponseIdsCannotSwapConcurrentResults() = runTest(timeout = 10.seconds) {
|
||||||
|
initCrypto()
|
||||||
|
val echo by command<String, String>()
|
||||||
|
val (a, b) = createTestDevice()
|
||||||
|
val ready = CompletableDeferred<Unit>()
|
||||||
|
var armed = false
|
||||||
|
val held = mutableListOf<Transport.Block.Response>()
|
||||||
|
val malicious = intercept(b) { block, send ->
|
||||||
|
if (armed && block is Transport.Block.Response) {
|
||||||
|
held += block
|
||||||
|
if (held.size == 2) {
|
||||||
|
send(held[0].copy(forId = held[1].forId).also { it.priority = held[0].priority })
|
||||||
|
send(held[1].copy(forId = held[0].forId).also { it.priority = held[1].priority })
|
||||||
|
}
|
||||||
|
} else send(block)
|
||||||
|
}
|
||||||
|
val server = KiloServerConnection(KiloInterface<Unit>().apply { on(echo) { it } }, malicious, Unit, SigningSecretKey.new())
|
||||||
|
val client = KiloClientConnection(KiloInterface<Unit>(), a, Unit)
|
||||||
|
val serverJob = launch { runCatching { server.run() } }
|
||||||
|
val clientJob = launch { runCatching { client.run { if (it) ready.complete(Unit) } } }
|
||||||
|
try {
|
||||||
|
ready.await(); armed = true
|
||||||
|
val first = async { runCatching { client.call(echo, "first") } }
|
||||||
|
val second = async { runCatching { client.call(echo, "second") } }
|
||||||
|
assertTrue(withTimeout(2000) { first.await() }.isFailure)
|
||||||
|
assertTrue(withTimeout(2000) { second.await() }.isFailure)
|
||||||
|
assertEquals(2, held.size, "Both authenticated responses must reach the mutation point")
|
||||||
|
withTimeout(2000) { clientJob.join() }
|
||||||
|
} finally { listOf(serverJob, clientJob).forEach { it.cancelAndJoin() } }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun changingOuterCallIdToPushCannotDispatch() = rejectTamperedCall(changeId = true)
|
||||||
|
@Test fun changingOuterPriorityCannotDispatch() = rejectTamperedCall(changeId = false)
|
||||||
|
|
||||||
|
private fun rejectTamperedCall(changeId: Boolean) = runTest(timeout = 10.seconds) {
|
||||||
|
initCrypto()
|
||||||
|
val mutate by command<Int, Int>()
|
||||||
|
val (a, b) = createTestDevice()
|
||||||
|
val ready = CompletableDeferred<Unit>()
|
||||||
|
var executions = 0
|
||||||
|
var attacked = false
|
||||||
|
val malicious = intercept(a) { block, send ->
|
||||||
|
if (block is Transport.Block.Call && block.name == "L0Call") {
|
||||||
|
attacked = true
|
||||||
|
send(block.copy(id = if (changeId) 0u else block.id).also {
|
||||||
|
it.priority = if (changeId) block.priority else block.priority + 1
|
||||||
|
})
|
||||||
|
} else send(block)
|
||||||
|
}
|
||||||
|
val server = KiloServerConnection(KiloInterface<Unit>().apply { on(mutate) { executions++; it } }, b, Unit, SigningSecretKey.new())
|
||||||
|
val client = KiloClientConnection(KiloInterface<Unit>(), malicious, Unit)
|
||||||
|
val jobs = listOf(launch { runCatching { server.run() } }, launch { runCatching { client.run { if (it) ready.complete(Unit) } } })
|
||||||
|
try {
|
||||||
|
ready.await()
|
||||||
|
assertTrue(withTimeout(2000) { runCatching { client.call(mutate, 1) } }.isFailure)
|
||||||
|
assertTrue(attacked)
|
||||||
|
withTimeout(2000) { jobs[0].join() }
|
||||||
|
assertEquals(0, executions, "Unauthenticated routing metadata must be rejected before dispatch")
|
||||||
|
} finally { jobs.forEach { it.cancelAndJoin() } }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun replayCannotExecuteTwice() = runTest(timeout = 10.seconds) {
|
||||||
|
initCrypto()
|
||||||
|
val mutate by command<Int, Int>()
|
||||||
|
val (a, b) = createTestDevice()
|
||||||
|
val ready = CompletableDeferred<Unit>()
|
||||||
|
var executions = 0
|
||||||
|
var attacked = false
|
||||||
|
val malicious = intercept(a) { block, send ->
|
||||||
|
send(block)
|
||||||
|
if (block is Transport.Block.Call && block.name == "L0Call") { attacked = true; send(block) }
|
||||||
|
}
|
||||||
|
val server = KiloServerConnection(KiloInterface<Unit>().apply { on(mutate) { executions++; it } }, b, Unit, SigningSecretKey.new())
|
||||||
|
val client = KiloClientConnection(KiloInterface<Unit>(), malicious, Unit)
|
||||||
|
val serverJob = launch { runCatching { server.run() } }
|
||||||
|
val clientJob = launch { runCatching { client.run { if (it) ready.complete(Unit) } } }
|
||||||
|
try {
|
||||||
|
ready.await()
|
||||||
|
assertEquals(1, withTimeout(2000) { client.call(mutate, 1) })
|
||||||
|
runCurrent()
|
||||||
|
assertTrue(attacked)
|
||||||
|
assertEquals(1, executions, "The replay must never execute the application operation again")
|
||||||
|
assertTrue(serverJob.isActive)
|
||||||
|
assertEquals(2, client.call(mutate, 2))
|
||||||
|
runCurrent()
|
||||||
|
assertEquals(2, executions)
|
||||||
|
} finally { listOf(serverJob, clientJob).forEach { it.cancelAndJoin() } }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun forgedPlaintextIdentityAcknowledgementCannotConnect() = runTest(timeout = 10.seconds) {
|
||||||
|
initCrypto()
|
||||||
|
val (a, b) = createTestDevice()
|
||||||
|
var identityId: UInt? = null
|
||||||
|
var connected = false
|
||||||
|
var attacked = false
|
||||||
|
val observedClient = intercept(a) { block, send ->
|
||||||
|
if (block is Transport.Block.Call && block.name == "L0ClientId") identityId = block.id
|
||||||
|
send(block)
|
||||||
|
}
|
||||||
|
val maliciousServer = intercept(b) { block, send ->
|
||||||
|
if (block is Transport.Block.Response && block.forId == identityId) {
|
||||||
|
attacked = true
|
||||||
|
send(block.copy(packedResult = pack(Unit)))
|
||||||
|
} else send(block)
|
||||||
|
}
|
||||||
|
val server = KiloServerConnection(KiloInterface<Unit>(), maliciousServer, Unit, SigningSecretKey.new())
|
||||||
|
val client = KiloClientConnection(KiloInterface<Unit>(), observedClient, Unit)
|
||||||
|
val serverJob = launch { runCatching { server.run() } }
|
||||||
|
val clientJob = launch { runCatching { client.run { if (it) connected = true } } }
|
||||||
|
try {
|
||||||
|
withTimeout(2000) { clientJob.join() }
|
||||||
|
assertTrue(attacked)
|
||||||
|
assertFalse(connected, "Connected must await the authenticated server Finished")
|
||||||
|
} finally { listOf(serverJob, clientJob).forEach { it.cancelAndJoin() } }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun legacyHandshakeVersionIsRejectedBeforeConnection() = runTest(timeout = 10.seconds) {
|
||||||
|
initCrypto()
|
||||||
|
val (a, b) = createTestDevice()
|
||||||
|
var connected = false
|
||||||
|
var attacked = false
|
||||||
|
val downgraded = intercept(a) { block, send ->
|
||||||
|
if (block is Transport.Block.Call && block.name == "L0Request") {
|
||||||
|
attacked = true
|
||||||
|
val request = unpack<Handshake>(block.packedArgs)
|
||||||
|
send(block.copy(packedArgs = pack(request.copy(version = 1u))))
|
||||||
|
} else send(block)
|
||||||
|
}
|
||||||
|
val server = KiloServerConnection(KiloInterface<Unit>(), b, Unit, SigningSecretKey.new())
|
||||||
|
val client = KiloClientConnection(KiloInterface<Unit>(), downgraded, Unit)
|
||||||
|
val serverJob = launch { runCatching { server.run() } }
|
||||||
|
val clientJob = launch { runCatching { client.run { if (it) connected = true } } }
|
||||||
|
try {
|
||||||
|
withTimeout(2000) { clientJob.join() }
|
||||||
|
assertTrue(attacked)
|
||||||
|
assertFalse(connected)
|
||||||
|
} finally { listOf(serverJob, clientJob).forEach { it.cancelAndJoin() } }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
@file:OptIn(ExperimentalUnsignedTypes::class)
|
||||||
|
|
||||||
|
import kotlinx.coroutines.*
|
||||||
|
import kotlinx.coroutines.test.runTest
|
||||||
|
import net.sergeych.crypto2.SigningSecretKey
|
||||||
|
import net.sergeych.crypto2.initCrypto
|
||||||
|
import net.sergeych.kiloparsec.*
|
||||||
|
import kotlin.test.*
|
||||||
|
import kotlin.time.Duration.Companion.seconds
|
||||||
|
|
||||||
|
class ConnectionInitializationTest {
|
||||||
|
private class PolicyRejected : RemoteInterface.SecurityException("Peer rejected by policy")
|
||||||
|
private class InitializationAborted : LocalInterface.BreakConnectionException("Initialization aborted")
|
||||||
|
|
||||||
|
@Test fun serverSecurityRejectionClosesConnection() = rejectsInitialization(true, PolicyRejected())
|
||||||
|
@Test fun clientSecurityRejectionClosesConnection() = rejectsInitialization(false, PolicyRejected())
|
||||||
|
@Test fun serverBreakSubclassClosesConnection() = rejectsInitialization(true, InitializationAborted())
|
||||||
|
@Test fun clientBreakSubclassClosesConnection() = rejectsInitialization(false, InitializationAborted())
|
||||||
|
|
||||||
|
private fun rejectsInitialization(rejectOnServer: Boolean, rejection: Throwable) = runTest(timeout = 10.seconds) {
|
||||||
|
initCrypto()
|
||||||
|
val (a, b) = createTestDevice()
|
||||||
|
val serverKey = SigningSecretKey.new()
|
||||||
|
val clientKey = SigningSecretKey.new()
|
||||||
|
val clientInterface = KiloInterface<Unit>()
|
||||||
|
val serverInterface = KiloInterface<Unit>()
|
||||||
|
var policyCalled = false
|
||||||
|
var identityMatched = false
|
||||||
|
var laterHandlerCalled = false
|
||||||
|
var clientConnected = false
|
||||||
|
(if (rejectOnServer) serverInterface else clientInterface).apply {
|
||||||
|
onConnected {
|
||||||
|
identityMatched = remoteIdentity == if (rejectOnServer) clientKey.verifyingKey else serverKey.verifyingKey
|
||||||
|
policyCalled = true
|
||||||
|
throw rejection
|
||||||
|
}
|
||||||
|
onConnected { laterHandlerCalled = true }
|
||||||
|
}
|
||||||
|
val server = KiloServerConnection(serverInterface, b, Unit, serverKey)
|
||||||
|
val client = KiloClientConnection(clientInterface, a, Unit, clientKey)
|
||||||
|
val serverRun = async { runCatching { server.run() } }
|
||||||
|
val clientRun = async { runCatching { client.run { if (it) clientConnected = true } } }
|
||||||
|
try {
|
||||||
|
withTimeout(2000) { serverRun.await(); clientRun.await() }
|
||||||
|
assertTrue(policyCalled, "Initialization policy must run")
|
||||||
|
assertTrue(identityMatched, "Policy must receive the verified remote identity")
|
||||||
|
assertFalse(laterHandlerCalled, "Rejection must stop subsequent initialization handlers")
|
||||||
|
assertFalse(clientConnected, "Rejected initialization must not announce a connected client")
|
||||||
|
if (!rejectOnServer) assertSame(rejection, clientRun.await().exceptionOrNull())
|
||||||
|
val echo by command<String, String>()
|
||||||
|
assertIs<RemoteInterface.ClosedException>(runCatching { client.call(echo, "after rejection") }.exceptionOrNull())
|
||||||
|
} finally {
|
||||||
|
serverRun.cancelAndJoin()
|
||||||
|
clientRun.cancelAndJoin()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun ordinaryHandlerFailuresStillAllowInitialization() = runTest(timeout = 10.seconds) {
|
||||||
|
initCrypto()
|
||||||
|
val (a, b) = createTestDevice()
|
||||||
|
val echo by command<String, String>()
|
||||||
|
var serverInitialized = false
|
||||||
|
var clientInitialized = false
|
||||||
|
val serverInterface = KiloInterface<Unit>().apply {
|
||||||
|
onConnected { throw IllegalStateException("Nonfatal handler failure") }
|
||||||
|
onConnected { serverInitialized = true }
|
||||||
|
on(echo) { it }
|
||||||
|
}
|
||||||
|
val clientInterface = KiloInterface<Unit>().apply {
|
||||||
|
onConnected { throw IllegalStateException("Nonfatal handler failure") }
|
||||||
|
onConnected { clientInitialized = true }
|
||||||
|
}
|
||||||
|
val ready = CompletableDeferred<Unit>()
|
||||||
|
val server = KiloServerConnection(serverInterface, b, Unit)
|
||||||
|
val client = KiloClientConnection(clientInterface, a, Unit)
|
||||||
|
val serverJob = launch { server.run() }
|
||||||
|
val clientJob = launch { client.run { if (it) ready.complete(Unit) } }
|
||||||
|
try {
|
||||||
|
ready.await()
|
||||||
|
assertTrue(serverInitialized)
|
||||||
|
assertTrue(clientInitialized)
|
||||||
|
assertEquals("ok", client.call(echo, "ok"))
|
||||||
|
} finally {
|
||||||
|
serverJob.cancelAndJoin()
|
||||||
|
clientJob.cancelAndJoin()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,3 +1,13 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2025. Sergey S. Chernov - All Rights Reserved
|
||||||
|
*
|
||||||
|
* You may use, distribute and modify this code under the
|
||||||
|
* terms of the private license, which you must obtain from the author
|
||||||
|
*
|
||||||
|
* To obtain the license, contact the author: https://t.me/real_sergeych or email to
|
||||||
|
* real dot sergeych at gmail.
|
||||||
|
*/
|
||||||
|
|
||||||
import kotlinx.coroutines.test.runTest
|
import kotlinx.coroutines.test.runTest
|
||||||
import net.sergeych.crypto2.IllegalSignatureException
|
import net.sergeych.crypto2.IllegalSignatureException
|
||||||
import net.sergeych.crypto2.SealedBox
|
import net.sergeych.crypto2.SealedBox
|
||||||
|
|||||||
@@ -0,0 +1,114 @@
|
|||||||
|
@file:OptIn(ExperimentalUnsignedTypes::class, kotlinx.coroutines.ExperimentalCoroutinesApi::class)
|
||||||
|
|
||||||
|
import kotlinx.coroutines.*
|
||||||
|
import kotlinx.coroutines.test.*
|
||||||
|
import net.sergeych.crypto2.initCrypto
|
||||||
|
import net.sergeych.kiloparsec.*
|
||||||
|
import net.sergeych.utools.pack
|
||||||
|
import net.sergeych.utools.unpack
|
||||||
|
import kotlin.test.*
|
||||||
|
import kotlin.time.Duration.Companion.seconds
|
||||||
|
|
||||||
|
class OutgoingSecurityTest {
|
||||||
|
@Test fun replayedReplyLeavesWaiterForValidReply() = runTest(timeout = 10.seconds) {
|
||||||
|
initCrypto()
|
||||||
|
val echo by command<String, String>()
|
||||||
|
val (a, b) = createTestDevice()
|
||||||
|
var armed = false
|
||||||
|
var saved: UByteArray? = null
|
||||||
|
val adversary = object : Transport.Device by b {
|
||||||
|
override suspend fun send(block: UByteArray) {
|
||||||
|
val bytes = block
|
||||||
|
val decoded = unpack<Transport.Block>(bytes)
|
||||||
|
if (armed && decoded is Transport.Block.Response) {
|
||||||
|
saved?.let { b.send(pack<Transport.Block>(decoded.copy(packedResult = it))) }
|
||||||
|
saved = decoded.packedResult
|
||||||
|
}
|
||||||
|
b.send(bytes)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val ready = CompletableDeferred<Unit>()
|
||||||
|
val server = KiloServerConnection(KiloInterface<Unit>().apply { on(echo) { it } }, adversary, Unit)
|
||||||
|
val client = KiloClientConnection(KiloInterface<Unit>(), a, Unit)
|
||||||
|
val sj = launch { server.run() }
|
||||||
|
val cj = launch { client.run { if (it) ready.complete(Unit) } }
|
||||||
|
try {
|
||||||
|
ready.await(); armed = true
|
||||||
|
assertEquals("first", client.call(echo, "first"))
|
||||||
|
assertEquals("second", client.call(echo, "second"))
|
||||||
|
assertTrue(sj.isActive); assertTrue(cj.isActive)
|
||||||
|
} finally { sj.cancelAndJoin(); cj.cancelAndJoin() }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun localReplySendFailureDoesNotForgePlaintextErrorOrClose() = runTest(timeout = 10.seconds) {
|
||||||
|
initCrypto()
|
||||||
|
val echo by command<Int, Int>()
|
||||||
|
val (a, b) = createTestDevice()
|
||||||
|
var fail = false
|
||||||
|
var plaintextErrors = 0
|
||||||
|
val device = object : Transport.Device by b {
|
||||||
|
override suspend fun send(block: UByteArray) {
|
||||||
|
val bytes = block
|
||||||
|
val decoded = unpack<Transport.Block>(bytes)
|
||||||
|
if (decoded is Transport.Block.Error) plaintextErrors++
|
||||||
|
if (fail && decoded is Transport.Block.Response) throw RemoteInterface.Exception("Local write failure")
|
||||||
|
b.send(bytes)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val ready = CompletableDeferred<Unit>()
|
||||||
|
val server = KiloServerConnection(KiloInterface<Unit>().apply { on(echo) { it } }, device, Unit)
|
||||||
|
val client = KiloClientConnection(KiloInterface<Unit>(), a, Unit)
|
||||||
|
val sj = launch { server.run() }
|
||||||
|
val cj = launch { client.run { if (it) ready.complete(Unit) } }
|
||||||
|
try {
|
||||||
|
ready.await(); fail = true
|
||||||
|
assertNull(withTimeoutOrNull(100) { client.call(echo, 1) })
|
||||||
|
assertEquals(0, plaintextErrors)
|
||||||
|
fail = false
|
||||||
|
assertEquals(2, client.call(echo, 2))
|
||||||
|
} finally { sj.cancelAndJoin(); cj.cancelAndJoin() }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun allSecurePathsShareOrderedNonceAdmission() = runTest(timeout = 20.seconds) {
|
||||||
|
initCrypto()
|
||||||
|
val echo by command<Int, Int>()
|
||||||
|
val notify by command<Int, Unit>()
|
||||||
|
val (a, b) = createTestDevice()
|
||||||
|
fun observing(device: Transport.Device, nonces: MutableList<ULong>, skipHandshakeReply: Boolean = false) = object : Transport.Device by device {
|
||||||
|
override suspend fun send(block: UByteArray) {
|
||||||
|
val bytes = block
|
||||||
|
when (val decoded = unpack<Transport.Block>(bytes)) {
|
||||||
|
is Transport.Block.Call -> if (decoded.name != "L0Request")
|
||||||
|
nonces += unpack<KiloParams.Package>(unpack<UByteArray>(decoded.packedArgs)).nonce
|
||||||
|
is Transport.Block.Response -> if (!skipHandshakeReply || decoded.forId != 1u)
|
||||||
|
nonces += unpack<KiloParams.Package>(unpack<UByteArray>(decoded.packedResult)).nonce
|
||||||
|
else -> Unit
|
||||||
|
}
|
||||||
|
device.send(bytes)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val an = mutableListOf<ULong>(); val bn = mutableListOf<ULong>()
|
||||||
|
val api = KiloInterface<Unit>().apply { on(echo) { it }; on(notify) {} }
|
||||||
|
val ready = CompletableDeferred<Unit>()
|
||||||
|
val server = KiloServerConnection(api, observing(b, bn, true), Unit)
|
||||||
|
val client = KiloClientConnection(api, observing(a, an), Unit)
|
||||||
|
val sj = launch { server.run() }
|
||||||
|
val cj = launch { client.run { if (it) ready.complete(Unit) } }
|
||||||
|
try {
|
||||||
|
ready.await()
|
||||||
|
// Real JVM parallel preparation, requests in both directions, replies and pushes.
|
||||||
|
withContext(Dispatchers.Default) {
|
||||||
|
(0 until 32).map { n -> async {
|
||||||
|
val remote: RemoteInterface = if (n % 2 == 0) client else server
|
||||||
|
remote.push(notify, n)
|
||||||
|
assertEquals(n, remote.call(echo, n))
|
||||||
|
} }.awaitAll()
|
||||||
|
}
|
||||||
|
for (nonces in listOf(an, bn)) {
|
||||||
|
assertEquals(0uL, nonces.first())
|
||||||
|
assertTrue(nonces.zipWithNext().all { (x, y) -> y > x }, "Equal-priority admission must follow nonce allocation: $nonces")
|
||||||
|
assertTrue(nonces.size >= 49)
|
||||||
|
}
|
||||||
|
} finally { sj.cancelAndJoin(); cj.cancelAndJoin() }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,14 @@
|
|||||||
import kotlinx.coroutines.runBlocking
|
/*
|
||||||
|
* Copyright (c) 2025. Sergey S. Chernov - All Rights Reserved
|
||||||
|
*
|
||||||
|
* You may use, distribute and modify this code under the
|
||||||
|
* terms of the private license, which you must obtain from the author
|
||||||
|
*
|
||||||
|
* To obtain the license, contact the author: https://t.me/real_sergeych or email to
|
||||||
|
* real dot sergeych at gmail.
|
||||||
|
*/
|
||||||
|
|
||||||
import kotlinx.coroutines.test.runTest
|
import kotlinx.coroutines.test.runTest
|
||||||
import kotlinx.datetime.Instant
|
|
||||||
import net.sergeych.bipack.BipackEncoder
|
import net.sergeych.bipack.BipackEncoder
|
||||||
import net.sergeych.crypto2.initCrypto
|
import net.sergeych.crypto2.initCrypto
|
||||||
import net.sergeych.kiloparsec.KiloParams
|
import net.sergeych.kiloparsec.KiloParams
|
||||||
@@ -12,6 +20,7 @@ import kotlin.test.Test
|
|||||||
import kotlin.test.assertContentEquals
|
import kotlin.test.assertContentEquals
|
||||||
import kotlin.test.assertEquals
|
import kotlin.test.assertEquals
|
||||||
import kotlin.time.Duration.Companion.microseconds
|
import kotlin.time.Duration.Companion.microseconds
|
||||||
|
import kotlin.time.Instant
|
||||||
|
|
||||||
class PackTest {
|
class PackTest {
|
||||||
inline fun <reified T>check(x: T?) {
|
inline fun <reified T>check(x: T?) {
|
||||||
@@ -46,7 +55,7 @@ class PackTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun packPackage() = runBlocking {
|
fun packPackage() = runTest {
|
||||||
val x = BipackEncoder.encode(KiloParams.Package(1u, ubyteArrayOf()))
|
val x = BipackEncoder.encode(KiloParams.Package(1u, ubyteArrayOf()))
|
||||||
assertContentEquals(byteArrayOf(4, 0), x)
|
assertContentEquals(byteArrayOf(4, 0), x)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,49 @@
|
|||||||
|
@file:OptIn(ExperimentalUnsignedTypes::class, kotlinx.coroutines.ExperimentalCoroutinesApi::class)
|
||||||
|
import kotlinx.coroutines.*
|
||||||
|
import kotlinx.coroutines.test.*
|
||||||
|
import net.sergeych.crypto2.initCrypto
|
||||||
|
import net.sergeych.kiloparsec.*
|
||||||
|
import net.sergeych.utools.unpack
|
||||||
|
import kotlin.test.*
|
||||||
|
|
||||||
|
class PriorityRpcTest {
|
||||||
|
@Test fun encryptedConcurrentRepliesAndErrorsInheritPriority() = runTest {
|
||||||
|
initCrypto()
|
||||||
|
val echo by command<Int, Int>()
|
||||||
|
val wait by command<Int, Int>()
|
||||||
|
val fail by command<Int, Int>()
|
||||||
|
val release = CompletableDeferred<Unit>()
|
||||||
|
val entered = CompletableDeferred<Unit>()
|
||||||
|
val ready = CompletableDeferred<Unit>()
|
||||||
|
val requests = mutableListOf<Transport.Block>()
|
||||||
|
val replies = mutableListOf<Transport.Block>()
|
||||||
|
val (a, b) = createTestDevice()
|
||||||
|
fun recording(device: Transport.Device, blocks: MutableList<Transport.Block>) = object : Transport.Device by device {
|
||||||
|
override suspend fun send(block: UByteArray) {
|
||||||
|
blocks += unpack<Transport.Block>(block)
|
||||||
|
device.send(block)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val server = KiloServerConnection(KiloInterface<Unit>().apply {
|
||||||
|
on(echo) { it }
|
||||||
|
on(wait) { entered.complete(Unit); release.await(); it }
|
||||||
|
on(fail) { throw RemoteInterface.RemoteException("test-error") }
|
||||||
|
}, recording(b, replies), Unit)
|
||||||
|
val client = KiloClientConnection(KiloInterface<Unit>(), recording(a, requests), Unit)
|
||||||
|
val jobs = listOf(launch { server.run() }, launch { client.run { if (it) ready.complete(Unit) } })
|
||||||
|
try {
|
||||||
|
ready.await()
|
||||||
|
val slow = async { client.call(wait, 1, priority = 7) }
|
||||||
|
entered.await()
|
||||||
|
assertEquals(2, client.call(echo, 2, priority = 123))
|
||||||
|
assertFalse(slow.isCompleted, "A pending reply must not prevent another concurrent call")
|
||||||
|
assertFailsWith<RemoteInterface.RemoteException> { client.call(fail, 3, priority = 81) }
|
||||||
|
release.complete(Unit); assertEquals(1, slow.await())
|
||||||
|
for (priority in listOf(7, 123, 81)) {
|
||||||
|
val request = requests.filterIsInstance<Transport.Block.Call>().single { it.priority == priority }
|
||||||
|
val response = replies.filterIsInstance<Transport.Block.Response>().single { it.forId == request.id }
|
||||||
|
assertEquals(priority, response.priority)
|
||||||
|
}
|
||||||
|
} finally { release.complete(Unit); jobs.forEach { it.cancelAndJoin() } }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
@file:OptIn(ExperimentalUnsignedTypes::class)
|
||||||
|
import kotlinx.coroutines.*
|
||||||
|
import kotlinx.coroutines.test.*
|
||||||
|
import net.sergeych.crypto2.*
|
||||||
|
import net.sergeych.kiloparsec.*
|
||||||
|
import net.sergeych.utools.pack
|
||||||
|
import net.sergeych.utools.unpack
|
||||||
|
import kotlin.test.*
|
||||||
|
import kotlin.time.Duration.Companion.seconds
|
||||||
|
|
||||||
|
class ReplayDeliveryTest {
|
||||||
|
@Test fun replayWindowBoundaries() = runTest {
|
||||||
|
initCrypto()
|
||||||
|
val a = SafeKeyExchange(); val b = SafeKeyExchange()
|
||||||
|
val (da, db) = createTestDevice()
|
||||||
|
val ta = Transport(da, LocalInterface<Unit>(), Unit)
|
||||||
|
val tb = Transport(db, LocalInterface<Unit>(), Unit)
|
||||||
|
val sender = KiloParams(false, ta, a.clientSessionKey(b.publicKey), Unit, null, ta)
|
||||||
|
val receiver = KiloParams(true, tb, b.serverSessionKey(a.publicKey), Unit, null, tb)
|
||||||
|
val packets = (0..4096).map { sender.encrypt(pack(it)) }
|
||||||
|
assertEquals(4096, unpack<Int>(receiver.decrypt(packets[4096])))
|
||||||
|
assertEquals(2, unpack<Int>(receiver.decrypt(packets[2])))
|
||||||
|
assertEquals(1, unpack<Int>(receiver.decrypt(packets[1])))
|
||||||
|
assertFails { receiver.decrypt(packets[0]) }
|
||||||
|
assertFails { receiver.decrypt(packets[1]) }
|
||||||
|
da.close(); db.close()
|
||||||
|
}
|
||||||
|
@Test fun localSendFailurePreservesHealthyConnection() = runTest(timeout = 10.seconds) {
|
||||||
|
initCrypto()
|
||||||
|
val echo by command<String,String>()
|
||||||
|
val (a,b) = createTestDevice()
|
||||||
|
val ready = CompletableDeferred<Unit>()
|
||||||
|
var fail = true
|
||||||
|
val localFailure = object: Transport.Device by a {
|
||||||
|
override suspend fun send(block: UByteArray) {
|
||||||
|
val decoded = unpack<Transport.Block>(block)
|
||||||
|
if(fail && decoded is Transport.Block.Call && decoded.name == "L0Call")
|
||||||
|
throw RemoteInterface.Exception("Outgoing block queue is full")
|
||||||
|
a.send(block)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val server=KiloServerConnection(KiloInterface<Unit>().apply { on(echo) { it } }, b, Unit)
|
||||||
|
val client=KiloClientConnection(KiloInterface<Unit>(),localFailure,Unit)
|
||||||
|
val sj=launch { runCatching { server.run() } }
|
||||||
|
val cj=launch { runCatching { client.run { if(it) ready.complete(Unit) } } }
|
||||||
|
try {
|
||||||
|
ready.await()
|
||||||
|
val result=runCatching { client.call(echo,"x") }
|
||||||
|
assertIs<RemoteInterface.Exception>(result.exceptionOrNull())
|
||||||
|
assertFalse(result.exceptionOrNull() is RemoteInterface.SecurityException)
|
||||||
|
assertTrue(cj.isActive); assertTrue(sj.isActive)
|
||||||
|
fail = false
|
||||||
|
assertEquals("recovered", client.call(echo,"recovered"))
|
||||||
|
} finally { sj.cancelAndJoin(); cj.cancelAndJoin() }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun adjacentReorderingSurvives() = reorderedPushes(1, false)
|
||||||
|
@Test fun deepReorderingDiscardsWithoutClosing() = reorderedPushes(4096, true)
|
||||||
|
private fun reorderedPushes(overtakers: Int, shouldDiscard: Boolean) = runTest(timeout = 20.seconds) {
|
||||||
|
initCrypto()
|
||||||
|
val notify by command<Int,Unit>()
|
||||||
|
val (a,b)=createTestDevice()
|
||||||
|
val ready=CompletableDeferred<Unit>()
|
||||||
|
val newerReceived=CompletableDeferred<Unit>()
|
||||||
|
val heldReceived=CompletableDeferred<Unit>()
|
||||||
|
var held: UByteArray?=null
|
||||||
|
val reorder=object: Transport.Device by a {
|
||||||
|
override suspend fun send(block: UByteArray) {
|
||||||
|
val decoded=unpack<Transport.Block>(block)
|
||||||
|
if(decoded is Transport.Block.Call && decoded.name=="L0Call" && held==null) held=block
|
||||||
|
else a.send(block)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val server=KiloServerConnection(KiloInterface<Unit>().apply { on(notify) {
|
||||||
|
if(it==overtakers) newerReceived.complete(Unit)
|
||||||
|
if(it==0) heldReceived.complete(Unit)
|
||||||
|
} }, b, Unit)
|
||||||
|
val client=KiloClientConnection(KiloInterface<Unit>(),reorder,Unit)
|
||||||
|
val sj=launch { runCatching { server.run() } }
|
||||||
|
val cj=launch { runCatching { client.run { if(it) ready.complete(Unit) } } }
|
||||||
|
try {
|
||||||
|
ready.await()
|
||||||
|
for(i in 0..overtakers) client.push(notify,i)
|
||||||
|
newerReceived.await()
|
||||||
|
a.send(held!!)
|
||||||
|
if(shouldDiscard) {
|
||||||
|
runCurrent()
|
||||||
|
assertTrue(sj.isActive); assertTrue(cj.isActive)
|
||||||
|
assertFalse(heldReceived.isCompleted)
|
||||||
|
client.ping()
|
||||||
|
} else {
|
||||||
|
withTimeout(2000) { heldReceived.await() }
|
||||||
|
assertTrue(sj.isActive); assertTrue(cj.isActive)
|
||||||
|
}
|
||||||
|
} finally { sj.cancelAndJoin(); cj.cancelAndJoin() }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
@file:OptIn(ExperimentalUnsignedTypes::class)
|
||||||
|
package net.sergeych.kiloparsec
|
||||||
|
|
||||||
|
import kotlin.random.Random
|
||||||
|
import kotlin.test.*
|
||||||
|
|
||||||
|
class ReplayWindowTest {
|
||||||
|
@Test fun boundariesWraparoundAndLargeJumpsMatchReference() {
|
||||||
|
val window = ReplayWindow()
|
||||||
|
val seen = mutableSetOf<ULong>()
|
||||||
|
var highest: ULong? = null
|
||||||
|
val random = Random(41)
|
||||||
|
val inputs = mutableListOf(4096uL, 1uL, 2uL, 0uL, 1uL, 8191uL, 4096uL, 8192uL)
|
||||||
|
repeat(15000) { inputs += random.nextInt(0, 30000).toULong() }
|
||||||
|
inputs += listOf(ULong.MAX_VALUE - 1u, ULong.MAX_VALUE, ULong.MAX_VALUE - 4095u, ULong.MAX_VALUE - 4096u)
|
||||||
|
for (n in inputs) {
|
||||||
|
val h = highest
|
||||||
|
val reject = n in seen || (h != null && n <= h && h - n >= 4096u)
|
||||||
|
assertEquals(reject, window.containsOrStale(n), "nonce=$n highest=$h")
|
||||||
|
if (!reject) {
|
||||||
|
window.record(n)
|
||||||
|
seen += n
|
||||||
|
if (h == null || n > h) highest = n
|
||||||
|
assertTrue(window.containsOrStale(n))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
@file:OptIn(ExperimentalUnsignedTypes::class, kotlinx.coroutines.ExperimentalCoroutinesApi::class)
|
||||||
|
|
||||||
|
import kotlinx.coroutines.*
|
||||||
|
import kotlinx.coroutines.test.*
|
||||||
|
import net.sergeych.crypto2.SigningSecretKey
|
||||||
|
import net.sergeych.crypto2.initCrypto
|
||||||
|
import net.sergeych.kiloparsec.*
|
||||||
|
import net.sergeych.utools.pack
|
||||||
|
import net.sergeych.utools.unpack
|
||||||
|
import kotlin.test.*
|
||||||
|
import kotlin.time.Duration.Companion.seconds
|
||||||
|
|
||||||
|
/** Regression checks at the boundary between untrusted outer transport and authenticated RPC. */
|
||||||
|
class SecurityBoundaryTest {
|
||||||
|
@Test fun plaintextRegisteredBusinessErrorCannotReachCallerAsBusinessResult() =
|
||||||
|
rejectPlaintextResponse(registeredError = true)
|
||||||
|
|
||||||
|
@Test fun malformedPlaintextResultClosesConnection() = rejectPlaintextResponse(registeredError = false)
|
||||||
|
|
||||||
|
private fun rejectPlaintextResponse(registeredError: Boolean) = runTest(timeout = 10.seconds) {
|
||||||
|
initCrypto()
|
||||||
|
val echo by command<String, String>()
|
||||||
|
val (clientDevice, serverDevice) = createTestDevice()
|
||||||
|
val ready = CompletableDeferred<Unit>()
|
||||||
|
var armed = false
|
||||||
|
var attacked = false
|
||||||
|
val malicious = object : Transport.Device by serverDevice {
|
||||||
|
override suspend fun send(block: UByteArray) {
|
||||||
|
val decoded = unpack<Transport.Block>(block)
|
||||||
|
if (armed && decoded is Transport.Block.Response) {
|
||||||
|
attacked = true
|
||||||
|
val forged: Transport.Block = if (registeredError)
|
||||||
|
Transport.Block.Error(decoded.forId, "IllegalArgumentException", "forged quota rejection")
|
||||||
|
else decoded.copy(packedResult = ubyteArrayOf())
|
||||||
|
serverDevice.send(pack(forged))
|
||||||
|
} else serverDevice.send(block)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val server = KiloServerConnection(KiloInterface<Unit>().apply { on(echo) { it } }, malicious, Unit, SigningSecretKey.new())
|
||||||
|
val client = KiloClientConnection(KiloInterface<Unit>(), clientDevice, Unit)
|
||||||
|
val serverJob = launch { runCatching { server.run() } }
|
||||||
|
val clientJob = launch { runCatching { client.run { if (it) ready.complete(Unit) } } }
|
||||||
|
try {
|
||||||
|
ready.await(); armed = true
|
||||||
|
val result = withTimeout(2000) { runCatching { client.call(echo, "payload") } }
|
||||||
|
assertTrue(attacked)
|
||||||
|
assertIs<RemoteInterface.SecurityException>(result.exceptionOrNull(), "Plaintext outer errors/data must never impersonate authenticated business results")
|
||||||
|
withTimeout(2000) { clientJob.join() }
|
||||||
|
} finally { listOf(clientJob, serverJob).forEach { it.cancelAndJoin() } }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun unestablishedProtectedCallDoesNotKeepDisconnectedServerAlive() = runTest(timeout = 10.seconds) {
|
||||||
|
initCrypto()
|
||||||
|
val (clientDevice, serverDevice) = createTestDevice()
|
||||||
|
val server = KiloServerConnection(KiloInterface<Unit>(), serverDevice, Unit, SigningSecretKey.new())
|
||||||
|
val serverJob = launch { runCatching { server.run() } }
|
||||||
|
try {
|
||||||
|
clientDevice.send(pack<Transport.Block>(Transport.Block.Call(1u, "L0Call", pack(ubyteArrayOf()))))
|
||||||
|
runCurrent()
|
||||||
|
clientDevice.close()
|
||||||
|
withTimeout(2000) { serverJob.join() }
|
||||||
|
} finally { serverJob.cancelAndJoin() }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,3 +1,13 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2025. Sergey S. Chernov - All Rights Reserved
|
||||||
|
*
|
||||||
|
* You may use, distribute and modify this code under the
|
||||||
|
* terms of the private license, which you must obtain from the author
|
||||||
|
*
|
||||||
|
* To obtain the license, contact the author: https://t.me/real_sergeych or email to
|
||||||
|
* real dot sergeych at gmail.
|
||||||
|
*/
|
||||||
|
|
||||||
class ToolsTest {
|
class ToolsTest {
|
||||||
// @Test
|
// @Test
|
||||||
// fun testRemoceCmd() {
|
// fun testRemoceCmd() {
|
||||||
|
|||||||
@@ -0,0 +1,65 @@
|
|||||||
|
@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class, ExperimentalUnsignedTypes::class)
|
||||||
|
|
||||||
|
import kotlinx.coroutines.*
|
||||||
|
import kotlinx.coroutines.test.*
|
||||||
|
import net.sergeych.crypto2.initCrypto
|
||||||
|
import net.sergeych.kiloparsec.*
|
||||||
|
import kotlin.test.*
|
||||||
|
import kotlin.time.Duration.Companion.seconds
|
||||||
|
|
||||||
|
class TransportAdmissionTest {
|
||||||
|
@Test fun readyCallsDoNotAddPollingDelay() = runTest(timeout = 10.seconds) {
|
||||||
|
val ping by command<Int, Int>()
|
||||||
|
val (a, b) = createTestDevice()
|
||||||
|
val local = LocalInterface<Unit>().apply { on(ping) { it } }
|
||||||
|
val client = Transport(a, local, Unit)
|
||||||
|
val server = Transport(b, local, Unit)
|
||||||
|
val jobs = listOf(launch { client.run() }, launch { server.run() })
|
||||||
|
try {
|
||||||
|
val start = currentTime
|
||||||
|
repeat(20) { assertEquals(it, client.call(ping, it)) }
|
||||||
|
assertEquals(0L, currentTime - start, "Ready transports must not impose an artificial per-call delay")
|
||||||
|
} finally { jobs.forEach { it.cancelAndJoin() } }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun successfulPlainPushReturnsNormally() = runTest(timeout = 10.seconds) {
|
||||||
|
val notify by command<Int, Unit>()
|
||||||
|
val received = CompletableDeferred<Int>()
|
||||||
|
val (a, b) = createTestDevice()
|
||||||
|
val client = Transport(a, LocalInterface<Unit>(), Unit)
|
||||||
|
val server = Transport(b, LocalInterface<Unit>().apply { on(notify) { received.complete(it); Unit } }, Unit)
|
||||||
|
val jobs = listOf(launch { client.run() }, launch { server.run() })
|
||||||
|
try {
|
||||||
|
client.push(notify, 7)
|
||||||
|
assertEquals(7, received.await())
|
||||||
|
} finally { jobs.forEach { it.cancelAndJoin() } }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun encryptedPushDoesNotWaitForRemoteHandler() = runTest(timeout = 10.seconds) {
|
||||||
|
initCrypto()
|
||||||
|
val notify by command<Int, Unit>()
|
||||||
|
val ping by command<Int, Int>()
|
||||||
|
val entered = CompletableDeferred<Unit>()
|
||||||
|
val release = CompletableDeferred<Unit>()
|
||||||
|
val ready = CompletableDeferred<Unit>()
|
||||||
|
val (a, b) = createTestDevice()
|
||||||
|
val server = KiloServerConnection(KiloInterface<Unit>().apply {
|
||||||
|
on(notify) { entered.complete(Unit); release.await() }
|
||||||
|
on(ping) { it }
|
||||||
|
}, b, Unit)
|
||||||
|
val client = KiloClientConnection(KiloInterface<Unit>(), a, Unit)
|
||||||
|
val jobs = listOf(launch { server.run() }, launch { client.run { if (it) ready.complete(Unit) } })
|
||||||
|
try {
|
||||||
|
ready.await()
|
||||||
|
val notification = async { client.push(notify, 7) }
|
||||||
|
entered.await()
|
||||||
|
runCurrent()
|
||||||
|
assertTrue(notification.isCompleted, "Push must return before the remote handler finishes")
|
||||||
|
notification.await()
|
||||||
|
assertEquals(9, client.call(ping, 9), "A pending notification must not block ordinary RPC")
|
||||||
|
} finally {
|
||||||
|
release.complete(Unit)
|
||||||
|
jobs.forEach { it.cancelAndJoin() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,3 +1,13 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2025. Sergey S. Chernov - All Rights Reserved
|
||||||
|
*
|
||||||
|
* You may use, distribute and modify this code under the
|
||||||
|
* terms of the private license, which you must obtain from the author
|
||||||
|
*
|
||||||
|
* To obtain the license, contact the author: https://t.me/real_sergeych or email to
|
||||||
|
* real dot sergeych at gmail.
|
||||||
|
*/
|
||||||
|
|
||||||
import kotlinx.coroutines.*
|
import kotlinx.coroutines.*
|
||||||
import kotlinx.coroutines.channels.Channel
|
import kotlinx.coroutines.channels.Channel
|
||||||
import kotlinx.coroutines.channels.ReceiveChannel
|
import kotlinx.coroutines.channels.ReceiveChannel
|
||||||
@@ -66,7 +76,8 @@ class TransportTest {
|
|||||||
"p2: $it"
|
"p2: $it"
|
||||||
}
|
}
|
||||||
on(cmdSlow) {
|
on(cmdSlow) {
|
||||||
delay(100)
|
// the problem: runTest() breaks delays so it is not enough
|
||||||
|
for( i in 0..10000) delay(1)
|
||||||
"done"
|
"done"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -159,6 +170,41 @@ class TransportTest {
|
|||||||
d2.close()
|
d2.close()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testDisconnectedHandlers() = runTest {
|
||||||
|
initCrypto()
|
||||||
|
|
||||||
|
val cmdPing by command<String, String>()
|
||||||
|
val (d1, d2) = createTestDevice()
|
||||||
|
val serverDisconnected = CompletableDeferred<String>()
|
||||||
|
val clientDisconnected = CompletableDeferred<String>()
|
||||||
|
|
||||||
|
val serverInterface = KiloInterface<String>().apply {
|
||||||
|
onDisconnected {
|
||||||
|
serverDisconnected.complete(session)
|
||||||
|
}
|
||||||
|
on(cmdPing) {
|
||||||
|
"pong! [$it]"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
launch { KiloServerConnection(serverInterface, d1, "server session").run() }
|
||||||
|
|
||||||
|
val clientInterface = KiloInterface<String>().apply {
|
||||||
|
onDisconnected {
|
||||||
|
clientDisconnected.complete(session)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val client = KiloClientConnection(clientInterface, d2, "client session")
|
||||||
|
launch { client.run() }
|
||||||
|
|
||||||
|
assertEquals("pong! [hello]", client.call(cmdPing, "hello"))
|
||||||
|
d1.close()
|
||||||
|
d2.close()
|
||||||
|
|
||||||
|
assertEquals("server session", withTimeout(1000) { serverDisconnected.await() })
|
||||||
|
assertEquals("client session", withTimeout(1000) { clientDisconnected.await() })
|
||||||
|
}
|
||||||
|
|
||||||
class TestException(text: String) : Exception(text)
|
class TestException(text: String) : Exception(text)
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -184,10 +230,16 @@ class TransportTest {
|
|||||||
val cmdRemoteExceptionTest by command<Unit, String>()
|
val cmdRemoteExceptionTest by command<Unit, String>()
|
||||||
val cmdBreak by command<Unit, Unit>()
|
val cmdBreak by command<Unit, Unit>()
|
||||||
|
|
||||||
|
val cmdPushServer by push<String>()
|
||||||
|
val pushedFromServer = CompletableDeferred<String>()
|
||||||
|
|
||||||
val serverInterface = KiloInterface<String>().apply {
|
val serverInterface = KiloInterface<String>().apply {
|
||||||
on(cmdPing) {
|
on(cmdPing) {
|
||||||
"pong! [$it]"
|
"pong! [$it]"
|
||||||
}
|
}
|
||||||
|
on(cmdPushServer) {
|
||||||
|
pushedFromServer.complete(it)
|
||||||
|
}
|
||||||
on(cmdGetToken) {
|
on(cmdGetToken) {
|
||||||
sessionToken
|
sessionToken
|
||||||
}
|
}
|
||||||
@@ -249,11 +301,17 @@ class TransportTest {
|
|||||||
assertEquals("client pong: foo", kiloServerConnection.call(cmdPing, "foo"))
|
assertEquals("client pong: foo", kiloServerConnection.call(cmdPing, "foo"))
|
||||||
assertEquals("server push: bar", kiloServerConnection.call(cmdPush, "bar"))
|
assertEquals("server push: bar", kiloServerConnection.call(cmdPush, "bar"))
|
||||||
|
|
||||||
|
client.push(cmdPushServer, "42")
|
||||||
|
|
||||||
assertEquals("**-s1-c1-s2-c2", client.call(cmdChainCallServer1, "**"))
|
assertEquals("**-s1-c1-s2-c2", client.call(cmdChainCallServer1, "**"))
|
||||||
|
|
||||||
|
|
||||||
assertThrows<TestException> { client.call(cmdException) }
|
assertThrows<TestException> { client.call(cmdException) }
|
||||||
assertEquals("ok: te-local", client.call(cmdRemoteExceptionTest))
|
assertEquals("ok: te-local", client.call(cmdRemoteExceptionTest))
|
||||||
|
|
||||||
|
// wait for push to be received and check
|
||||||
|
assertEquals("42", pushedFromServer.await())
|
||||||
|
|
||||||
assertThrows<RemoteInterface.ClosedException> {
|
assertThrows<RemoteInterface.ClosedException> {
|
||||||
client.call(cmdBreak)
|
client.call(cmdBreak)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,13 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2025. Sergey S. Chernov - All Rights Reserved
|
||||||
|
*
|
||||||
|
* You may use, distribute and modify this code under the
|
||||||
|
* terms of the private license, which you must obtain from the author
|
||||||
|
*
|
||||||
|
* To obtain the license, contact the author: https://t.me/real_sergeych or email to
|
||||||
|
* real dot sergeych at gmail.
|
||||||
|
*/
|
||||||
|
|
||||||
import kotlin.test.fail
|
import kotlin.test.fail
|
||||||
|
|
||||||
inline fun <reified T: Throwable>assertThrows(f: ()->Unit): T {
|
inline fun <reified T: Throwable>assertThrows(f: ()->Unit): T {
|
||||||
|
|||||||
@@ -0,0 +1,123 @@
|
|||||||
|
@file:OptIn(ExperimentalUnsignedTypes::class, kotlinx.coroutines.ExperimentalCoroutinesApi::class)
|
||||||
|
package net.sergeych.kiloparsec.adapter
|
||||||
|
|
||||||
|
import createTestDevice
|
||||||
|
import kotlinx.coroutines.*
|
||||||
|
import kotlinx.coroutines.test.*
|
||||||
|
import net.sergeych.kiloparsec.*
|
||||||
|
import net.sergeych.utools.pack
|
||||||
|
import net.sergeych.utools.unpack
|
||||||
|
import kotlin.test.*
|
||||||
|
|
||||||
|
class OutQueueTest {
|
||||||
|
@Test fun priorityWithinWindowAndOldestProgress() {
|
||||||
|
val queue = OutQueue<ULong>()
|
||||||
|
queue.push(100u, 100u, -100)
|
||||||
|
for (n in 101uL..5000uL) queue.push(n, n, 100)
|
||||||
|
val sent = mutableListOf<ULong>()
|
||||||
|
while (true) sent += queue.pop() ?: break
|
||||||
|
assertEquals((101uL..2830uL).toList(), sent.take(2730))
|
||||||
|
assertEquals(100uL, sent[2730])
|
||||||
|
assertEquals(4901, sent.toSet().size)
|
||||||
|
}
|
||||||
|
@Test fun gapsAndMaximumNonceDoNotOverflow() {
|
||||||
|
val queue = OutQueue<ULong>()
|
||||||
|
queue.push(ULong.MAX_VALUE, ULong.MAX_VALUE, 100)
|
||||||
|
queue.push(ULong.MAX_VALUE - 2731u, ULong.MAX_VALUE - 2731u, -100)
|
||||||
|
assertEquals(ULong.MAX_VALUE - 2731u, queue.pop())
|
||||||
|
assertEquals(ULong.MAX_VALUE, queue.pop())
|
||||||
|
assertNull(queue.pop())
|
||||||
|
}
|
||||||
|
@Test fun writerHandlesCancellationCapacityAndContinuesAfterLocalFailure() = runTest {
|
||||||
|
val gate = CompletableDeferred<Unit>()
|
||||||
|
val entered = CompletableDeferred<Unit>()
|
||||||
|
val observed = mutableListOf<Int>()
|
||||||
|
val writer = PriorityBlockWriter(backgroundScope, maxQueuedItems = 2, continueOnWriteFailure = true) {
|
||||||
|
val n = it[0].toInt()
|
||||||
|
if (n == 0) { entered.complete(Unit); gate.await() }
|
||||||
|
if (n == 3) throw IllegalStateException("Local carrier rejection")
|
||||||
|
observed += n
|
||||||
|
}
|
||||||
|
val first = async { writer.enqueue(ubyteArrayOf(0u), 0u).invoke() }
|
||||||
|
entered.await()
|
||||||
|
val cancelled = async { writer.enqueue(ubyteArrayOf(1u), 1u).invoke() }
|
||||||
|
runCurrent()
|
||||||
|
val second = async { writer.enqueue(ubyteArrayOf(2u), 2u).invoke() }
|
||||||
|
runCurrent()
|
||||||
|
assertFailsWith<RemoteInterface.Exception> { writer.enqueue(ubyteArrayOf(9u), 9u) }
|
||||||
|
cancelled.cancelAndJoin()
|
||||||
|
gate.complete(Unit)
|
||||||
|
first.await(); second.await()
|
||||||
|
assertFailsWith<IllegalStateException> { writer.enqueue(ubyteArrayOf(3u), 3u).invoke() }
|
||||||
|
writer.enqueue(ubyteArrayOf(4u), 4u).invoke()
|
||||||
|
assertEquals(listOf(0, 2, 4), observed)
|
||||||
|
writer.close(); runCurrent()
|
||||||
|
assertFailsWith<RemoteInterface.ClosedException> { writer.enqueue(ubyteArrayOf(5u), 5u) }
|
||||||
|
}
|
||||||
|
@Test fun writerUsesNonceBoundBeforePriority() = runTest {
|
||||||
|
val gate = CompletableDeferred<Unit>()
|
||||||
|
val entered = CompletableDeferred<Unit>()
|
||||||
|
val order = mutableListOf<Int>()
|
||||||
|
val writer = PriorityBlockWriter(backgroundScope) { bytes ->
|
||||||
|
val n = (unpack<Transport.Block>(bytes) as Transport.Block.Call).id.toInt()
|
||||||
|
if (n == 0) { entered.complete(Unit); gate.await() }
|
||||||
|
order += n
|
||||||
|
}
|
||||||
|
fun frame(n: Int, priority: Int) = pack<Transport.Block>(Transport.Block.Call(n.toUInt(), "x", ubyteArrayOf()).also { it.priority = priority })
|
||||||
|
val first = async { writer.enqueue(frame(0, 0), 0u).invoke() }
|
||||||
|
entered.await()
|
||||||
|
val old = writer.enqueue(frame(1, 0), 1u)
|
||||||
|
val newer = writer.enqueue(frame(2, 100), 2732u)
|
||||||
|
gate.complete(Unit); first.await(); old(); newer()
|
||||||
|
assertEquals(3, order.size)
|
||||||
|
assertEquals(listOf(0, 1, 2), order)
|
||||||
|
writer.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun encryptedBacklogCrossingWindowStillDeliversEveryMessage() = runTest {
|
||||||
|
net.sergeych.crypto2.initCrypto()
|
||||||
|
val a = net.sergeych.crypto2.SafeKeyExchange()
|
||||||
|
val b = net.sergeych.crypto2.SafeKeyExchange()
|
||||||
|
val (da, db) = createTestDevice()
|
||||||
|
val ta = Transport(da, LocalInterface<Unit>(), Unit)
|
||||||
|
val tb = Transport(db, LocalInterface<Unit>(), Unit)
|
||||||
|
val sender = KiloParams(false, ta, a.clientSessionKey(b.publicKey), Unit, null, ta)
|
||||||
|
val receiver = KiloParams(true, tb, b.serverSessionKey(a.publicKey), Unit, null, tb)
|
||||||
|
val gate = CompletableDeferred<Unit>()
|
||||||
|
val entered = CompletableDeferred<Unit>()
|
||||||
|
val order = mutableListOf<Int>()
|
||||||
|
// Larger test capacity reaches the boundary in one batch; production retains 128.
|
||||||
|
val writer = PriorityBlockWriter(backgroundScope, maxQueuedItems = 5000) { bytes ->
|
||||||
|
val frame = unpack<Transport.Block>(bytes) as Transport.Block.Call
|
||||||
|
if (frame.id == 0u) { entered.complete(Unit); gate.await() }
|
||||||
|
order += unpack<Int>(receiver.decrypt(unpack(frame.packedArgs)))
|
||||||
|
}
|
||||||
|
suspend fun admit(n: Int, priority: Int): suspend () -> Unit {
|
||||||
|
val encoded = sender.encode(pack(n))
|
||||||
|
val frame = Transport.Block.Call(n.toUInt(), "L0Call", pack(encoded.bytes)).also { it.priority = priority }
|
||||||
|
return writer.enqueue(pack<Transport.Block>(frame), encoded.nonce)
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
val first = admit(0, 0)
|
||||||
|
entered.await()
|
||||||
|
val completions = mutableListOf(admit(1, -100))
|
||||||
|
for (n in 2..4097) completions += admit(n, 100)
|
||||||
|
gate.complete(Unit); first()
|
||||||
|
completions.forEach { it() }
|
||||||
|
assertEquals(4098, order.size)
|
||||||
|
assertEquals((0..4097).toSet(), order.toSet())
|
||||||
|
assertEquals(2731, order.indexOf(1))
|
||||||
|
} finally { writer.close(); da.close(); db.close() }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun closingWriterReleasesCurrentAndQueuedSenders() = runTest {
|
||||||
|
val entered = CompletableDeferred<Unit>()
|
||||||
|
val writer = PriorityBlockWriter(backgroundScope) { entered.complete(Unit); awaitCancellation() }
|
||||||
|
val first = async { runCatching { writer.send(ubyteArrayOf(0u)) } }
|
||||||
|
entered.await()
|
||||||
|
val second = async { runCatching { writer.enqueue(ubyteArrayOf(1u), 1u).invoke() } }
|
||||||
|
runCurrent(); writer.close()
|
||||||
|
assertTrue(first.await().isFailure)
|
||||||
|
assertTrue(second.await().isFailure)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
@file:OptIn(ExperimentalUnsignedTypes::class, kotlinx.coroutines.ExperimentalCoroutinesApi::class)
|
||||||
|
package net.sergeych.kiloparsec.adapter
|
||||||
|
|
||||||
|
import kotlinx.coroutines.*
|
||||||
|
import kotlinx.coroutines.channels.Channel
|
||||||
|
import kotlinx.coroutines.test.*
|
||||||
|
import net.sergeych.crypto2.initCrypto
|
||||||
|
import net.sergeych.kiloparsec.*
|
||||||
|
import kotlin.math.ceil
|
||||||
|
import kotlin.test.*
|
||||||
|
|
||||||
|
class PriorityLinkTest {
|
||||||
|
@Test fun saturatedEncryptedLinkKeepsConcurrentControlResponsiveWithoutRateCap() = runTest {
|
||||||
|
initCrypto()
|
||||||
|
val bulk by command<UByteArray, Unit>()
|
||||||
|
val ping by command<Int, Int>()
|
||||||
|
val received = Channel<UByteArray>(Channel.UNLIMITED)
|
||||||
|
val aInput = Channel<UByteArray>(Channel.UNLIMITED)
|
||||||
|
val bInput = Channel<UByteArray>(Channel.UNLIMITED)
|
||||||
|
var sentBytes = 0L
|
||||||
|
val rate = 16_384
|
||||||
|
fun endpoint(input: Channel<UByteArray>, destination: Channel<UByteArray>): Transport.Device {
|
||||||
|
val writer = PriorityBlockWriter(backgroundScope) { block ->
|
||||||
|
delay(ceil(block.size * 1000.0 / rate).toLong())
|
||||||
|
sentBytes += block.size
|
||||||
|
destination.send(block)
|
||||||
|
}
|
||||||
|
return ProxyDevice(input, Channel(), doClose = { writer.close(); input.close() }).also { it.priorityWriter = writer }
|
||||||
|
}
|
||||||
|
val a = endpoint(aInput, bInput)
|
||||||
|
val b = endpoint(bInput, aInput)
|
||||||
|
val ready = CompletableDeferred<Unit>()
|
||||||
|
val api = KiloInterface<Unit>().apply {
|
||||||
|
on(bulk) { received.send(it) }
|
||||||
|
on(ping) { it }
|
||||||
|
}
|
||||||
|
val server = KiloServerConnection(api, b, Unit)
|
||||||
|
val client = KiloClientConnection(api, a, Unit)
|
||||||
|
val jobs = listOf(backgroundScope.launch { server.run() }, backgroundScope.launch { client.run { if (it) ready.complete(Unit) } })
|
||||||
|
try {
|
||||||
|
ready.await()
|
||||||
|
val start = currentTime
|
||||||
|
val initialBytes = sentBytes
|
||||||
|
val producers = listOf<RemoteInterface>(client, server).flatMap { sender ->
|
||||||
|
List(8) { backgroundScope.launch { while (isActive) sender.push(bulk, UByteArray(2000), priority = 0) } }
|
||||||
|
}
|
||||||
|
received.receive()
|
||||||
|
repeat(10) {
|
||||||
|
val began = currentTime
|
||||||
|
assertEquals(it, client.call(ping, it, priority = 100))
|
||||||
|
assertTrue(currentTime - began < 400, "control latency=${currentTime - began}")
|
||||||
|
delay(80)
|
||||||
|
}
|
||||||
|
val elapsed = currentTime - start
|
||||||
|
assertTrue((sentBytes - initialBytes) * 1000 / elapsed > rate * 1.6, "Writer must use available capacity")
|
||||||
|
producers.forEach { it.cancelAndJoin() }
|
||||||
|
} finally { jobs.forEach { it.cancelAndJoin() }; a.close(); b.close() }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
@file:OptIn(ExperimentalUnsignedTypes::class, kotlinx.coroutines.ExperimentalCoroutinesApi::class)
|
||||||
|
package net.sergeych.kiloparsec.adapter
|
||||||
|
|
||||||
|
import kotlinx.coroutines.*
|
||||||
|
import kotlinx.coroutines.test.*
|
||||||
|
import kotlinx.serialization.serializer
|
||||||
|
import net.sergeych.bintools.DataSource
|
||||||
|
import net.sergeych.bipack.BipackDecoder
|
||||||
|
import net.sergeych.bipack.BipackEncoder
|
||||||
|
import net.sergeych.kiloparsec.*
|
||||||
|
import net.sergeych.utools.pack
|
||||||
|
import net.sergeych.utools.unpack
|
||||||
|
import kotlin.test.*
|
||||||
|
|
||||||
|
class PriorityTest {
|
||||||
|
private fun block(priority: Int, id: Int = 1): UByteArray = pack<Transport.Block>(
|
||||||
|
Transport.Block.Call(id.toUInt(), "example", ubyteArrayOf(1u, 2u)).also { it.priority = priority })
|
||||||
|
|
||||||
|
@Test fun legacyBodyAndTrailerCompatibility() {
|
||||||
|
for (original in listOf(
|
||||||
|
Transport.Block.Call(123456u, "test", UByteArray(3500) { it.toUByte() }),
|
||||||
|
Transport.Block.Response(123456u, UByteArray(256)),
|
||||||
|
Transport.Block.Error(123456u, "code", "message", UByteArray(180)),
|
||||||
|
Transport.Block.Error(0u, "code", null, null),
|
||||||
|
)) {
|
||||||
|
val legacy = when (original) {
|
||||||
|
is Transport.Block.Call -> ubyteArrayOf(0u) + BipackEncoder.encode(original).asUByteArray()
|
||||||
|
is Transport.Block.Error -> ubyteArrayOf(1u) + BipackEncoder.encode(original).asUByteArray()
|
||||||
|
is Transport.Block.Response -> ubyteArrayOf(2u) + BipackEncoder.encode(original).asUByteArray()
|
||||||
|
}
|
||||||
|
assertContentEquals(legacy, pack<Transport.Block>(original))
|
||||||
|
assertEquals(0, unpack<Transport.Block>(legacy).priority)
|
||||||
|
for (priority in listOf(Int.MIN_VALUE, -1, 0, 1, 100, Int.MAX_VALUE)) {
|
||||||
|
original.priority = priority
|
||||||
|
val packed = pack<Transport.Block>(original)
|
||||||
|
assertEquals(priority, unpack<Transport.Block>(packed).priority)
|
||||||
|
assertEquals(priority, blockPriority(packed))
|
||||||
|
assertContentEquals(legacy, packed.copyOf(legacy.size))
|
||||||
|
// Legacy decoding invokes the original body serializer and ignores trailing bytes.
|
||||||
|
val oldRead = when (original) {
|
||||||
|
is Transport.Block.Call -> BipackDecoder.decode<Transport.Block.Call>(packed.drop(1).toUByteArray())
|
||||||
|
is Transport.Block.Response -> BipackDecoder.decode<Transport.Block.Response>(packed.drop(1).toUByteArray())
|
||||||
|
is Transport.Block.Error -> BipackDecoder.decode<Transport.Block.Error>(packed.drop(1).toUByteArray())
|
||||||
|
}
|
||||||
|
assertEquals(0, oldRead.priority)
|
||||||
|
}
|
||||||
|
assertFailsWith<DataSource.EndOfData> { unpack<Transport.Block>(legacy + ubyteArrayOf(1u)) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun numericOrderingStableTiesAndCancellation() = runTest {
|
||||||
|
val release = CompletableDeferred<Unit>()
|
||||||
|
val started = CompletableDeferred<Unit>()
|
||||||
|
val sent = mutableListOf<Pair<Int, UInt>>()
|
||||||
|
val writer = PriorityBlockWriter(backgroundScope) { bytes ->
|
||||||
|
val b = unpack<Transport.Block>(bytes) as Transport.Block.Call
|
||||||
|
if (b.id == 1u) { started.complete(Unit); release.await() }
|
||||||
|
sent += b.priority to b.id
|
||||||
|
}
|
||||||
|
val first = async { writer.send(block(0, 1)) }
|
||||||
|
started.await()
|
||||||
|
val queued = listOf(0 to 2, 100 to 3, 2 to 4, 100 to 5, -10 to 6).map { (p, id) ->
|
||||||
|
async { writer.send(block(p, id)) }
|
||||||
|
}
|
||||||
|
val cancelled = async { writer.send(block(Int.MAX_VALUE, 7)) }
|
||||||
|
runCurrent(); cancelled.cancelAndJoin()
|
||||||
|
release.complete(Unit)
|
||||||
|
first.await(); queued.awaitAll()
|
||||||
|
assertEquals(listOf(0 to 1u, 100 to 3u, 100 to 5u, 2 to 4u, 0 to 2u, -10 to 6u), sent)
|
||||||
|
writer.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun boundedAdmissionAndCloseReleaseWaiters() = runTest {
|
||||||
|
val started = CompletableDeferred<Unit>()
|
||||||
|
val writer = PriorityBlockWriter(backgroundScope, maxQueuedItems = 1) { started.complete(Unit); awaitCancellation() }
|
||||||
|
val sending = async { runCatching { writer.send(block(0)) } }
|
||||||
|
started.await()
|
||||||
|
val queued = async { runCatching { writer.send(block(2)) } }
|
||||||
|
runCurrent()
|
||||||
|
assertFailsWith<RemoteInterface.Exception> { writer.send(block(100)) }
|
||||||
|
writer.close()
|
||||||
|
assertIs<CancellationException>(sending.await().exceptionOrNull())
|
||||||
|
assertIs<RemoteInterface.ClosedException>(queued.await().exceptionOrNull())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
package net.sergeych.kiloparsec.adapter
|
|
||||||
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
package net.sergeych.kiloparsec.adapter
|
|
||||||
|
|
||||||
import kotlinx.coroutines.flow.Flow
|
|
||||||
|
|
||||||
actual fun NetworkAddress(host: String, port: Int): NetworkAddress {
|
|
||||||
TODO("Not yet implemented")
|
|
||||||
}
|
|
||||||
|
|
||||||
actual fun acceptTcpDevice(port: Int): Flow<InetTransportDevice> {
|
|
||||||
TODO("Not yet implemented")
|
|
||||||
}
|
|
||||||
|
|
||||||
actual suspend fun connectTcpDevice(address: NetworkAddress): InetTransportDevice {
|
|
||||||
TODO("Not yet implemented")
|
|
||||||
}
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
package net.sergeych.kiloparsec.adapter
|
|
||||||
|
|
||||||
import java.nio.channels.CompletionHandler
|
|
||||||
import kotlin.coroutines.Continuation
|
|
||||||
import kotlin.coroutines.resume
|
|
||||||
import kotlin.coroutines.resumeWithException
|
|
||||||
|
|
||||||
open class ContinuationHandler<T> : CompletionHandler<T, Continuation<T>> {
|
|
||||||
override fun completed(result: T, attachment: Continuation<T>) {
|
|
||||||
attachment.resume(result)
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun failed(exc: Throwable, attachment: Continuation<T>) {
|
|
||||||
attachment.resumeWithException(exc)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
object VoidCompletionHandler: ContinuationHandler<Void>()
|
|
||||||
|
|
||||||
object IntCompletionHandler: ContinuationHandler<Int>()
|
|
||||||
@@ -1,47 +0,0 @@
|
|||||||
package net.sergeych.kiloparsec.adapter
|
|
||||||
|
|
||||||
import kotlinx.coroutines.Dispatchers
|
|
||||||
import kotlinx.coroutines.flow.Flow
|
|
||||||
import kotlinx.coroutines.flow.flow
|
|
||||||
import kotlinx.coroutines.suspendCancellableCoroutine
|
|
||||||
import kotlinx.coroutines.withContext
|
|
||||||
import java.net.InetAddress
|
|
||||||
import java.net.InetSocketAddress
|
|
||||||
import java.nio.channels.AsynchronousServerSocketChannel
|
|
||||||
import java.nio.channels.AsynchronousSocketChannel
|
|
||||||
import kotlin.coroutines.suspendCoroutine
|
|
||||||
|
|
||||||
actual fun NetworkAddress(host: String, port: Int): NetworkAddress =
|
|
||||||
JvmNetworkAddress(InetAddress.getByName(host), port)
|
|
||||||
|
|
||||||
actual fun acceptTcpDevice(port: Int): Flow<InetTransportDevice> {
|
|
||||||
return flow {
|
|
||||||
val socket = withContext(Dispatchers.IO) {
|
|
||||||
AsynchronousServerSocketChannel.open().also {
|
|
||||||
it.bind(InetSocketAddress(port))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
while (true) {
|
|
||||||
val connectedSocket = suspendCancellableCoroutine { continuation ->
|
|
||||||
continuation.invokeOnCancellation {
|
|
||||||
socket.close()
|
|
||||||
}
|
|
||||||
socket.accept(continuation, ContinuationHandler())
|
|
||||||
}
|
|
||||||
emit(asyncSocketToDevice(connectedSocket))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Suppress("unused")
|
|
||||||
suspend fun connectTcpDevice(host: String, port: Int) = connectTcpDevice(NetworkAddress(host,port))
|
|
||||||
actual suspend fun connectTcpDevice(address: NetworkAddress): InetTransportDevice {
|
|
||||||
address as JvmNetworkAddress
|
|
||||||
val socket = withContext(Dispatchers.IO) {
|
|
||||||
AsynchronousSocketChannel.open()
|
|
||||||
}
|
|
||||||
suspendCoroutine { cont ->
|
|
||||||
socket.connect(address.socketAddress, cont, VoidCompletionHandler)
|
|
||||||
}
|
|
||||||
return asyncSocketToDevice(socket)
|
|
||||||
}
|
|
||||||
@@ -1,118 +0,0 @@
|
|||||||
package net.sergeych.kiloparsec.adapter
|
|
||||||
|
|
||||||
import kotlinx.coroutines.*
|
|
||||||
import kotlinx.coroutines.channels.BufferOverflow
|
|
||||||
import kotlinx.coroutines.channels.Channel
|
|
||||||
import net.sergeych.mp_logger.LogTag
|
|
||||||
import net.sergeych.mp_logger.exception
|
|
||||||
import net.sergeych.mp_logger.info
|
|
||||||
import net.sergeych.mp_logger.warning
|
|
||||||
import java.net.*
|
|
||||||
import java.util.concurrent.atomic.AtomicInteger
|
|
||||||
|
|
||||||
private val counter = AtomicInteger(0)
|
|
||||||
|
|
||||||
class JvmNetworkAddress(val inetAddress: InetAddress, override val port: Int) : NetworkAddress {
|
|
||||||
override val host: String by lazy { inetAddress.canonicalHostName }
|
|
||||||
override fun equals(other: Any?): Boolean {
|
|
||||||
if (this === other) return true
|
|
||||||
if (other !is JvmNetworkAddress) return false
|
|
||||||
|
|
||||||
if (inetAddress != other.inetAddress) return false
|
|
||||||
if (port != other.port) return false
|
|
||||||
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
val socketAddress: SocketAddress by lazy { InetSocketAddress(inetAddress,port) }
|
|
||||||
|
|
||||||
override fun hashCode(): Int {
|
|
||||||
var result = inetAddress.hashCode()
|
|
||||||
result = 31 * result + port
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun toString(): String = "$host:$port"
|
|
||||||
}
|
|
||||||
|
|
||||||
class UdpDatagram(override val message: UByteArray, val inetAddress: InetAddress, val port: Int) : Datagram {
|
|
||||||
|
|
||||||
override val address: NetworkAddress by lazy {
|
|
||||||
JvmNetworkAddress(inetAddress, port)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@OptIn(DelicateCoroutinesApi::class)
|
|
||||||
class UdpServer(val port: Int) :
|
|
||||||
DatagramConnector, LogTag("UDPS:${counter.incrementAndGet()}") {
|
|
||||||
private var isClosed = false
|
|
||||||
|
|
||||||
|
|
||||||
private val deferredSocket = CompletableDeferred<DatagramSocket>()
|
|
||||||
private var job: Job? = null
|
|
||||||
|
|
||||||
private suspend fun start() = try {
|
|
||||||
coroutineScope {
|
|
||||||
val socket = DatagramSocket(port)
|
|
||||||
val buffer = ByteArray(16384)
|
|
||||||
val packet = DatagramPacket(buffer, buffer.size)
|
|
||||||
deferredSocket.complete(socket)
|
|
||||||
while (isActive && !isClosed) {
|
|
||||||
try {
|
|
||||||
socket.receive(packet)
|
|
||||||
val data = packet.data.sliceArray(0..<packet.length)
|
|
||||||
val datagram = UdpDatagram(data.toUByteArray(), packet.address, packet.port)
|
|
||||||
if (!channel.trySend(datagram).isSuccess) {
|
|
||||||
warning { "packet lost!" }
|
|
||||||
// and we cause overflow that overwrites the oldest
|
|
||||||
channel.send(datagram)
|
|
||||||
}
|
|
||||||
} catch (e: Exception) {
|
|
||||||
if (!isClosed)
|
|
||||||
e.printStackTrace()
|
|
||||||
throw e
|
|
||||||
}
|
|
||||||
}
|
|
||||||
info { "closing socket and reception loop" }
|
|
||||||
|
|
||||||
}
|
|
||||||
} catch (_: CancellationException) {
|
|
||||||
info { "server is closed" }
|
|
||||||
} catch (t: Throwable) {
|
|
||||||
exception { "unexpected end of server" to t }
|
|
||||||
}
|
|
||||||
|
|
||||||
init {
|
|
||||||
job = GlobalScope.launch(Dispatchers.IO) {
|
|
||||||
start()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun close() {
|
|
||||||
if (!isClosed) {
|
|
||||||
if (deferredSocket.isCompleted) {
|
|
||||||
runCatching {
|
|
||||||
deferredSocket.getCompleted().close()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
isClosed = true
|
|
||||||
job?.cancel(); job = null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private val channel = Channel<Datagram>(2048, BufferOverflow.DROP_OLDEST)
|
|
||||||
override val incoming = channel
|
|
||||||
|
|
||||||
override suspend fun send(message: UByteArray, networkAddress: NetworkAddress) {
|
|
||||||
networkAddress as JvmNetworkAddress
|
|
||||||
withContext(Dispatchers.IO) {
|
|
||||||
val packet = DatagramPacket(
|
|
||||||
message.toByteArray(), message.size,
|
|
||||||
networkAddress.inetAddress, networkAddress.port
|
|
||||||
)
|
|
||||||
deferredSocket.await().send(packet)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,3 +1,13 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2025. Sergey S. Chernov - All Rights Reserved
|
||||||
|
*
|
||||||
|
* You may use, distribute and modify this code under the
|
||||||
|
* terms of the private license, which you must obtain from the author
|
||||||
|
*
|
||||||
|
* To obtain the license, contact the author: https://t.me/real_sergeych or email to
|
||||||
|
* real dot sergeych at gmail.
|
||||||
|
*/
|
||||||
|
|
||||||
package net.sergeych.kiloparsec.adapter
|
package net.sergeych.kiloparsec.adapter
|
||||||
|
|
||||||
import io.ktor.server.application.*
|
import io.ktor.server.application.*
|
||||||
@@ -10,27 +20,56 @@ import kotlinx.coroutines.channels.ClosedReceiveChannelException
|
|||||||
import kotlinx.coroutines.isActive
|
import kotlinx.coroutines.isActive
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import net.sergeych.crypto2.SigningKey
|
import net.sergeych.crypto2.SigningKey
|
||||||
import net.sergeych.crypto2.toDump
|
|
||||||
import net.sergeych.kiloparsec.KiloInterface
|
import net.sergeych.kiloparsec.KiloInterface
|
||||||
import net.sergeych.kiloparsec.KiloServerConnection
|
import net.sergeych.kiloparsec.KiloServerConnection
|
||||||
import net.sergeych.kiloparsec.RemoteInterface
|
import net.sergeych.kiloparsec.RemoteInterface
|
||||||
import net.sergeych.mp_logger.*
|
import net.sergeych.mp_logger.*
|
||||||
|
import net.sergeych.mp_tools.decodeBase64Compact
|
||||||
|
import net.sergeych.mp_tools.encodeToBase64Compact
|
||||||
import net.sergeych.tools.AtomicCounter
|
import net.sergeych.tools.AtomicCounter
|
||||||
import java.time.Duration
|
import kotlin.time.Duration.Companion.seconds
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a ktor-based websocket server.
|
||||||
|
* This call install Routing and WebSockets with proper configuration.
|
||||||
|
*
|
||||||
|
* The course of action is:
|
||||||
|
*
|
||||||
|
* - create LocalInterface and populate it with functionality
|
||||||
|
* - call this method with localInterface
|
||||||
|
* - optionally, connect the same interface with TCP or UDP providers on supported platforms,
|
||||||
|
* in which case it might be useful to hae session creating function [createSession] separate.
|
||||||
|
*
|
||||||
|
* _Note_: [KiloInterface] as for now does not contain session creation in it as we suggest
|
||||||
|
* session could be transport specific.
|
||||||
|
*
|
||||||
|
* @param localInterface where the actual work is performed.
|
||||||
|
* @param path default http path to the websocket.
|
||||||
|
* @param serverKey optional key to authenticate the connection. If the client specify expected
|
||||||
|
* server key it should match of connection will not be established.
|
||||||
|
* @param createSession function to create a server session.
|
||||||
|
*/
|
||||||
fun <S> Application.setupWebsocketServer(
|
fun <S> Application.setupWebsocketServer(
|
||||||
localInterface: KiloInterface<S>,
|
localInterface: KiloInterface<S>,
|
||||||
path: String = "/kp",
|
path: String = "/kp",
|
||||||
serverKey: SigningKey? = null,
|
serverKey: SigningKey? = null,
|
||||||
createSession: () -> S,
|
createSession: () -> S,
|
||||||
) {
|
) = setupWebsocketServer(localInterface, path, serverKey, {}, createSession)
|
||||||
|
|
||||||
install(Routing)
|
/** Configure transport keepalive without changing the legacy defaults for other applications. */
|
||||||
|
fun <S> Application.setupWebsocketServer(
|
||||||
|
localInterface: KiloInterface<S>,
|
||||||
|
path: String = "/kp",
|
||||||
|
serverKey: SigningKey? = null,
|
||||||
|
configureWebSockets: WebSockets.WebSocketOptions.() -> Unit,
|
||||||
|
createSession: () -> S,
|
||||||
|
) {
|
||||||
install(WebSockets) {
|
install(WebSockets) {
|
||||||
pingPeriod = Duration.ofSeconds(15)
|
pingPeriod = 60.seconds //Duration.ofSeconds(15)
|
||||||
timeout = Duration.ofSeconds(15)
|
timeout = 45.seconds
|
||||||
maxFrameSize = Long.MAX_VALUE
|
maxFrameSize = Long.MAX_VALUE
|
||||||
masking = false
|
masking = false
|
||||||
|
configureWebSockets()
|
||||||
}
|
}
|
||||||
val counter = AtomicCounter()
|
val counter = AtomicCounter()
|
||||||
routing {
|
routing {
|
||||||
@@ -38,23 +77,20 @@ fun <S> Application.setupWebsocketServer(
|
|||||||
val log = LogTag("KWS:${counter.incrementAndGet()}")
|
val log = LogTag("KWS:${counter.incrementAndGet()}")
|
||||||
log.debug { "opening the connection" }
|
log.debug { "opening the connection" }
|
||||||
val input = Channel<UByteArray>(256)
|
val input = Channel<UByteArray>(256)
|
||||||
val output = Channel<UByteArray>(256)
|
val output = Channel<UByteArray>()
|
||||||
|
var useBinary: Boolean? = null
|
||||||
|
val writer = PriorityBlockWriter(this) { block ->
|
||||||
|
if (useBinary == false) send(block.asByteArray().encodeToBase64Compact())
|
||||||
|
else send(block.asByteArray())
|
||||||
|
flush()
|
||||||
|
}
|
||||||
launch {
|
launch {
|
||||||
log.debug { "starting output pump" }
|
try { for (block in output) writer.send(block) }
|
||||||
while (isActive) {
|
finally { writer.close() }
|
||||||
try {
|
|
||||||
send(output.receive().toByteArray())
|
|
||||||
}
|
|
||||||
catch(_: ClosedReceiveChannelException) {
|
|
||||||
log.debug { "closing output pump as output channel is closed" }
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
log.debug { "closing output pump" }
|
|
||||||
}
|
}
|
||||||
val server = KiloServerConnection(
|
val server = KiloServerConnection(
|
||||||
localInterface,
|
localInterface,
|
||||||
ProxyDevice(input, output),
|
ProxyDevice(input, output).also { it.priorityWriter = writer },
|
||||||
createSession(),
|
createSession(),
|
||||||
serverKey
|
serverKey
|
||||||
)
|
)
|
||||||
@@ -64,12 +100,28 @@ fun <S> Application.setupWebsocketServer(
|
|||||||
}
|
}
|
||||||
log.debug { "KSC started, looking for incoming frames" }
|
log.debug { "KSC started, looking for incoming frames" }
|
||||||
for (f in incoming) {
|
for (f in incoming) {
|
||||||
log.debug { "incoming frame: ${f.frameType}" }
|
|
||||||
if (f is Frame.Binary)
|
|
||||||
try {
|
try {
|
||||||
input.send(f.readBytes().toUByteArray().also {
|
when (f) {
|
||||||
log.debug { "in frame\n${it.toDump()}" }
|
is Frame.Binary -> {
|
||||||
})
|
if (useBinary == null) {
|
||||||
|
log.debug { "Setting binary frame mode ------------------------------------" }
|
||||||
|
useBinary = true
|
||||||
|
}
|
||||||
|
input.send(f.readBytes().toUByteArray())
|
||||||
|
}
|
||||||
|
|
||||||
|
is Frame.Text -> {
|
||||||
|
if (useBinary == null) {
|
||||||
|
log.debug { "Setting text frame mode -----------------------------------" }
|
||||||
|
useBinary = false
|
||||||
|
}
|
||||||
|
input.send(f.readText().decodeBase64Compact().asUByteArray())
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> {
|
||||||
|
log.warning { "unexpected frame type ${f.frameType}, ignoring" }
|
||||||
|
}
|
||||||
|
}
|
||||||
} catch (_: RemoteInterface.ClosedException) {
|
} catch (_: RemoteInterface.ClosedException) {
|
||||||
log.warning { "caught local closed exception (strange!), closing" }
|
log.warning { "caught local closed exception (strange!), closing" }
|
||||||
break
|
break
|
||||||
@@ -80,8 +132,6 @@ fun <S> Application.setupWebsocketServer(
|
|||||||
log.exception { "unexpected exception, server connection will close" to t }
|
log.exception { "unexpected exception, server connection will close" to t }
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
else
|
|
||||||
log.warning { "unknown frame type ${f.frameType}, ignoring" }
|
|
||||||
}
|
}
|
||||||
log.debug { "closing the server" }
|
log.debug { "closing the server" }
|
||||||
close()
|
close()
|
||||||
|
|||||||
@@ -1,155 +0,0 @@
|
|||||||
package net.sergeych.kiloparsec.adapter
|
|
||||||
|
|
||||||
import kotlinx.coroutines.*
|
|
||||||
import kotlinx.coroutines.channels.Channel
|
|
||||||
import kotlinx.coroutines.channels.ClosedReceiveChannelException
|
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
|
||||||
import net.sergeych.crypto2.Contrail
|
|
||||||
import net.sergeych.crypto2.encodeVarUnsigned
|
|
||||||
import net.sergeych.crypto2.readVarUnsigned
|
|
||||||
import net.sergeych.kiloparsec.RemoteInterface
|
|
||||||
import net.sergeych.kiloparsec.Transport
|
|
||||||
import net.sergeych.mp_logger.LogTag
|
|
||||||
import net.sergeych.mp_logger.warning
|
|
||||||
import net.sergeych.mp_tools.globalLaunch
|
|
||||||
import net.sergeych.tools.waitFor
|
|
||||||
import java.net.InetSocketAddress
|
|
||||||
import java.net.StandardSocketOptions.TCP_NODELAY
|
|
||||||
import java.nio.ByteBuffer
|
|
||||||
import java.nio.channels.AsynchronousSocketChannel
|
|
||||||
import kotlin.coroutines.cancellation.CancellationException
|
|
||||||
import kotlin.coroutines.suspendCoroutine
|
|
||||||
|
|
||||||
private val log = LogTag("ASTD")
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Prepend block with its size, varint-encoded
|
|
||||||
*/
|
|
||||||
private fun encode(block: UByteArray): ByteArray {
|
|
||||||
val c = Contrail.create(block)
|
|
||||||
return (encodeVarUnsigned(c.size.toUInt()) + c).toByteArray()
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Convert asynchronous socket to a [Transport.Device] using non-blocking nio,
|
|
||||||
* in a coroutine-effective manner. Note that it runs coroutines to read/write
|
|
||||||
* to the socket in a global scope.These are closed when transport is closed
|
|
||||||
* or the socket is closed, for example, by network failure.
|
|
||||||
*/
|
|
||||||
suspend fun asyncSocketToDevice(socket: AsynchronousSocketChannel): InetTransportDevice {
|
|
||||||
val deferredDevice = CompletableDeferred<InetTransportDevice>()
|
|
||||||
globalLaunch {
|
|
||||||
coroutineScope {
|
|
||||||
val sendQueueEmpty = MutableStateFlow(true)
|
|
||||||
val receiving = MutableStateFlow(false)
|
|
||||||
// We're in block mode, every block we send worth immediate sending, we do not
|
|
||||||
// send partial blocks, so:
|
|
||||||
socket.setOption(TCP_NODELAY, true)
|
|
||||||
|
|
||||||
// socket input is to be parsed for blocks, so we receive bytes
|
|
||||||
// and decode them to blocks
|
|
||||||
val input = Channel<UByte>(1024)
|
|
||||||
val inputBlocks = Channel<UByteArray>()
|
|
||||||
// output is blocks, so we sent transformed, framed blocks:
|
|
||||||
val outputBlocks = Channel<UByteArray>()
|
|
||||||
|
|
||||||
fun stop() {
|
|
||||||
kotlin.runCatching { inputBlocks.close(RemoteInterface.ClosedException()) }
|
|
||||||
kotlin.runCatching { outputBlocks.close() }
|
|
||||||
socket.close()
|
|
||||||
cancel()
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// copy incoming data from the socket to input channel:
|
|
||||||
launch {
|
|
||||||
val data = ByteArray(1024)
|
|
||||||
val inb = ByteBuffer.wrap(data)
|
|
||||||
kotlin.runCatching {
|
|
||||||
while (isActive) {
|
|
||||||
inb.position(0)
|
|
||||||
val size: Int = suspendCoroutine { continuation ->
|
|
||||||
socket.read(inb, continuation, IntCompletionHandler)
|
|
||||||
}
|
|
||||||
if (size < 0) stop()
|
|
||||||
else {
|
|
||||||
// println("recvd:\n${data.sliceArray(0..<size).toDump()}\n------------------")
|
|
||||||
for (i in 0..<size) input.send(data[i].toUByte())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// copy from output to socket:
|
|
||||||
launch {
|
|
||||||
try {
|
|
||||||
while (isActive) {
|
|
||||||
// wait for the first block to send
|
|
||||||
sendQueueEmpty.value = outputBlocks.isEmpty
|
|
||||||
var data = encode(outputBlocks.receive())
|
|
||||||
|
|
||||||
// now we're sending, so queue state is sending:
|
|
||||||
sendQueueEmpty.value = false
|
|
||||||
|
|
||||||
// if there are more, take them all (NO_DELAY optimization)
|
|
||||||
while (!outputBlocks.isEmpty)
|
|
||||||
data += encode(outputBlocks.receive())
|
|
||||||
|
|
||||||
// now send it all together:
|
|
||||||
val outBuff = ByteBuffer.wrap(data)
|
|
||||||
val cnt = suspendCoroutine { continuation ->
|
|
||||||
socket.write(outBuff, continuation, IntCompletionHandler)
|
|
||||||
}
|
|
||||||
// be sure it was all sent
|
|
||||||
if (outBuff.position() != data.size || cnt != data.size) {
|
|
||||||
throw RuntimeException("unexpected partial write")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// in the case of just breaking out of the loop:
|
|
||||||
sendQueueEmpty.value = true
|
|
||||||
} catch (_: ClosedReceiveChannelException) {
|
|
||||||
stop()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// transport device copes with blocks:
|
|
||||||
// decode blocks from a byte channel read from the socket:
|
|
||||||
launch {
|
|
||||||
try {
|
|
||||||
while (isActive) {
|
|
||||||
receiving.value = !input.isEmpty
|
|
||||||
val size = readVarUnsigned(input)
|
|
||||||
receiving.value = true
|
|
||||||
if (size == 0u) log.warning { "zero size block is ignored!" }
|
|
||||||
else {
|
|
||||||
val block = UByteArray(size.toInt())
|
|
||||||
for (i in 0..<size.toInt()) {
|
|
||||||
block[i] = input.receive()
|
|
||||||
}
|
|
||||||
Contrail.unpack(block)?.let { inputBlocks.send(it) }
|
|
||||||
?: log.warning { "skipping bad block ${block.size} bytes" }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (_: CancellationException) {
|
|
||||||
} catch (_: ClosedReceiveChannelException) {
|
|
||||||
stop()
|
|
||||||
}
|
|
||||||
receiving.value = false
|
|
||||||
}
|
|
||||||
|
|
||||||
val addr = socket.remoteAddress as InetSocketAddress
|
|
||||||
deferredDevice.complete(
|
|
||||||
InetTransportDevice(inputBlocks, outputBlocks, JvmNetworkAddress(addr.address, addr.port), {
|
|
||||||
yield()
|
|
||||||
// wait until all received data are parsed, but not too long
|
|
||||||
withTimeoutOrNull(500) {
|
|
||||||
receiving.waitFor { !it }
|
|
||||||
}
|
|
||||||
// then stop it
|
|
||||||
stop()
|
|
||||||
})
|
|
||||||
)
|
|
||||||
}
|
|
||||||
globalLaunch { socket.close() }
|
|
||||||
}
|
|
||||||
return deferredDevice.await()
|
|
||||||
}
|
|
||||||
@@ -1,23 +1,37 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2025. Sergey S. Chernov - All Rights Reserved
|
||||||
|
*
|
||||||
|
* You may use, distribute and modify this code under the
|
||||||
|
* terms of the private license, which you must obtain from the author
|
||||||
|
*
|
||||||
|
* To obtain the license, contact the author: https://t.me/real_sergeych or email to
|
||||||
|
* real dot sergeych at gmail.
|
||||||
|
*/
|
||||||
|
|
||||||
package net.sergeych.kiloparsec
|
package net.sergeych.kiloparsec
|
||||||
|
|
||||||
import assertThrows
|
import assertThrows
|
||||||
import io.ktor.server.engine.*
|
import io.ktor.server.engine.*
|
||||||
import io.ktor.server.netty.*
|
import io.ktor.server.netty.*
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.runBlocking
|
||||||
import kotlinx.coroutines.test.runTest
|
import kotlinx.coroutines.test.runTest
|
||||||
|
import net.sergeych.crypto2.SigningSecretKey
|
||||||
import net.sergeych.crypto2.initCrypto
|
import net.sergeych.crypto2.initCrypto
|
||||||
import net.sergeych.kiloparsec.adapter.acceptTcpDevice
|
|
||||||
import net.sergeych.kiloparsec.adapter.connectTcpDevice
|
|
||||||
import net.sergeych.kiloparsec.adapter.setupWebsocketServer
|
import net.sergeych.kiloparsec.adapter.setupWebsocketServer
|
||||||
import net.sergeych.kiloparsec.adapter.websocketClient
|
import net.sergeych.kiloparsec.adapter.websocketClient
|
||||||
|
import net.sergeych.kiloparsec.adapter.websocketTransportDevice
|
||||||
import net.sergeych.mp_logger.Log
|
import net.sergeych.mp_logger.Log
|
||||||
import java.net.InetAddress
|
import java.net.InetAddress
|
||||||
import kotlin.test.*
|
import kotlin.random.Random
|
||||||
|
import kotlin.test.Test
|
||||||
|
import kotlin.test.assertEquals
|
||||||
|
import kotlin.test.assertFalse
|
||||||
|
import kotlin.test.assertTrue
|
||||||
|
|
||||||
class ClientTest {
|
class ClientTest {
|
||||||
|
|
||||||
class TestException : Exception("test1")
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun testAddresses() {
|
fun testAddresses() {
|
||||||
println(InetAddress.getLocalHost())
|
println(InetAddress.getLocalHost())
|
||||||
@@ -25,62 +39,10 @@ class ClientTest {
|
|||||||
println(InetAddress.getByName("127.0.0.1"))
|
println(InetAddress.getByName("127.0.0.1"))
|
||||||
println(InetAddress.getByName("mail.ru"))
|
println(InetAddress.getByName("mail.ru"))
|
||||||
}
|
}
|
||||||
@Test
|
|
||||||
fun testClient() = runTest {
|
|
||||||
initCrypto()
|
|
||||||
Log.connectConsole(Log.Level.DEBUG)
|
|
||||||
data class Session(
|
|
||||||
var data: String
|
|
||||||
)
|
|
||||||
|
|
||||||
val cmdSave by command<String,Unit>()
|
|
||||||
val cmdLoad by command<Unit,String>()
|
|
||||||
val cmdDrop by command<Unit,Unit>()
|
|
||||||
val cmdException by command<Unit,Unit>()
|
|
||||||
|
|
||||||
val cli = KiloInterface<Session>().apply {
|
|
||||||
registerError { TestException() }
|
|
||||||
onConnected { session.data = "start" }
|
|
||||||
on(cmdSave) { session.data = it }
|
|
||||||
on(cmdLoad) {
|
|
||||||
session.data
|
|
||||||
}
|
|
||||||
on(cmdException) {
|
|
||||||
throw TestException()
|
|
||||||
}
|
|
||||||
on(cmdDrop) {
|
|
||||||
throw LocalInterface.BreakConnectionException()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
val server = KiloServer(cli, acceptTcpDevice(17101)) {
|
|
||||||
Session("unknown")
|
|
||||||
}
|
|
||||||
|
|
||||||
val client = KiloClient<Unit>() {
|
|
||||||
addErrors(cli)
|
|
||||||
connect { connectTcpDevice("localhost:17101") }
|
|
||||||
}
|
|
||||||
println(client.call(cmdLoad))
|
|
||||||
|
|
||||||
assertEquals("start", client.call(cmdLoad))
|
|
||||||
client.call(cmdSave, "foobar")
|
|
||||||
assertEquals("foobar", client.call(cmdLoad))
|
|
||||||
|
|
||||||
val res = kotlin.runCatching { client.call(cmdException) }
|
|
||||||
println(res.exceptionOrNull())
|
|
||||||
assertIs<TestException>(res.exceptionOrNull())
|
|
||||||
assertEquals("foobar", client.call(cmdLoad))
|
|
||||||
|
|
||||||
assertThrows<RemoteInterface.ClosedException> { client.call(cmdDrop) }
|
|
||||||
|
|
||||||
// reconnect?
|
|
||||||
assertEquals("start", client.call(cmdLoad))
|
|
||||||
|
|
||||||
server.close()
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun webSocketTest() = runTest {
|
fun webSocketTest1() = runTest {
|
||||||
initCrypto()
|
initCrypto()
|
||||||
// fun Application.
|
// fun Application.
|
||||||
val cmdClose by command<Unit, Unit>()
|
val cmdClose by command<Unit, Unit>()
|
||||||
@@ -91,6 +53,7 @@ class ClientTest {
|
|||||||
Log.connectConsole(Log.Level.DEBUG)
|
Log.connectConsole(Log.Level.DEBUG)
|
||||||
|
|
||||||
data class Session(var foo: String = "not set")
|
data class Session(var foo: String = "not set")
|
||||||
|
|
||||||
var closeCounter = 0
|
var closeCounter = 0
|
||||||
val serverInterface = KiloInterface<Session>().apply {
|
val serverInterface = KiloInterface<Session>().apply {
|
||||||
var connectedCalled = false
|
var connectedCalled = false
|
||||||
@@ -100,27 +63,23 @@ class ClientTest {
|
|||||||
on(cmdCheckConnected) { connectedCalled }
|
on(cmdCheckConnected) { connectedCalled }
|
||||||
on(cmdClose) {
|
on(cmdClose) {
|
||||||
throw LocalInterface.BreakConnectionException()
|
throw LocalInterface.BreakConnectionException()
|
||||||
// if( closeCounter < 2 ) {
|
|
||||||
// println("-------------------------- call close!")
|
|
||||||
// throw RemoteInterface.ClosedException()
|
|
||||||
// }
|
|
||||||
// else {
|
|
||||||
// println("close counter $closeCounter, ignoring")
|
|
||||||
// }
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// val server = setupWebsoketServer()
|
|
||||||
val ns: NettyApplicationEngine = embeddedServer(Netty, port = 8080, host = "0.0.0.0", module = {
|
val port = Random.nextInt(8080, 9090)
|
||||||
|
val ns = embeddedServer(Netty, port = port, host = "0.0.0.0", module = {
|
||||||
setupWebsocketServer(serverInterface) { Session() }
|
setupWebsocketServer(serverInterface) { Session() }
|
||||||
}).start(wait = false)
|
}).start(wait = false)
|
||||||
|
|
||||||
val client = websocketClient<Unit>("ws://localhost:8080/kp")
|
val client = websocketClient<Unit>("ws://localhost:$port/kp")
|
||||||
val states = mutableListOf<Boolean>()
|
val states = mutableListOf<Boolean>()
|
||||||
val collector = launch {
|
val collector = launch {
|
||||||
client.connectedStateFlow.collect {
|
client.connectedStateFlow.collect {
|
||||||
println("got: $closeCounter/$it")
|
println("got: $closeCounter/$it")
|
||||||
states += it
|
states += it
|
||||||
if( !it) { closeCounter++ }
|
if (!it) {
|
||||||
|
closeCounter++
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
assertEquals(true, client.call(cmdCheckConnected))
|
assertEquals(true, client.call(cmdCheckConnected))
|
||||||
@@ -135,6 +94,9 @@ class ClientTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// connection should now be closed
|
// connection should now be closed
|
||||||
|
// the problem is: it needs some unspecified time to close
|
||||||
|
// as it is async process.
|
||||||
|
delay(100)
|
||||||
assertFalse { client.connectedStateFlow.value }
|
assertFalse { client.connectedStateFlow.value }
|
||||||
|
|
||||||
// this should be run on automatically reopen connection
|
// this should be run on automatically reopen connection
|
||||||
@@ -148,4 +110,101 @@ class ClientTest {
|
|||||||
// println("stopped server")
|
// println("stopped server")
|
||||||
// println("closed client")
|
// println("closed client")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun webSocketTest2() = runTest {
|
||||||
|
initCrypto()
|
||||||
|
// fun Application.
|
||||||
|
val cmdClose by command<Unit, Unit>()
|
||||||
|
val cmdGetFoo by command<Unit, String>()
|
||||||
|
val cmdSetFoo by command<String, Unit>()
|
||||||
|
val cmdCheckConnected by command<Unit, Boolean>()
|
||||||
|
|
||||||
|
Log.connectConsole(Log.Level.DEBUG)
|
||||||
|
|
||||||
|
data class Session(var foo: String = "not set")
|
||||||
|
|
||||||
|
var closeCounter = 0
|
||||||
|
val serverInterface = KiloInterface<Session>().apply {
|
||||||
|
var connectedCalled = false
|
||||||
|
onConnected { connectedCalled = true }
|
||||||
|
on(cmdGetFoo) { session.foo }
|
||||||
|
on(cmdSetFoo) { session.foo = it }
|
||||||
|
on(cmdCheckConnected) { connectedCalled }
|
||||||
|
on(cmdClose) {
|
||||||
|
throw LocalInterface.BreakConnectionException()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val port = Random.nextInt(8080, 9090)
|
||||||
|
val ns = embeddedServer(Netty, port = port, host = "0.0.0.0", module = {
|
||||||
|
setupWebsocketServer(serverInterface) { Session() }
|
||||||
|
}).start(wait = false)
|
||||||
|
|
||||||
|
val client = websocketClient<Unit>("ws://localhost:$port/kp", useTextFrames = true)
|
||||||
|
val states = mutableListOf<Boolean>()
|
||||||
|
val collector = launch {
|
||||||
|
client.connectedStateFlow.collect {
|
||||||
|
println("got: $closeCounter/$it")
|
||||||
|
states += it
|
||||||
|
if (!it) {
|
||||||
|
closeCounter++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assertEquals(true, client.call(cmdCheckConnected))
|
||||||
|
assertTrue { client.connectedStateFlow.value }
|
||||||
|
assertEquals("not set", client.call(cmdGetFoo))
|
||||||
|
client.call(cmdSetFoo, "foo")
|
||||||
|
assertEquals("foo", client.call(cmdGetFoo))
|
||||||
|
|
||||||
|
client.close()
|
||||||
|
ns.stop()
|
||||||
|
collector.cancel()
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun webSocketWaitForConnectTest() = runBlocking {
|
||||||
|
initCrypto()
|
||||||
|
// fun Application.
|
||||||
|
Log.connectConsole(Log.Level.DEBUG)
|
||||||
|
|
||||||
|
val clientInterface = KiloInterface<Unit>().apply {}
|
||||||
|
|
||||||
|
val port = Random.nextInt(8080, 9090)
|
||||||
|
var clientConnectCalls = 0
|
||||||
|
// It should repeatedly reconnect, and we will count:
|
||||||
|
KiloClient(clientInterface, SigningSecretKey.new()) {
|
||||||
|
clientConnectCalls++
|
||||||
|
KiloConnectionData(websocketTransportDevice("ws://localhost:$port/kp", true), Unit)
|
||||||
|
}
|
||||||
|
delay(1200)
|
||||||
|
// and check:
|
||||||
|
// println("connection attemtps: $clientConnectCalls")
|
||||||
|
assertTrue { clientConnectCalls > 1 }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun webSocketWaitForConnectTest2() = runBlocking {
|
||||||
|
initCrypto()
|
||||||
|
// fun Application.
|
||||||
|
Log.connectConsole(Log.Level.DEBUG)
|
||||||
|
|
||||||
|
val clientInterface = KiloInterface<Unit>().apply {}
|
||||||
|
|
||||||
|
val port = Random.nextInt(8080, 9090)
|
||||||
|
var clientConnectCalls = 0
|
||||||
|
// It should repeatedly reconnect, and we will count:
|
||||||
|
KiloClient(clientInterface, SigningSecretKey.new()) {
|
||||||
|
clientConnectCalls++
|
||||||
|
KiloConnectionData(websocketTransportDevice("ws://localhost:$port/kp", false), Unit)
|
||||||
|
}
|
||||||
|
delay(1200)
|
||||||
|
// and check:
|
||||||
|
// println("connection attemtps: $clientConnectCalls")
|
||||||
|
assertTrue { clientConnectCalls > 1 }
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
package net.sergeych.kiloparsec
|
||||||
|
|
||||||
|
import kotlinx.coroutines.*
|
||||||
|
import kotlinx.coroutines.channels.Channel
|
||||||
|
import kotlinx.coroutines.flow.first
|
||||||
|
import net.sergeych.crypto2.initCrypto
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger
|
||||||
|
import kotlin.test.*
|
||||||
|
|
||||||
|
class ConnectionHealthTest {
|
||||||
|
@Test(timeout = 15_000)
|
||||||
|
fun silentHandshakesExhaustBudgetAndReleaseWaitingCalls() = runBlocking {
|
||||||
|
initCrypto()
|
||||||
|
val attempts = AtomicInteger()
|
||||||
|
val closes = AtomicInteger()
|
||||||
|
val client = KiloClient(KiloInterface<Unit>(), options = ReconnectionOptions(
|
||||||
|
health = ConnectionHealth(50, 50), maxAttempts = 3,
|
||||||
|
connectTimeoutMillis = 100, retryDelayMillis = 10,
|
||||||
|
)) {
|
||||||
|
attempts.incrementAndGet()
|
||||||
|
KiloConnectionData(object : Transport.Device {
|
||||||
|
val closed = java.util.concurrent.atomic.AtomicBoolean()
|
||||||
|
override val input = Channel<UByteArray>(16)
|
||||||
|
override val output = Channel<UByteArray>(16)
|
||||||
|
override suspend fun close() { if (closed.compareAndSet(false, true)) closes.incrementAndGet(); input.cancel(); output.cancel() }
|
||||||
|
}, Unit)
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
val waiter = async { runCatching { client.token() } }
|
||||||
|
withTimeout(10_000) { client.reconnectExhausted.first { it } }
|
||||||
|
assertEquals(3, attempts.get())
|
||||||
|
assertEquals(3, closes.get())
|
||||||
|
assertFalse(client.connectedStateFlow.value)
|
||||||
|
assertTrue(withTimeout(1_000) { waiter.await() }.isFailure)
|
||||||
|
val missing by command<Unit, Unit>()
|
||||||
|
repeat(2) {
|
||||||
|
withTimeout(1_000) {
|
||||||
|
assertFailsWith<RemoteInterface.ClosedException> { client.call(missing, Unit) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
delay(200)
|
||||||
|
assertEquals(3, attempts.get(), "An exhausted client must not reconnect forever")
|
||||||
|
} finally { client.close() }
|
||||||
|
}
|
||||||
|
@Test(timeout = 15_000)
|
||||||
|
fun establishedSilentLossTriggersHeartbeatAndBoundedRecovery() = runBlocking {
|
||||||
|
initCrypto()
|
||||||
|
val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
|
||||||
|
val blocked = java.util.concurrent.atomic.AtomicBoolean()
|
||||||
|
val attempts = AtomicInteger()
|
||||||
|
val api = object : KiloInterface<Unit>() {
|
||||||
|
override suspend fun execute(scope: KiloScope<Unit>, name: String, packedArgs: UByteArray): UByteArray {
|
||||||
|
error("Heartbeat must bypass application command dispatch")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val client = KiloClient(KiloInterface<Unit>(), options = ReconnectionOptions(
|
||||||
|
health = ConnectionHealth(100, 100), maxAttempts = 3,
|
||||||
|
connectTimeoutMillis = 300, retryDelayMillis = 10,
|
||||||
|
)) {
|
||||||
|
attempts.incrementAndGet()
|
||||||
|
val requests = Channel<UByteArray>(16)
|
||||||
|
val forwarded = Channel<UByteArray>(16)
|
||||||
|
val responses = Channel<UByteArray>(16)
|
||||||
|
val pump = scope.launch { for (block in requests) if (!blocked.get()) forwarded.send(block) }
|
||||||
|
suspend fun retire() { pump.cancel(); requests.cancel(); forwarded.cancel(); responses.cancel() }
|
||||||
|
val serverDevice = object : Transport.Device {
|
||||||
|
override val input = forwarded
|
||||||
|
override val output = responses
|
||||||
|
override suspend fun close() { retire() }
|
||||||
|
}
|
||||||
|
scope.launch { runCatching { KiloServerConnection(api, serverDevice, Unit).run() } }
|
||||||
|
KiloConnectionData(object : Transport.Device {
|
||||||
|
override val input = responses
|
||||||
|
override val output = requests
|
||||||
|
override suspend fun close() { retire() }
|
||||||
|
}, Unit)
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
withTimeout(5_000) { client.connectedStateFlow.first { it } }
|
||||||
|
// Several successful native encrypted heartbeats; no application RPC is exported.
|
||||||
|
client.ping()
|
||||||
|
delay(800)
|
||||||
|
assertTrue(client.connectedStateFlow.value)
|
||||||
|
assertEquals(1, attempts.get())
|
||||||
|
blocked.set(true)
|
||||||
|
withTimeout(5_000) { client.reconnectExhausted.first { it } }
|
||||||
|
// The healthy session earns a new budget: three failed recovery connections.
|
||||||
|
assertEquals(4, attempts.get())
|
||||||
|
assertFalse(client.connectedStateFlow.value)
|
||||||
|
delay(400)
|
||||||
|
assertEquals(4, attempts.get())
|
||||||
|
} finally { client.close(); scope.coroutineContext[Job]!!.cancelAndJoin() }
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
@file:OptIn(ExperimentalUnsignedTypes::class)
|
||||||
|
package net.sergeych.kiloparsec.adapter
|
||||||
|
|
||||||
|
import kotlinx.coroutines.*
|
||||||
|
import kotlinx.coroutines.channels.Channel
|
||||||
|
import net.sergeych.crypto2.SigningSecretKey
|
||||||
|
import net.sergeych.crypto2.initCrypto
|
||||||
|
import net.sergeych.kiloparsec.*
|
||||||
|
import net.sergeych.utools.unpack
|
||||||
|
import kotlin.test.*
|
||||||
|
|
||||||
|
/** Real loopback carriers; impairment occurs before writing actual datagrams. */
|
||||||
|
class CarrierReleaseTest {
|
||||||
|
@Test fun udpDuplicatesReorderingAndConcurrentDuplex() = carrier(udp = true)
|
||||||
|
@Test fun tcpConcurrentDuplexAndPriority() = carrier(udp = false)
|
||||||
|
|
||||||
|
private fun carrier(udp: Boolean) = runBlocking {
|
||||||
|
withTimeout(20_000) {
|
||||||
|
initCrypto()
|
||||||
|
val tcp = if (!udp) TcpServer(0, "127.0.0.1") else null
|
||||||
|
val datagrams = if (udp) UdpServer(0, "127.0.0.1") else null
|
||||||
|
val received = Channel<Int>(Channel.UNLIMITED)
|
||||||
|
val echo by command<Int, Int>()
|
||||||
|
val notify by command<Int, Unit>()
|
||||||
|
val api = KiloInterface<Unit>().apply {
|
||||||
|
on(echo) { it }
|
||||||
|
on(notify) { received.send(it) }
|
||||||
|
}
|
||||||
|
val serverReady = CompletableDeferred<KiloServerConnection<Unit>>()
|
||||||
|
val serverKey = SigningSecretKey.new()
|
||||||
|
val collector = launch {
|
||||||
|
(tcp?.transportFlow ?: datagrams!!.transportFlow).collect { device ->
|
||||||
|
val server = KiloServerConnection(api, device, Unit, serverKey)
|
||||||
|
serverReady.complete(server)
|
||||||
|
launch { server.run() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val port = tcp?.boundPort() ?: datagrams!!.boundPort()
|
||||||
|
val raw = if (udp) connectUdpDevice(NetworkAddress("127.0.0.1", port))
|
||||||
|
else connectTcpDevice(NetworkAddress("127.0.0.1", port))
|
||||||
|
var held: UByteArray? = null
|
||||||
|
var impaired = false
|
||||||
|
val device = object : Transport.Device by raw {
|
||||||
|
override suspend fun send(block: UByteArray) {
|
||||||
|
val decoded = unpack<Transport.Block>(block)
|
||||||
|
if (udp && !impaired && decoded is Transport.Block.Call && decoded.name == "L0Call" && decoded.id == 0u) {
|
||||||
|
val first = held
|
||||||
|
if (first == null) held = block
|
||||||
|
else {
|
||||||
|
raw.send(block)
|
||||||
|
raw.send(first)
|
||||||
|
raw.send(first) // exact duplicate over the real UDP socket
|
||||||
|
impaired = true
|
||||||
|
}
|
||||||
|
} else raw.send(block)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val ready = CompletableDeferred<Unit>()
|
||||||
|
val clientApi = KiloInterface<Unit>().apply {
|
||||||
|
onConnected { if (remoteIdentity != serverKey.verifyingKey) throw RemoteInterface.SecurityException() }
|
||||||
|
on(echo) { it }
|
||||||
|
}
|
||||||
|
val client = KiloClientConnection(clientApi, device, Unit)
|
||||||
|
val clientJob = launch { client.run { if (it) ready.complete(Unit) } }
|
||||||
|
try {
|
||||||
|
ready.await()
|
||||||
|
val server = serverReady.await()
|
||||||
|
client.push(notify, 1)
|
||||||
|
client.push(notify, 2)
|
||||||
|
val notices = setOf(received.receive(), received.receive())
|
||||||
|
assertEquals(setOf(1, 2), notices)
|
||||||
|
coroutineScope {
|
||||||
|
(0 until 32).map { n -> async {
|
||||||
|
val peer: RemoteInterface = if (n % 2 == 0) client else server
|
||||||
|
assertEquals(n, peer.call(echo, n, priority = if (n % 3 == 0) 100 else 0))
|
||||||
|
} }.awaitAll()
|
||||||
|
}
|
||||||
|
client.ping()
|
||||||
|
assertNull(withTimeoutOrNull(100) { received.receive() }, "Duplicate must not execute again")
|
||||||
|
assertTrue(clientJob.isActive)
|
||||||
|
if (udp) assertTrue(impaired)
|
||||||
|
} finally {
|
||||||
|
clientJob.cancelAndJoin()
|
||||||
|
raw.close()
|
||||||
|
collector.cancelAndJoin()
|
||||||
|
tcp?.close(); datagrams?.close()
|
||||||
|
received.close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
package net.sergeych.kiloparsec.adapter
|
||||||
|
|
||||||
|
import java.net.DatagramPacket
|
||||||
|
import java.net.DatagramSocket
|
||||||
|
import java.net.InetAddress
|
||||||
|
import kotlinx.coroutines.*
|
||||||
|
import kotlinx.coroutines.channels.Channel
|
||||||
|
import kotlin.test.*
|
||||||
|
|
||||||
|
class SocketLifecycleTest {
|
||||||
|
@Test fun tcpRoundTripAndRebind() = runBlocking {
|
||||||
|
withTimeout(10_000) {
|
||||||
|
val server = TcpServer(0, "127.0.0.1")
|
||||||
|
val port = server.boundPort()
|
||||||
|
val accepted = Channel<InetTransportDevice>(1)
|
||||||
|
val collector = launch { runCatching { server.transportFlow.collect { accepted.send(it) } } }
|
||||||
|
val client = connectTcpDevice(NetworkAddress("127.0.0.1", port))
|
||||||
|
val peer = accepted.receive()
|
||||||
|
try {
|
||||||
|
val payload = ubyteArrayOf(2u, 3u, 4u)
|
||||||
|
client.output.send(payload)
|
||||||
|
assertContentEquals(payload, peer.input.receive())
|
||||||
|
peer.output.send(payload)
|
||||||
|
assertContentEquals(payload, client.input.receive())
|
||||||
|
} finally { client.close(); server.close(); collector.cancelAndJoin() }
|
||||||
|
val replacement = TcpServer(port, "127.0.0.1")
|
||||||
|
try { assertEquals(port, replacement.boundPort()) } finally { replacement.close() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun udpMalformedPacketDoesNotStopListenerAndRebind() = runBlocking {
|
||||||
|
withTimeout(10_000) {
|
||||||
|
val server = UdpServer(0, "127.0.0.1")
|
||||||
|
val port = server.boundPort()
|
||||||
|
val accepted = Channel<InetTransportDevice>(1)
|
||||||
|
val collector = launch { server.transportFlow.collect { accepted.send(it) } }
|
||||||
|
DatagramSocket().use { socket ->
|
||||||
|
socket.send(DatagramPacket(byteArrayOf(1), 1, InetAddress.getLoopbackAddress(), port))
|
||||||
|
}
|
||||||
|
val client = connectUdpDevice(NetworkAddress("127.0.0.1", port))
|
||||||
|
try {
|
||||||
|
val payload = ubyteArrayOf(2u, 3u, 4u)
|
||||||
|
client.output.send(payload)
|
||||||
|
val peer = accepted.receive()
|
||||||
|
assertContentEquals(payload, peer.input.receive())
|
||||||
|
peer.output.send(payload)
|
||||||
|
assertContentEquals(payload, client.input.receive())
|
||||||
|
} finally { client.close(); server.close(); collector.cancelAndJoin() }
|
||||||
|
val replacement = UdpServer(port, "127.0.0.1")
|
||||||
|
try { assertEquals(port, replacement.boundPort()) } finally { replacement.close() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun deviceCloseWorksInCancelledContext() = runBlocking {
|
||||||
|
withTimeout(10_000) {
|
||||||
|
val tcp = TcpServer(0, "127.0.0.1")
|
||||||
|
val udp = UdpServer(0, "127.0.0.1")
|
||||||
|
val peers = Channel<InetTransportDevice>(2)
|
||||||
|
val tcpCollector = launch { runCatching { tcp.transportFlow.collect { peers.send(it) } } }
|
||||||
|
val udpCollector = launch { udp.transportFlow.collect { peers.send(it) } }
|
||||||
|
val tcpClient = connectTcpDevice(NetworkAddress("127.0.0.1", tcp.boundPort()))
|
||||||
|
val udpClient = connectUdpDevice(NetworkAddress("127.0.0.1", udp.boundPort()))
|
||||||
|
udpClient.output.send(ubyteArrayOf(2u, 3u))
|
||||||
|
val firstPeer = peers.receive()
|
||||||
|
val secondPeer = peers.receive()
|
||||||
|
try {
|
||||||
|
val closer = launch(start = CoroutineStart.UNDISPATCHED) {
|
||||||
|
currentCoroutineContext().cancel()
|
||||||
|
tcpClient.close()
|
||||||
|
udpClient.close()
|
||||||
|
}
|
||||||
|
closer.join()
|
||||||
|
// EOF reaches both peers even when caller cancellation precedes close.
|
||||||
|
for (peer in listOf(firstPeer, secondPeer)) {
|
||||||
|
while (peer.input.receiveCatching().isSuccess) { }
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
tcpClient.close(); udpClient.close(); tcp.close(); udp.close()
|
||||||
|
tcpCollector.cancelAndJoin(); udpCollector.cancelAndJoin()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun bindFailuresAreReported() = runBlocking {
|
||||||
|
val tcp = TcpServer(0, "127.0.0.1")
|
||||||
|
val udp = UdpServer(0, "127.0.0.1")
|
||||||
|
try {
|
||||||
|
val duplicateTcp = TcpServer(tcp.boundPort(), "127.0.0.1")
|
||||||
|
try { assertFails { duplicateTcp.boundPort() } } finally { duplicateTcp.close() }
|
||||||
|
val duplicateUdp = UdpServer(udp.boundPort(), "127.0.0.1")
|
||||||
|
try { assertFails { duplicateUdp.boundPort() } } finally { duplicateUdp.close() }
|
||||||
|
} finally { tcp.close(); udp.close() }
|
||||||
|
Unit
|
||||||
|
}
|
||||||
|
}
|
||||||
Loaded 100 of 152 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user