Compare commits
54
Commits
v0.2.3
...
2829bcfecd
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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
+4
-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,5 @@ bin/
|
|||||||
# More
|
# More
|
||||||
.kotlin
|
.kotlin
|
||||||
/.idea/workspace.xml
|
/.idea/workspace.xml
|
||||||
|
/.gigaide/gigaide.properties
|
||||||
|
local.properties
|
||||||
@@ -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
+4
-1
@@ -1,7 +1,10 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<project version="4">
|
<project version="4">
|
||||||
<component name="ExternalStorageConfigurationManager" enabled="true" />
|
<component name="ExternalStorageConfigurationManager" enabled="true" />
|
||||||
<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>
|
||||||
@@ -1,35 +1,79 @@
|
|||||||
# 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
|
> 0.7.0-SNAPSHOT is recommended for newer builds; due to extremely poor Kotlin time migration architecture, on Apple targets it is the only working version.
|
||||||
|
|
||||||
|
|
||||||
|
__Recommended version is `0.6.8`: to keep the code compatible with current and further versions we
|
||||||
|
ask to upgrade to `0.4.2` at least.__ Starting from this version some package names are changed for
|
||||||
|
better clarity and fast UDP endpoints are added.
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
We recommend using `0.6.12`
|
||||||
|
|
||||||
## TCP/IP transport
|
Since version 0.6.9 websocket protocol supports both text and binary frames; old clients are backward compatible with
|
||||||
|
mew servers, but new clients only can work with older servers only in default binary frame mode. Upgrade also your
|
||||||
|
servers to get better websocket compatibility[^1].
|
||||||
|
|
||||||
It is the fastest. JVM implementation uses nio2 async sockets and optimizes TCP socket to play
|
Version 0.5.1 could be backward incompatible due to the upgrade of the crypto2.
|
||||||
well with blocks (smart NO_DELAY mode). It is multiplatform, nut lacks of async TCP/IP support
|
|
||||||
on natvic targetm this is where I need help having little time. I'd prefer to use something asyn like UV on native targets.
|
|
||||||
|
|
||||||
I know no existing way to implement it in KotlinJS for the modern browsers.
|
Protocols >= 0.3.0 are not binary compatible with the previous version due to a more compact binary
|
||||||
|
format. The format from 0.3.0 onwards is supposed to keep compatible.
|
||||||
|
|
||||||
## Websock server
|
#### ID calculation algorithm is changed since 0.4.1
|
||||||
|
|
||||||
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.
|
We recommend to upgrade to 0.4+ ASAP as public/shared key id derivation method was changed for even higher security.
|
||||||
|
|
||||||
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.
|
### Supported native targets
|
||||||
|
|
||||||
|
- iosArm64, iosX64
|
||||||
|
- macosArm64, macosArm64
|
||||||
|
- linuxArm64, linuxX64
|
||||||
|
|
||||||
|
### Non-native targets
|
||||||
|
|
||||||
|
- 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 +94,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:
|
||||||
@@ -64,22 +108,22 @@ and functions available, like:
|
|||||||
// Api.kt
|
// Api.kt
|
||||||
|
|
||||||
@Serializable
|
@Serializable
|
||||||
class FooArgs(val text: String,val number: Int = 42)
|
class FooArgs(val text: String, val number: Int = 42)
|
||||||
|
|
||||||
// Server-side interface
|
// Server-side interface
|
||||||
val cmdSetFoo by command<FooArgs,Unit>()
|
val cmdSetFoo by command<FooArgs, Unit>()
|
||||||
val cmdGetFoo by command<Unit,FooArgs>()
|
val cmdGetFoo by command<Unit, FooArgs>()
|
||||||
val cmdPing by command<String,String>()
|
val cmdPing by command<String, String>()
|
||||||
val cmdCheckConnected by command<Unit,Boolean>()
|
val cmdCheckConnected by command<Unit, Boolean>()
|
||||||
|
|
||||||
// client-side interface (called from the server)
|
// client-side interface (called from the server)
|
||||||
val cmdPushClient by command<String,Unit>()
|
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:
|
||||||
@@ -93,7 +137,7 @@ val client = websocketClient<Unit>("wss://your.host.com/kp") {
|
|||||||
// If we want to collect connected state changes (this is optional)
|
// If we want to collect connected state changes (this is optional)
|
||||||
launch {
|
launch {
|
||||||
client.connectedStateFlow.collect {
|
client.connectedStateFlow.collect {
|
||||||
if( it )
|
if (it)
|
||||||
println("I am connected")
|
println("I am connected")
|
||||||
else
|
else
|
||||||
println("trying to connect...")
|
println("trying to connect...")
|
||||||
@@ -106,14 +150,15 @@ 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:
|
||||||
data class Session(var fooState: FooArgs?=null)
|
data class Session(var fooState: FooArgs? = null)
|
||||||
|
|
||||||
// Let's now provide interface we export, it will be used on each connection automatically:
|
// Let's now provide interface we export, it will be used on each connection automatically:
|
||||||
|
|
||||||
@@ -134,38 +179,134 @@ 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.
|
||||||
Executable
+14
@@ -0,0 +1,14 @@
|
|||||||
|
#!/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
|
||||||
|
./gradlew dokkaHtml
|
||||||
|
rsync -avz ./build/dokka/* code.sergeych.net:/bigstore/sergeych_pub/code/docs/kiloparsec
|
||||||
+131
-62
@@ -1,82 +1,98 @@
|
|||||||
|
/*
|
||||||
|
* 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 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 "1.9.20"
|
||||||
}
|
}
|
||||||
|
|
||||||
group = "net.sergeych"
|
group = "net.sergeych"
|
||||||
version = "0.2.2-SNAPSHOT"
|
version = "0.7.0-SNAPSHOT"
|
||||||
|
|
||||||
repositories {
|
repositories {
|
||||||
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 {
|
|
||||||
// enabled.set(true)
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
// 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()
|
||||||
|
@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")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
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")
|
||||||
@@ -85,37 +101,90 @@ kotlin {
|
|||||||
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 nativeTest by getting
|
|
||||||
}
|
|
||||||
|
|
||||||
publishing {
|
|
||||||
val mavenToken by lazy {
|
|
||||||
File("${System.getProperty("user.home")}/.gitea_token").readText()
|
|
||||||
}
|
}
|
||||||
repositories {
|
val macosArm64Test by getting {
|
||||||
maven {
|
dependsOn(ktorSocketTest)
|
||||||
credentials(HttpHeaderCredentials::class) {
|
}
|
||||||
name = "Authorization"
|
val macosX64Main by getting {
|
||||||
value = mavenToken
|
dependsOn(ktorSocketMain)
|
||||||
}
|
}
|
||||||
url = uri("https://gitea.sergeych.net/api/packages/SergeychWorks/maven")
|
val iosX64Main by getting {
|
||||||
authentication {
|
dependsOn(ktorSocketMain)
|
||||||
create("Authorization", HttpHeaderAuthentication::class)
|
}
|
||||||
}
|
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 {
|
||||||
|
val mavenToken by lazy {
|
||||||
|
File("${System.getProperty("user.home")}/.gitea_token").readText()
|
||||||
|
}
|
||||||
|
repositories {
|
||||||
|
maven {
|
||||||
|
credentials(HttpHeaderCredentials::class) {
|
||||||
|
name = "Authorization"
|
||||||
|
value = mavenToken
|
||||||
|
}
|
||||||
|
url = uri("https://gitea.sergeych.net/api/packages/SergeychWorks/maven")
|
||||||
|
authentication {
|
||||||
|
create("Authorization", HttpHeaderAuthentication::class)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
tasks.dokkaHtml.configure {
|
||||||
|
outputDirectory.set(buildDir.resolve("dokka"))
|
||||||
|
dokkaSourceSets {
|
||||||
|
configureEach {
|
||||||
|
// includes.from("docs/bipack.md")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
android {
|
||||||
|
namespace = "net.sergeych.kiloparsec"
|
||||||
|
compileSdk = 34
|
||||||
|
defaultConfig {
|
||||||
|
minSdk = 24
|
||||||
|
}
|
||||||
|
compileOptions {
|
||||||
|
sourceCompatibility = JavaVersion.VERSION_17
|
||||||
|
targetCompatibility = JavaVersion.VERSION_17
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -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 }
|
||||||
|
}
|
||||||
@@ -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,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,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.CancellationException
|
import kotlinx.coroutines.CancellationException
|
||||||
@@ -9,6 +19,7 @@ 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
|
||||||
@@ -17,10 +28,33 @@ 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, 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>,
|
||||||
@@ -28,7 +62,6 @@ class KiloClient<S>(
|
|||||||
connectionDataFactory: ConnectionDataFactory<S>,
|
connectionDataFactory: ConnectionDataFactory<S>,
|
||||||
) : RemoteInterface,
|
) : RemoteInterface,
|
||||||
Loggable by LogTag("CLIF") {
|
Loggable by LogTag("CLIF") {
|
||||||
|
|
||||||
val _state = MutableStateFlow(false)
|
val _state = MutableStateFlow(false)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -38,6 +71,14 @@ 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 job =
|
private val job =
|
||||||
@@ -50,9 +91,11 @@ class KiloClient<S>(
|
|||||||
debug { "get device and session" }
|
debug { "get device and session" }
|
||||||
val client = KiloClientConnection(localInterface, kc, secretKey)
|
val client = KiloClientConnection(localInterface, kc, secretKey)
|
||||||
deferredClient.complete(client)
|
deferredClient.complete(client)
|
||||||
client.run {
|
debug { "starting client run"}
|
||||||
|
val r = runCatching { client.run {
|
||||||
_state.value = it
|
_state.value = it
|
||||||
}
|
} }
|
||||||
|
debug { "----------- client run finished: $r" }
|
||||||
resetDeferredClient()
|
resetDeferredClient()
|
||||||
debug { "client run finished" }
|
debug { "client run finished" }
|
||||||
} catch (_: RemoteInterface.ClosedException) {
|
} catch (_: RemoteInterface.ClosedException) {
|
||||||
@@ -67,7 +110,8 @@ class KiloClient<S>(
|
|||||||
}
|
}
|
||||||
_state.value = false
|
_state.value = false
|
||||||
resetDeferredClient()
|
resetDeferredClient()
|
||||||
delay(100)
|
// reconnection timeout
|
||||||
|
delay(700)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -94,6 +138,15 @@ 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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 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 +162,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>() {
|
||||||
@@ -124,8 +177,19 @@ class KiloClient<S>(
|
|||||||
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
|
||||||
|
|||||||
@@ -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.*
|
||||||
@@ -39,7 +49,6 @@ class KiloClientConnection<S>(
|
|||||||
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" }
|
||||||
|
|
||||||
|
|
||||||
@@ -52,10 +61,11 @@ class KiloClientConnection<S>(
|
|||||||
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(1u, pair.publicKey))
|
||||||
|
|
||||||
|
debug { "got server HE (2)" }
|
||||||
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)
|
||||||
|
|
||||||
@@ -80,15 +90,14 @@ class KiloClientConnection<S>(
|
|||||||
kiloRemoteInterface.complete(
|
kiloRemoteInterface.complete(
|
||||||
KiloRemoteInterface(deferredParams, clientInterface)
|
KiloRemoteInterface(deferredParams, clientInterface)
|
||||||
)
|
)
|
||||||
clientInterface.onConnectHandler?.invoke(params.scope)
|
clientInterface.onConnectHandlers.invokeAll(params.scope)
|
||||||
onConnectedStateChanged?.invoke(true)
|
onConnectedStateChanged?.invoke(true)
|
||||||
job.join()
|
job.join()
|
||||||
|
|
||||||
} 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 {
|
||||||
onConnectedStateChanged?.invoke(false)
|
onConnectedStateChanged?.invoke(false)
|
||||||
job?.cancel()
|
job?.cancel()
|
||||||
@@ -100,4 +109,11 @@ class KiloClientConnection<S>(
|
|||||||
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 { runCatching { scope.it() } }
|
||||||
@@ -1,22 +1,46 @@
|
|||||||
|
/*
|
||||||
|
* 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] handler
|
||||||
|
*
|
||||||
|
* 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>>()
|
||||||
|
|
||||||
fun onConnected(f: KiloScope<S>.()->Unit) { onConnectHandler = f }
|
/**
|
||||||
|
* Registers handler [f] for [onConnected] event, to the head or the end of 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
|
||||||
|
}
|
||||||
|
|
||||||
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() }
|
||||||
|
|||||||
@@ -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.CompletableDeferred
|
import kotlinx.coroutines.CompletableDeferred
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -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.CompletableDeferred
|
import kotlinx.coroutines.CompletableDeferred
|
||||||
@@ -35,5 +45,10 @@ class KiloRemoteInterface<S>(
|
|||||||
else -> throw RemoteInterface.Exception("unexpected block type: $block")
|
else -> throw RemoteInterface.Exception("unexpected block type: $block")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
override suspend fun <A> push(cmd: Command<A, Unit>, args: A) {
|
||||||
|
val params = deferredParams.await()
|
||||||
|
params.transport.call(L0Call, params.encrypt(cmd.packCall(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.crypto2.SigningKey
|
import net.sergeych.crypto2.SigningKey
|
||||||
|
|||||||
@@ -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.CancellationException
|
import kotlinx.coroutines.CancellationException
|
||||||
@@ -13,13 +23,100 @@ 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<InetTransportDevice>,
|
||||||
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()}") {
|
||||||
|
|
||||||
private val job = globalLaunch {
|
private val job = globalLaunch {
|
||||||
connections.collect { device ->
|
connections.collect { device ->
|
||||||
@@ -27,22 +124,30 @@ class KiloServer<S>(
|
|||||||
try {
|
try {
|
||||||
info { "connected ${device}" }
|
info { "connected ${device}" }
|
||||||
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,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.CompletableDeferred
|
import kotlinx.coroutines.CompletableDeferred
|
||||||
@@ -75,7 +85,7 @@ class KiloServerConnection<S>(
|
|||||||
kiloRemoteInterface.complete(
|
kiloRemoteInterface.complete(
|
||||||
KiloRemoteInterface(deferredParams, clientInterface)
|
KiloRemoteInterface(deferredParams, clientInterface)
|
||||||
)
|
)
|
||||||
clientInterface.onConnectHandler?.invoke(p.scope)
|
clientInterface.onConnectHandlers.invokeAll(p.scope)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -94,4 +104,8 @@ class KiloServerConnection<S>(
|
|||||||
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
|
||||||
@@ -67,14 +77,18 @@ open class LocalInterface<S> : Loggable by LogTag("LocalInterface${idCounter.inc
|
|||||||
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 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 +96,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 +116,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)
|
||||||
}
|
}
|
||||||
@@ -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.bipack.Unsigned
|
||||||
import net.sergeych.crypto2.toDump
|
import net.sergeych.crypto2.toDump
|
||||||
import net.sergeych.kiloparsec.Transport.Device
|
|
||||||
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)
|
||||||
*/
|
*/
|
||||||
@@ -63,7 +73,12 @@ class Transport<S>(
|
|||||||
@Serializable(TransportBlockSerializer::class)
|
@Serializable(TransportBlockSerializer::class)
|
||||||
sealed class Block {
|
sealed class Block {
|
||||||
@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,10 +98,10 @@ 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" }
|
||||||
}
|
}
|
||||||
@@ -98,7 +113,8 @@ class Transport<S>(
|
|||||||
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
|
||||||
*/
|
*/
|
||||||
@@ -111,12 +127,19 @@ class Transport<S>(
|
|||||||
// 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()
|
||||||
|
// the order is important: first id in use MUST BE >= 1, not zero:
|
||||||
b = Block.Call(++lastId, name, packedArgs)
|
b = Block.Call(++lastId, name, packedArgs)
|
||||||
calls[b.id] = deferred
|
calls[b.id] = deferred
|
||||||
}
|
}
|
||||||
|
|
||||||
// now we have mutex freed so we can call:
|
// now we have mutex freed so we can call:
|
||||||
val r = runCatching { device.output.send(pack(b).also { debug { ">>>\n${it.toDump()}" } }) }
|
val r = runCatching {
|
||||||
|
do {
|
||||||
|
val cr = device.output.trySend(pack(b))
|
||||||
|
if( cr.isClosed ) throw ClosedSendChannelException("can't send block: channel is closed")
|
||||||
|
delay(100)
|
||||||
|
} while(!cr.isSuccess)
|
||||||
|
}
|
||||||
if (!r.isSuccess) {
|
if (!r.isSuccess) {
|
||||||
r.exceptionOrNull()?.let {
|
r.exceptionOrNull()?.let {
|
||||||
exception { "failed to send output block" to it }
|
exception { "failed to send output block" to it }
|
||||||
@@ -131,6 +154,25 @@ class Transport<S>(
|
|||||||
return deferred.await()
|
return deferred.await()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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)
|
||||||
|
val r = runCatching { device.output.send(pack(b).also { debug { ">>$\n${it.toDump()}" } }) }
|
||||||
|
when(val e = r.exceptionOrNull()) {
|
||||||
|
is RemoteInterface.ClosedException, is CancellationException, is RemoteInterface.RemoteException
|
||||||
|
-> throw e
|
||||||
|
else -> throw RemoteInterface.ClosedException()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Call the remote procedure with specified args and return its result
|
* Call the remote procedure with specified args and return its result
|
||||||
*/
|
*/
|
||||||
@@ -139,6 +181,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
|
||||||
@@ -153,69 +199,62 @@ class Transport<S>(
|
|||||||
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 = 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))
|
calls.remove(b.forId)?.completeExceptionally(localInterface.decodeError(b))
|
||||||
?: 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 {
|
calls.remove(b.forId)?.complete(b.packedResult)
|
||||||
debug { "activating wait handle for ${b.forId}" }
|
|
||||||
it.complete(b.packedResult)
|
|
||||||
}
|
|
||||||
?: warning { "wait handle not found for ${b.forId}" }
|
?: warning { "wait handle not found for ${b.forId}" }
|
||||||
}
|
}
|
||||||
|
|
||||||
is Block.Call -> launch {
|
is Block.Call -> launch {
|
||||||
try {
|
try {
|
||||||
send(
|
if (b.id == 0u)
|
||||||
Block.Response(
|
// Command does not waits return
|
||||||
b.id,
|
localInterface.execute(commandContext, b.name, b.packedArgs)
|
||||||
localInterface.execute(commandContext, b.name, b.packedArgs)
|
else
|
||||||
|
send(
|
||||||
|
Block.Response(
|
||||||
|
b.id,
|
||||||
|
localInterface.execute(commandContext, b.name, b.packedArgs)
|
||||||
|
)
|
||||||
)
|
)
|
||||||
)
|
|
||||||
} 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) device.flush()
|
||||||
device.close()
|
device.close()
|
||||||
} 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))
|
||||||
} catch (t: Throwable) {
|
} catch (t: Throwable) {
|
||||||
send(Block.Error(b.id, "UnknownError", t.message))
|
send(Block.Error(b.id, "UnknownError", t.message))
|
||||||
}
|
}
|
||||||
.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) {
|
||||||
@@ -226,7 +265,7 @@ class Transport<S>(
|
|||||||
}
|
}
|
||||||
debug { "leaving transport loop" }
|
debug { "leaving transport loop" }
|
||||||
access.withLock {
|
access.withLock {
|
||||||
debug { "access lock obtained"}
|
debug { "access lock obtained" }
|
||||||
isClosed = true
|
isClosed = true
|
||||||
debug { "closing device $device, calls in queue ${calls.size}" }
|
debug { "closing device $device, calls in queue ${calls.size}" }
|
||||||
runCatching { device.close() }
|
runCatching { device.close() }
|
||||||
@@ -237,14 +276,13 @@ class Transport<S>(
|
|||||||
}
|
}
|
||||||
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))
|
device.output.send(pack(block))
|
||||||
}
|
} catch (_: ClosedSendChannelException) {
|
||||||
catch(_: ClosedSendChannelException) {
|
|
||||||
throw RemoteInterface.ClosedException()
|
throw RemoteInterface.ClosedException()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -275,7 +313,7 @@ object TransportBlockSerializer : KSerializer<Transport.Block> {
|
|||||||
|
|
||||||
|
|
||||||
override fun deserialize(decoder: Decoder): Transport.Block =
|
override fun deserialize(decoder: Decoder): Transport.Block =
|
||||||
when( val id = decoder.decodeByte().toInt()) {
|
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>())
|
||||||
|
|||||||
@@ -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())
|
|
||||||
@@ -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,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.client.*
|
import io.ktor.client.*
|
||||||
@@ -10,42 +20,62 @@ 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)
|
||||||
|
* @client use default [HttpClient], it installs [WebSockets] plugin
|
||||||
|
*/
|
||||||
|
fun websocketTransportDevice(
|
||||||
|
path: String,
|
||||||
|
useTextFrames: Boolean = false,
|
||||||
|
client: HttpClient = HttpClient {
|
||||||
|
install(WebSockets)
|
||||||
|
},
|
||||||
|
): Transport.Device {
|
||||||
var u = Url(path)
|
var u = Url(path)
|
||||||
if (u.encodedPath.length <= 1)
|
if (u.encodedPath.length <= 1)
|
||||||
u = URLBuilder(u).apply {
|
u = URLBuilder(u).apply {
|
||||||
encodedPath = "/kp"
|
encodedPath = "/kp"
|
||||||
}.build()
|
}.build()
|
||||||
|
|
||||||
return KiloClient(clientInterface, secretKey) {
|
val input = Channel<UByteArray>()
|
||||||
val input = Channel<UByteArray>()
|
val output = Channel<UByteArray>()
|
||||||
val output = Channel<UByteArray>()
|
val closeHandle = CompletableDeferred<Boolean>()
|
||||||
val closeHandle = CompletableDeferred<Boolean>()
|
val readyHandle = CompletableDeferred<Unit>()
|
||||||
globalLaunch {
|
|
||||||
val log = LogTag("KC:${counter.incrementAndGet()}")
|
globalLaunch {
|
||||||
|
val log = LogTag("KC:${counter.incrementAndGet()}")
|
||||||
|
try {
|
||||||
client.webSocket({
|
client.webSocket({
|
||||||
url.protocol = u.protocol
|
url.protocol = u.protocol
|
||||||
url.host = u.host
|
url.host = u.host
|
||||||
@@ -57,18 +87,23 @@ fun <S> websocketClient(
|
|||||||
log.info { "connected to the server" }
|
log.info { "connected to the server" }
|
||||||
// println("SENDING!!!")
|
// println("SENDING!!!")
|
||||||
// send("Helluva")
|
// send("Helluva")
|
||||||
|
readyHandle.complete(Unit)
|
||||||
launch {
|
launch {
|
||||||
try {
|
try {
|
||||||
for (block in output) {
|
for (block in output) {
|
||||||
send(block.toByteArray())
|
if (useTextFrames)
|
||||||
|
send(
|
||||||
|
Frame.Text(block.asByteArray().encodeToBase64Compact())
|
||||||
|
)
|
||||||
|
else
|
||||||
|
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)
|
||||||
}
|
}
|
||||||
@@ -77,10 +112,10 @@ fun <S> websocketClient(
|
|||||||
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)
|
||||||
@@ -94,21 +129,31 @@ fun <S> websocketClient(
|
|||||||
if (closeHandle.isActive) closeHandle.complete(false)
|
if (closeHandle.isActive) closeHandle.complete(false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if(!closeHandle.await()) {
|
if (!closeHandle.await()) {
|
||||||
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() }
|
||||||
}
|
}
|
||||||
log.info { "closing connection" }
|
} 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() }
|
||||||
}
|
}
|
||||||
val device = ProxyDevice(input, output) {
|
log.info { "closing connection" }
|
||||||
// we need to explicitly close the coroutine job, or it can hang for a long time
|
|
||||||
// leaking resources.
|
|
||||||
closeHandle.complete(true)
|
|
||||||
// job.cancel()
|
|
||||||
}
|
|
||||||
KiloConnectionData(device, sessionMaker())
|
|
||||||
}
|
}
|
||||||
|
// 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
|
||||||
|
// leaking resources.
|
||||||
|
runCatching { output.close() }
|
||||||
|
runCatching { input.close() }
|
||||||
|
closeHandle.complete(true)
|
||||||
|
// job.cancel()
|
||||||
|
})
|
||||||
|
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
|
||||||
|
|||||||
@@ -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
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
|||||||
@@ -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)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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() {
|
||||||
|
|||||||
@@ -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"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -184,10 +195,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 +266,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 {
|
||||||
|
|||||||
@@ -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,25 +20,44 @@ 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,
|
||||||
) {
|
) {
|
||||||
|
|
||||||
install(Routing)
|
|
||||||
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
|
||||||
}
|
}
|
||||||
@@ -39,13 +68,18 @@ fun <S> Application.setupWebsocketServer(
|
|||||||
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>(256)
|
||||||
|
var useBinary: Boolean? = null
|
||||||
launch {
|
launch {
|
||||||
log.debug { "starting output pump" }
|
log.debug { "starting output pump" }
|
||||||
while (isActive) {
|
while (isActive) {
|
||||||
try {
|
try {
|
||||||
send(output.receive().toByteArray())
|
val block = output.receive()
|
||||||
}
|
if (useBinary == false)
|
||||||
catch(_: ClosedReceiveChannelException) {
|
send(block.asByteArray().encodeToBase64Compact())
|
||||||
|
else
|
||||||
|
send(block.toByteArray())
|
||||||
|
|
||||||
|
} catch (_: ClosedReceiveChannelException) {
|
||||||
log.debug { "closing output pump as output channel is closed" }
|
log.debug { "closing output pump as output channel is closed" }
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
@@ -64,24 +98,38 @@ 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}" }
|
try {
|
||||||
if (f is Frame.Binary)
|
when (f) {
|
||||||
try {
|
is Frame.Binary -> {
|
||||||
input.send(f.readBytes().toUByteArray().also {
|
if (useBinary == null) {
|
||||||
log.debug { "in frame\n${it.toDump()}" }
|
log.debug { "Setting binary frame mode ------------------------------------" }
|
||||||
})
|
useBinary = true
|
||||||
} catch (_: RemoteInterface.ClosedException) {
|
}
|
||||||
log.warning { "caught local closed exception (strange!), closing" }
|
input.send(f.readBytes().toUByteArray())
|
||||||
break
|
}
|
||||||
} catch (_: ClosedReceiveChannelException) {
|
|
||||||
log.info { "receive channel is closed, closing connection" }
|
is Frame.Text -> {
|
||||||
break
|
if (useBinary == null) {
|
||||||
} catch (t: Throwable) {
|
log.debug { "Setting text frame mode -----------------------------------" }
|
||||||
log.exception { "unexpected exception, server connection will close" to t }
|
useBinary = false
|
||||||
break
|
}
|
||||||
|
input.send(f.readText().decodeBase64Compact().asUByteArray())
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> {
|
||||||
|
log.warning { "unexpected frame type ${f.frameType}, ignoring" }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
else
|
} catch (_: RemoteInterface.ClosedException) {
|
||||||
log.warning { "unknown frame type ${f.frameType}, ignoring" }
|
log.warning { "caught local closed exception (strange!), closing" }
|
||||||
|
break
|
||||||
|
} catch (_: ClosedReceiveChannelException) {
|
||||||
|
log.info { "receive channel is closed, closing connection" }
|
||||||
|
break
|
||||||
|
} catch (t: Throwable) {
|
||||||
|
log.exception { "unexpected exception, server connection will close" to t }
|
||||||
|
break
|
||||||
|
}
|
||||||
}
|
}
|
||||||
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,72 +39,21 @@ 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>()
|
||||||
val cmdGetFoo by command<Unit,String>()
|
val cmdGetFoo by command<Unit, String>()
|
||||||
val cmdSetFoo by command<String,Unit>()
|
val cmdSetFoo by command<String, Unit>()
|
||||||
val cmdCheckConnected by command<Unit,Boolean>()
|
val cmdCheckConnected by command<Unit, Boolean>()
|
||||||
|
|
||||||
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,10 +94,13 @@ 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
|
||||||
client.call(cmdSetFoo,"superbar")
|
client.call(cmdSetFoo, "superbar")
|
||||||
assertTrue { client.connectedStateFlow.value }
|
assertTrue { client.connectedStateFlow.value }
|
||||||
assertEquals("superbar", client.call(cmdGetFoo))
|
assertEquals("superbar", client.call(cmdGetFoo))
|
||||||
client.close()
|
client.close()
|
||||||
@@ -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 }
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -1,87 +0,0 @@
|
|||||||
package net.sergeych.kiloparsec.adapters
|
|
||||||
|
|
||||||
import kotlinx.coroutines.*
|
|
||||||
import kotlinx.coroutines.test.runTest
|
|
||||||
import net.sergeych.crypto2.initCrypto
|
|
||||||
import net.sergeych.kiloparsec.adapter.UdpServer
|
|
||||||
import net.sergeych.kiloparsec.adapter.acceptTcpDevice
|
|
||||||
import net.sergeych.kiloparsec.adapter.connectTcpDevice
|
|
||||||
import net.sergeych.kiloparsec.adapter.toNetworkAddress
|
|
||||||
import net.sergeych.kiloparsec.decodeFromUByteArray
|
|
||||||
import net.sergeych.kiloparsec.encodeToUByteArray
|
|
||||||
import net.sergeych.mp_logger.Log
|
|
||||||
import net.sergeych.synctools.ProtectedOp
|
|
||||||
import net.sergeych.synctools.invoke
|
|
||||||
import kotlin.test.Test
|
|
||||||
import kotlin.test.assertContains
|
|
||||||
import kotlin.test.assertEquals
|
|
||||||
|
|
||||||
class NetworkTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun udpProviderTest() = runTest {
|
|
||||||
Log.connectConsole(Log.Level.DEBUG)
|
|
||||||
val s1 = UdpServer(17120)
|
|
||||||
val s2 = UdpServer(17121)
|
|
||||||
s1.send("Hello".encodeToUByteArray(), "localhost", 17121)
|
|
||||||
val d1 = s2.incoming.receive()
|
|
||||||
assertEquals(d1.address.port, 17120)
|
|
||||||
assertEquals("Hello", d1.message.toByteArray().decodeToString())
|
|
||||||
s1.send("world".encodeToUByteArray(), d1.address)
|
|
||||||
assertEquals("world", s1.incoming.receive().message.toByteArray().decodeToString())
|
|
||||||
// println("s1: ${s1.bindAddress()}")
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun tcpAsyncConnectionTest() = runTest {
|
|
||||||
initCrypto()
|
|
||||||
Log.connectConsole(Log.Level.DEBUG)
|
|
||||||
|
|
||||||
coroutineScope {
|
|
||||||
val serverFlow = acceptTcpDevice(17171)
|
|
||||||
val op = ProtectedOp()
|
|
||||||
var pills = setOf<String>()
|
|
||||||
val j = launch {
|
|
||||||
serverFlow.collect { device ->
|
|
||||||
launch {
|
|
||||||
device.output.send("Hello, world!".encodeToUByteArray())
|
|
||||||
device.output.send("Great".encodeToUByteArray())
|
|
||||||
while (true) {
|
|
||||||
val x = device.input.receive().decodeFromUByteArray()
|
|
||||||
if (x.startsWith("die")) {
|
|
||||||
op.invoke {
|
|
||||||
pills += x
|
|
||||||
}
|
|
||||||
cancel()
|
|
||||||
}
|
|
||||||
else
|
|
||||||
println("ignoring unexpected input: $x")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
yield()
|
|
||||||
run {
|
|
||||||
val s = connectTcpDevice("127.0.1.1:17171".toNetworkAddress())
|
|
||||||
assertEquals("Hello, world!", s.input.receive().decodeFromUByteArray())
|
|
||||||
assertEquals("Great", s.input.receive().decodeFromUByteArray())
|
|
||||||
s.output.send("Goodbye".encodeToUByteArray())
|
|
||||||
s.output.send("die1".encodeToUByteArray())
|
|
||||||
s.close()
|
|
||||||
}
|
|
||||||
val s1 = connectTcpDevice("127.0.1.1:17171".toNetworkAddress())
|
|
||||||
assertEquals("Hello, world!", s1.input.receive().decodeFromUByteArray())
|
|
||||||
assertEquals("Great", s1.input.receive().decodeFromUByteArray())
|
|
||||||
s1.output.send("die2".encodeToUByteArray())
|
|
||||||
s1.close()
|
|
||||||
|
|
||||||
// check that channels were flushed prior to closed:
|
|
||||||
assertContains(pills, "die1")
|
|
||||||
assertContains(pills, "die2")
|
|
||||||
|
|
||||||
// Check that server jobs are closed
|
|
||||||
j.cancelAndJoin()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,224 @@
|
|||||||
|
/*
|
||||||
|
* 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
|
||||||
|
|
||||||
|
import io.ktor.network.selector.*
|
||||||
|
import io.ktor.network.sockets.*
|
||||||
|
import io.ktor.utils.io.*
|
||||||
|
import io.ktor.utils.io.writeByte
|
||||||
|
import kotlinx.coroutines.*
|
||||||
|
import kotlinx.coroutines.CancellationException
|
||||||
|
import kotlinx.coroutines.channels.Channel
|
||||||
|
import kotlinx.coroutines.channels.ClosedReceiveChannelException
|
||||||
|
import kotlinx.coroutines.flow.Flow
|
||||||
|
import kotlinx.coroutines.flow.flow
|
||||||
|
import kotlinx.coroutines.sync.Mutex
|
||||||
|
import kotlinx.coroutines.sync.withLock
|
||||||
|
import net.sergeych.kiloparsec.*
|
||||||
|
import net.sergeych.mp_logger.*
|
||||||
|
import net.sergeych.mp_tools.globalLaunch
|
||||||
|
import net.sergeych.tools.AtomicCounter
|
||||||
|
import kotlin.time.Clock
|
||||||
|
import kotlin.time.Duration.Companion.seconds
|
||||||
|
|
||||||
|
private val logCounter = AtomicCounter(0)
|
||||||
|
|
||||||
|
class ProtocolException(text: String, cause: Throwable? = null) : RuntimeException(text, cause)
|
||||||
|
|
||||||
|
const val MAX_TCP_BLOCK_SIZE = 16776216
|
||||||
|
internal val PING_INACTIVITY_TIME = 30.seconds
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Listen for incoming TCP/IP connections on all local interfaces and the specified [port]
|
||||||
|
* anc create flow of [InetTransportDevice] suitable for [KiloClient].
|
||||||
|
*/
|
||||||
|
fun acceptTcpDevice(port: Int, localInterface: String = "0.0.0.0"): Flow<InetTransportDevice> {
|
||||||
|
val selectorManager = SelectorManager(Dispatchers.IO)
|
||||||
|
return flow {
|
||||||
|
val serverSocket = aSocket(selectorManager).tcp().bind(localInterface, port)
|
||||||
|
while (true) {
|
||||||
|
serverSocket.accept().let { sock ->
|
||||||
|
emit(inetTransportDevice(sock, "srv"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Connect to the TCP/IP server (see [KiloServer]) at the specified address and provide th compatible
|
||||||
|
* [InetTransportDevice] to use with [KiloClient]. [hostPortAddress] is a string in the form of `host:port`.
|
||||||
|
*/
|
||||||
|
suspend fun connectTcpDevice(hostPortAddress: String): InetTransportDevice =
|
||||||
|
connectTcpDevice(hostPortAddress.toNetworkAddress())
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Connect to the TCP/IP server (see [KiloServer]) at the specified address and provide th compatible
|
||||||
|
* [InetTransportDevice] to use with [KiloClient].
|
||||||
|
*/
|
||||||
|
suspend fun connectTcpDevice(address: NetworkAddress): InetTransportDevice {
|
||||||
|
val selectorManager = SelectorManager(Dispatchers.IO)
|
||||||
|
val socket = aSocket(selectorManager).tcp().connect(address.host, address.port)
|
||||||
|
return inetTransportDevice(socket)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse `host:port` string into the [NetworkAddress]
|
||||||
|
*/
|
||||||
|
fun String.toNetworkAddress(): NetworkAddress {
|
||||||
|
val (host, port) = this.split(":").map { it.trim() }
|
||||||
|
return NetworkAddress(host, port.toInt())
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun inetTransportDevice(
|
||||||
|
sock: Socket,
|
||||||
|
suffix: String = "cli",
|
||||||
|
): InetTransportDevice {
|
||||||
|
val networkAddress = (sock.remoteAddress as InetSocketAddress).let { NetworkAddress(it.hostname, it.port) }
|
||||||
|
val inputBlocks = Channel<UByteArray>(4096)
|
||||||
|
val outputBlocks = Channel<UByteArray>(4096)
|
||||||
|
|
||||||
|
val log = LogTag("TCPT${logCounter.incrementAndGet()}:$suffix:$networkAddress")
|
||||||
|
val job = AtomicAsyncValue<Job?>(null)
|
||||||
|
|
||||||
|
val sockOutput = sock.openWriteChannel()
|
||||||
|
val sockInput = runCatching { sock.openReadChannel() }.getOrElse {
|
||||||
|
log.warning { "failed to open read channel $it" }
|
||||||
|
throw IllegalStateException("failed to open read channel")
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun stop() {
|
||||||
|
job.mutate {
|
||||||
|
if (it != null) {
|
||||||
|
log.debug { "stopping" }
|
||||||
|
runCatching { inputBlocks.close() }
|
||||||
|
runCatching { outputBlocks.close() }
|
||||||
|
// The problem: on mac platofrms closing the socket does not close its input
|
||||||
|
// and output channels!
|
||||||
|
runCatching { sockInput.cancel() }
|
||||||
|
runCatching { sockOutput.flushAndClose() }
|
||||||
|
if (!sock.isClosed)
|
||||||
|
runCatching {
|
||||||
|
log.debug { "closing socket by stop" }
|
||||||
|
sock.close()
|
||||||
|
}
|
||||||
|
else
|
||||||
|
log.debug { "socket is already closed when stop is called" }
|
||||||
|
it.cancel()
|
||||||
|
log.debug { "implementation job cancel called" }
|
||||||
|
} else
|
||||||
|
log.debug { "already stopped" }
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var lastActiveAt = Clock.System.now()
|
||||||
|
globalLaunch {
|
||||||
|
job.reset(globalLaunch {
|
||||||
|
launch {
|
||||||
|
|
||||||
|
log.debug { "opening read channel" }
|
||||||
|
|
||||||
|
while (isActive && sock.isActive) {
|
||||||
|
try {
|
||||||
|
val size = AsyncVarint.decodeUnsigned(sockInput).toInt()
|
||||||
|
if (size > MAX_TCP_BLOCK_SIZE) // 16M is a max command block
|
||||||
|
throw ProtocolException("Illegal block size: $size should be < $MAX_TCP_BLOCK_SIZE")
|
||||||
|
val data = ByteArray(size)
|
||||||
|
if (size == 0) {
|
||||||
|
log.debug { "ping received" }
|
||||||
|
lastActiveAt = Clock.System.now()
|
||||||
|
} else {
|
||||||
|
sockInput.readFully(data, 0, size)
|
||||||
|
inputBlocks.send(data.toUByteArray())
|
||||||
|
}
|
||||||
|
} catch (_: ClosedReceiveChannelException) {
|
||||||
|
log.error { "closed receive channel " }
|
||||||
|
stop()
|
||||||
|
break
|
||||||
|
} catch (_: CancellationException) {
|
||||||
|
log.error { "cancellation exception " }
|
||||||
|
break
|
||||||
|
} catch (e: Exception) {
|
||||||
|
log.exception { "unexpected exception in TCP socket read" to e }
|
||||||
|
stop()
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
launch {
|
||||||
|
val outAccess = Mutex()
|
||||||
|
var lastSentAt = Clock.System.now()
|
||||||
|
launch {
|
||||||
|
while (isActive && sock.isActive) {
|
||||||
|
delay(500)
|
||||||
|
val activityTime = if (lastSentAt > lastActiveAt) lastSentAt else lastActiveAt
|
||||||
|
if (Clock.System.now() - activityTime > PING_INACTIVITY_TIME) {
|
||||||
|
log.debug { "pinging for inactivity" }
|
||||||
|
val repeat = outAccess.withLock {
|
||||||
|
try {
|
||||||
|
sockOutput.writeByte(0)
|
||||||
|
sockOutput.flush()
|
||||||
|
lastSentAt = Clock.System.now()
|
||||||
|
true
|
||||||
|
} catch (e: ClosedReceiveChannelException) {
|
||||||
|
e.printStackTrace()
|
||||||
|
stop()
|
||||||
|
false
|
||||||
|
} catch (_: CancellationException) {
|
||||||
|
false
|
||||||
|
} catch (e: Throwable) {
|
||||||
|
e.printStackTrace()
|
||||||
|
stop()
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!repeat) break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
while (isActive && sock.isActive) {
|
||||||
|
try {
|
||||||
|
val block = outputBlocks.receive()
|
||||||
|
outAccess.withLock {
|
||||||
|
AsyncVarint.encodeUnsigned(block.size.toULong(), sockOutput)
|
||||||
|
sockOutput.writeFully(block.toByteArray(), 0, block.size)
|
||||||
|
sockOutput.flush()
|
||||||
|
lastSentAt = Clock.System.now()
|
||||||
|
}
|
||||||
|
} catch (_: CancellationException) {
|
||||||
|
log.debug { "cancellation exception on output" }
|
||||||
|
stop()
|
||||||
|
break
|
||||||
|
} catch (_: LocalInterface.BreakConnectionException) {
|
||||||
|
log.debug { "requested connection break" }
|
||||||
|
stop()
|
||||||
|
break
|
||||||
|
} catch (_: ClosedReceiveChannelException) {
|
||||||
|
log.debug { "receive block channel closed, closing the socket" }
|
||||||
|
stop()
|
||||||
|
break
|
||||||
|
} catch (e: Exception) {
|
||||||
|
log.exception { "unexpected exception. closing." to e }
|
||||||
|
stop()
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val device = InetTransportDevice(inputBlocks, outputBlocks, networkAddress, {
|
||||||
|
stop()
|
||||||
|
})
|
||||||
|
log.debug { "Transport ready" }
|
||||||
|
return device
|
||||||
|
}
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
/*
|
||||||
|
* 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
|
||||||
|
|
||||||
|
import io.ktor.network.sockets.*
|
||||||
|
import io.ktor.utils.io.core.*
|
||||||
|
import kotlinx.io.readByteArray
|
||||||
|
import net.sergeych.crypto2.toDump
|
||||||
|
import net.sergeych.kiloparsec.adapter.UdpBlock.Companion.CANCEL_BLOCK
|
||||||
|
import net.sergeych.kiloparsec.adapter.UdpBlock.Companion.ESCAPE_BYTE
|
||||||
|
import net.sergeych.kiloparsec.adapter.UdpBlock.Companion.PING_BLOCK
|
||||||
|
import net.sergeych.kiloparsec.adapter.UdpBlock.Companion.decode
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Encoded block for UDP datagram space-savvy. Minimum dara size is two bytes, which is fine
|
||||||
|
* for Kiloparsec blocks.
|
||||||
|
*
|
||||||
|
* First byte is encoded using [ESCAPE_BYTE] depending on the second byte:
|
||||||
|
*
|
||||||
|
* | 0 | 1 | meaning |
|
||||||
|
* |---|---|---------|
|
||||||
|
* | [ESCAPE_BYTE] | [ESCAPE_BYTE] | Data block, dropping first byte |
|
||||||
|
* | [ESCAPE_BYTE] | [PING_BLOCK] | Ping block, reset timers |
|
||||||
|
* | [ESCAPE_BYTE] | [CANCEL_BLOCK] | close connection |
|
||||||
|
* | any other | * | data block, all bytes |
|
||||||
|
*
|
||||||
|
* Use [encoded] and [toDatagram] to create binary or the datagram from a block, and [decode] to restore.
|
||||||
|
*
|
||||||
|
* We do not use serialization to speed up the transport layer.
|
||||||
|
*/
|
||||||
|
sealed class UdpBlock {
|
||||||
|
/**
|
||||||
|
* Block to show that the connection is closed and should also be closed on the other side
|
||||||
|
*/
|
||||||
|
object Cancel : UdpBlock()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parties show pings if there is no activity to keep it alive, detect connection loss and in some
|
||||||
|
* cases revive NAT/Proxy state in routers.
|
||||||
|
*/
|
||||||
|
object Ping : UdpBlock()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parsec data block. Could not be smaller than two bytes.
|
||||||
|
*/
|
||||||
|
class Data(val data: UByteArray) : UdpBlock() {
|
||||||
|
override fun toString(): String {
|
||||||
|
return "UDP Data (${data.size}):\n${data.toDump()}"
|
||||||
|
}
|
||||||
|
init {
|
||||||
|
if( data.size < 2) throw IllegalArgumentException("data must be at least 2 bytes")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val encoded: UByteArray by lazy {
|
||||||
|
when(this) {
|
||||||
|
is Data -> {
|
||||||
|
// Do we need escaping?
|
||||||
|
if( data[0] == ESCAPE_BYTE )
|
||||||
|
escapeAsArray + data
|
||||||
|
else
|
||||||
|
data
|
||||||
|
}
|
||||||
|
is Cancel -> cancelAsArray
|
||||||
|
is Ping -> pingAsArray
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun toDatagram(address: SocketAddress): Datagram {
|
||||||
|
val encoded = encoded.toByteArray()
|
||||||
|
return Datagram(ByteReadPacket(encoded, 0, encoded.size), address)
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
val ESCAPE_BYTE = 255.toUByte()
|
||||||
|
val PING_BLOCK = 0.toUByte()
|
||||||
|
val CANCEL_BLOCK = 1.toUByte()
|
||||||
|
|
||||||
|
private val escapeAsArray = ubyteArrayOf(ESCAPE_BYTE)
|
||||||
|
private val pingAsArray = ubyteArrayOf(ESCAPE_BYTE, PING_BLOCK)
|
||||||
|
private val cancelAsArray = ubyteArrayOf(ESCAPE_BYTE, CANCEL_BLOCK)
|
||||||
|
|
||||||
|
fun decode(data: UByteArray): UdpBlock {
|
||||||
|
if (data.size < 2)
|
||||||
|
throw UdpTransportException("block too short: ${data.size}")
|
||||||
|
return if( data[0] != ESCAPE_BYTE )
|
||||||
|
// plain data
|
||||||
|
Data(data)
|
||||||
|
else {
|
||||||
|
when(val b2 = data[1]) {
|
||||||
|
ESCAPE_BYTE -> {
|
||||||
|
// Escaped first byte, then plain data
|
||||||
|
Data(data.sliceArray(1 ..< data.size))
|
||||||
|
}
|
||||||
|
PING_BLOCK -> Ping
|
||||||
|
CANCEL_BLOCK -> Cancel
|
||||||
|
else -> throw UdpTransportException("invalid block type: $b2")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun decode(datagram: Datagram) =
|
||||||
|
decode(datagram.packet.readByteArray().toUByteArray())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
/*
|
||||||
|
* 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
|
||||||
|
|
||||||
|
import io.ktor.network.sockets.*
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The interface for common UDP connector shared by UDP components
|
||||||
|
*/
|
||||||
|
internal interface UdpConnector {
|
||||||
|
/**
|
||||||
|
* Called when client connection is done so the provider could free resources
|
||||||
|
*/
|
||||||
|
suspend fun disconnectClient(address: SocketAddress)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send a block from a proper UDP socket
|
||||||
|
*/
|
||||||
|
suspend fun sendBlock(block: UdpBlock, toAddress: SocketAddress)
|
||||||
|
}
|
||||||
@@ -0,0 +1,158 @@
|
|||||||
|
/*
|
||||||
|
* 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
|
||||||
|
|
||||||
|
import io.ktor.network.selector.*
|
||||||
|
import io.ktor.network.sockets.*
|
||||||
|
import io.ktor.utils.io.CancellationException
|
||||||
|
import kotlinx.coroutines.*
|
||||||
|
import kotlinx.coroutines.flow.Flow
|
||||||
|
import net.sergeych.kiloparsec.KiloClient
|
||||||
|
import net.sergeych.kiloparsec.KiloServer
|
||||||
|
import net.sergeych.kiloparsec.RemoteInterface
|
||||||
|
import net.sergeych.mp_tools.globalLaunch
|
||||||
|
import net.sergeych.tools.AtomicCounter
|
||||||
|
import kotlin.time.Duration
|
||||||
|
import kotlin.time.Duration.Companion.minutes
|
||||||
|
|
||||||
|
internal val udpCounter = AtomicCounter(0)
|
||||||
|
|
||||||
|
class UdpTransportException(override val message: String) : RemoteInterface.InvalidDataException(message)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Listen for incoming UDP connections and provide transport flow for it. See also [UdpServer.transportFlow]
|
||||||
|
* for another way to create a server. Use it with [KiloServer]:
|
||||||
|
* ```kotlin
|
||||||
|
* // Whatever server session data we might need:
|
||||||
|
* data class Session(
|
||||||
|
* var data: String,
|
||||||
|
* )
|
||||||
|
*
|
||||||
|
* // declare some commands (normally in a shared module):
|
||||||
|
* val cmdSave by command<String, Unit>()
|
||||||
|
* val cmdLoad by command<Unit, String>()
|
||||||
|
* val cmdDrop by command<Unit, Unit>()
|
||||||
|
* val cmdException by command<Unit, Unit>()
|
||||||
|
*
|
||||||
|
* // Interface using the session above, can be shared between many
|
||||||
|
* // server types and instances (different ports and protocols):
|
||||||
|
* val cli = KiloInterface<Session>().apply {
|
||||||
|
* onConnected { session.data = "start" }
|
||||||
|
* on(cmdSave) { session.data = it }
|
||||||
|
* on(cmdLoad) {
|
||||||
|
* session.data
|
||||||
|
* }
|
||||||
|
* on(cmdException) {
|
||||||
|
* throw TestException()
|
||||||
|
* }
|
||||||
|
* on(cmdDrop) {
|
||||||
|
* throw LocalInterface.BreakConnectionException()
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
* // Now create a server to accept incoming UDPs on our port:
|
||||||
|
* val server = KiloServer(cli, acceptUdpDevice(port)) {
|
||||||
|
* // This initializes new session for each incoming command
|
||||||
|
* Session("unknown")
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* See [connectUdpDevice] for the client sample.
|
||||||
|
*
|
||||||
|
* When it is necessary to stop listening to some port, use [UdpServer] instead.
|
||||||
|
*
|
||||||
|
* @param port port to listen
|
||||||
|
* @param localInterface string form local interface to listen
|
||||||
|
* @param maxInactivityTimeout maximum silence time after which the connection is supposed to be lost.
|
||||||
|
* the module automatically issues pings on inactivity when there is no data often enough
|
||||||
|
* to maintain the connection open.
|
||||||
|
*/
|
||||||
|
fun acceptUdpDevice(
|
||||||
|
port: Int,
|
||||||
|
localInterface: String = "0.0.0.0",
|
||||||
|
maxInactivityTimeout: Duration = 2.minutes,
|
||||||
|
): Flow<InetTransportDevice> =
|
||||||
|
UdpServer(port, localInterface,maxInactivityTimeout).transportFlow
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Connect to UDP server (see [acceptUdpDevice] or [UdpServer]) and return a [InetTransportDevice] for it. It
|
||||||
|
* should be used with [KiloClient] as connection provider:
|
||||||
|
* ```kotlin
|
||||||
|
* val client = KiloClient<Unit>() {
|
||||||
|
* connect { connectUdpDevice("localhost:$port") }
|
||||||
|
* }
|
||||||
|
* // now we can execute remote commands:
|
||||||
|
* assertEquals("start", client.call(cmdLoad))
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @param hostPort "host:port" string address of the remote UDP port to connect to
|
||||||
|
* @param maxInactivityTimeout maximum silence time after which the connection is supposed to be lost.
|
||||||
|
* the module automatically issues pings on inactivity when there is no data often enough
|
||||||
|
* to maintain the connection open.
|
||||||
|
*/
|
||||||
|
suspend fun connectUdpDevice(
|
||||||
|
hostPort: String,
|
||||||
|
maxInactivityTimeout: Duration = 2.minutes,
|
||||||
|
) = connectUdpDevice(hostPort.toNetworkAddress(), maxInactivityTimeout)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Connect to UDP server (see [acceptUdpDevice]) and return a [InetTransportDevice] for it. It
|
||||||
|
* should be used with [KiloClient] as connection provider:
|
||||||
|
* ```kotlin
|
||||||
|
* val client = KiloClient<Unit>() {
|
||||||
|
* connect { connectUdpDevice("localhost:$port") }
|
||||||
|
* }
|
||||||
|
* // now we can execute remote commands:
|
||||||
|
* assertEquals("start", client.call(cmdLoad))
|
||||||
|
* ```
|
||||||
|
* @param addr the network address where to connect to
|
||||||
|
* @param maxInactivityTimeout maximum silence time after which the connection is supposed to be lost.
|
||||||
|
* the module automatically issues pings on inactivity when there is no data often enough
|
||||||
|
* to maintain the connection open.
|
||||||
|
*/
|
||||||
|
suspend fun connectUdpDevice(
|
||||||
|
addr: NetworkAddress,
|
||||||
|
maxInactivityTimeout: Duration = 2.minutes,
|
||||||
|
): InetTransportDevice {
|
||||||
|
val selectorManager = SelectorManager(Dispatchers.IO)
|
||||||
|
val remoteAddress = InetSocketAddress(addr.host, addr.port)
|
||||||
|
|
||||||
|
val done = CompletableDeferred<Unit>()
|
||||||
|
|
||||||
|
val socket = aSocket(selectorManager).udp().connect(remoteAddress)
|
||||||
|
val transport = UdpSocketTransport(object : UdpConnector {
|
||||||
|
override suspend fun sendBlock(block: UdpBlock, toAddress: SocketAddress) {
|
||||||
|
socket.send(block.toDatagram(remoteAddress))
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun disconnectClient(address: SocketAddress) {
|
||||||
|
done.complete(Unit)
|
||||||
|
}
|
||||||
|
|
||||||
|
}, remoteAddress, false, maxInactivityTimeout)
|
||||||
|
|
||||||
|
globalLaunch {
|
||||||
|
launch {
|
||||||
|
while (isActive) {
|
||||||
|
try {
|
||||||
|
transport.processIncoming(UdpBlock.decode(socket.receive()))
|
||||||
|
} catch (_: CancellationException) {
|
||||||
|
break
|
||||||
|
} catch (e: Exception) {
|
||||||
|
transport.close()
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
done.await()
|
||||||
|
}
|
||||||
|
|
||||||
|
return transport.transportDevice
|
||||||
|
}
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
/*
|
||||||
|
* 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
|
||||||
|
|
||||||
|
import io.ktor.network.selector.*
|
||||||
|
import io.ktor.network.sockets.*
|
||||||
|
import io.ktor.utils.io.*
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.IO
|
||||||
|
import kotlinx.coroutines.channels.ClosedReceiveChannelException
|
||||||
|
import kotlinx.coroutines.flow.flow
|
||||||
|
import kotlinx.coroutines.sync.Mutex
|
||||||
|
import kotlinx.coroutines.sync.withLock
|
||||||
|
import net.sergeych.kiloparsec.KiloServer
|
||||||
|
import net.sergeych.mp_logger.LogTag
|
||||||
|
import net.sergeych.mp_logger.Loggable
|
||||||
|
import net.sergeych.mp_logger.debug
|
||||||
|
import net.sergeych.mp_logger.exception
|
||||||
|
import net.sergeych.mp_tools.globalDefer
|
||||||
|
import kotlin.time.Duration
|
||||||
|
import kotlin.time.Duration.Companion.minutes
|
||||||
|
|
||||||
|
/**
|
||||||
|
* UDP server for kiloparsec. Unlike [acceptUdpDevice], it allow stopping listening
|
||||||
|
* to the port when need with [close]. Use [transportFlow] with [KiloServer], here is the
|
||||||
|
* basic sample:
|
||||||
|
*
|
||||||
|
* ```kotlin
|
||||||
|
* val uServer = UdpServer(port)
|
||||||
|
* KiloServer(cli, uServer.transportFlow()) {
|
||||||
|
* Session("unknown")
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* // server is now active and accepts connections
|
||||||
|
* // ...
|
||||||
|
*
|
||||||
|
* // close and stop listening to the port:
|
||||||
|
* uServer.close()
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* See [acceptUdpDevice] for more information.
|
||||||
|
*
|
||||||
|
* @param port port to listen to
|
||||||
|
* @param localInterface string form of local interface to listen to
|
||||||
|
* @param maxInactivityTimeout maximum silence time after which the connection is supposed to be lost.
|
||||||
|
* the module automatically issues pings on inactivity when there is no data often enough
|
||||||
|
* to maintain the connection open.
|
||||||
|
|
||||||
|
*/
|
||||||
|
class UdpServer(val port: Int, localInterface: String = "0.0.0.0", maxInactivityTimeout: Duration = 2.minutes) :
|
||||||
|
Loggable by LogTag("UDPS${udpCounter.incrementAndGet()}"), UdpConnector {
|
||||||
|
|
||||||
|
private val sessions = mutableMapOf<SocketAddress, UdpSocketTransport>()
|
||||||
|
private val access = Mutex()
|
||||||
|
|
||||||
|
private val selectorManager = SelectorManager(Dispatchers.IO)
|
||||||
|
private val serverSocket = globalDefer {
|
||||||
|
aSocket(selectorManager).udp().bind(InetSocketAddress(localInterface, port))
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun disconnectClient(address: SocketAddress) {
|
||||||
|
access.withLock { sessions.remove(address) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* a transport flow of [InetTransportDevice] suitable to be used with [KiloServer], see [UdpServer] for the
|
||||||
|
* usage sample.
|
||||||
|
*/
|
||||||
|
val transportFlow by lazy {
|
||||||
|
flow {
|
||||||
|
while (true) {
|
||||||
|
try {
|
||||||
|
val datagram = serverSocket.await().receive()
|
||||||
|
val block = UdpBlock.decode(datagram)
|
||||||
|
val remoteAddress = datagram.address
|
||||||
|
|
||||||
|
access.withLock {
|
||||||
|
if (block == UdpBlock.Cancel) {
|
||||||
|
// if the cancel comes to already closed transport, do nothing
|
||||||
|
sessions.remove(remoteAddress)?.processIncoming(block)
|
||||||
|
} else {
|
||||||
|
sessions.getOrPut(remoteAddress) {
|
||||||
|
// new connection: create transport
|
||||||
|
debug { "Creating new connection to $remoteAddress" }
|
||||||
|
UdpSocketTransport(this@UdpServer, remoteAddress, true, maxInactivityTimeout)
|
||||||
|
// and emit it:
|
||||||
|
.also { emit(it.transportDevice) }
|
||||||
|
}.processIncoming(block)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (_: CancellationException) {
|
||||||
|
break
|
||||||
|
} catch (_: ClosedReceiveChannelException) {
|
||||||
|
break
|
||||||
|
} catch (e: Exception) {
|
||||||
|
exception { "unexpected exception in incoming datagram processing" to e }
|
||||||
|
close()
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun sendBlock(block: UdpBlock, toAddress: SocketAddress) {
|
||||||
|
serverSocket.await().send(block.toDatagram(toAddress))
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun isClosed(): Boolean = serverSocket.await().isClosed
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Close the UDP server. Calling it will cause:
|
||||||
|
*
|
||||||
|
* - Closing nound UDP socket on [port]
|
||||||
|
* - Closing all pending connections
|
||||||
|
* - cancelling the [transportFlow], which will cause Kiloparsec server to also stop
|
||||||
|
*
|
||||||
|
* Call suspends until socket and all sessions are closed. Later calls do nothing.
|
||||||
|
*/
|
||||||
|
suspend fun close() {
|
||||||
|
access.withLock {
|
||||||
|
if (!isClosed()) {
|
||||||
|
runCatching { serverSocket.await().close() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
while (sessions.isNotEmpty()) {
|
||||||
|
runCatching {
|
||||||
|
access.withLock { sessions.values.firstOrNull() }
|
||||||
|
?.close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,189 @@
|
|||||||
|
/*
|
||||||
|
* 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
|
||||||
|
|
||||||
|
import io.ktor.network.sockets.*
|
||||||
|
import io.ktor.utils.io.*
|
||||||
|
import kotlinx.coroutines.channels.BufferOverflow
|
||||||
|
import kotlinx.coroutines.channels.Channel
|
||||||
|
import kotlinx.coroutines.channels.ClosedReceiveChannelException
|
||||||
|
import kotlinx.coroutines.channels.ClosedSendChannelException
|
||||||
|
import kotlinx.coroutines.coroutineScope
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import net.sergeych.kiloparsec.SyncValue
|
||||||
|
import net.sergeych.mp_logger.Log
|
||||||
|
import net.sergeych.mp_logger.Loggable
|
||||||
|
import net.sergeych.mp_logger.debug
|
||||||
|
import net.sergeych.mp_logger.exception
|
||||||
|
import net.sergeych.mp_tools.globalLaunch
|
||||||
|
import kotlin.time.Clock
|
||||||
|
import kotlin.time.Duration
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This is a common part of UDP transport shared between client and server connections.
|
||||||
|
* It should not be used directly but bu the [UdpServer], [acceptUdpDevice] and [connectUdpDevice]
|
||||||
|
* respectively.
|
||||||
|
*/
|
||||||
|
internal class UdpSocketTransport(
|
||||||
|
private val server: UdpConnector,
|
||||||
|
val socketAddress: SocketAddress,
|
||||||
|
val isServer: Boolean,
|
||||||
|
val maxInactivityTimeout: Duration
|
||||||
|
) :
|
||||||
|
Loggable {
|
||||||
|
|
||||||
|
// IMPORTANT! Log stuff must be the first (or you shot your leg):
|
||||||
|
val address = (socketAddress as InetSocketAddress).let { NetworkAddress(it.hostname, it.port) }
|
||||||
|
override var logTag: String = "UDPT:$address${if (isServer) ":server" else ":client"}"
|
||||||
|
override var logLevel: Log.Level? = Log.Level.DEBUG
|
||||||
|
|
||||||
|
// Pinger params: keep them first!
|
||||||
|
private var lastSendAt = Clock.System.now()
|
||||||
|
private var lastReceived = Clock.System.now()
|
||||||
|
private val pingTimeout = maxInactivityTimeout / 3
|
||||||
|
private val pingSleep = pingTimeout / 3
|
||||||
|
private val pingMinTimeout = pingTimeout * 2 / 3
|
||||||
|
|
||||||
|
val inputDataBlocks = Channel<UByteArray>(256, onBufferOverflow = BufferOverflow.DROP_OLDEST)
|
||||||
|
val outputDataBlocks = Channel<UByteArray>(256, onBufferOverflow = BufferOverflow.DROP_OLDEST)
|
||||||
|
|
||||||
|
val inputUdpBlocks = Channel<UdpBlock>(256, onBufferOverflow = BufferOverflow.DROP_OLDEST)
|
||||||
|
|
||||||
|
private val job = globalLaunch {
|
||||||
|
coroutineScope {
|
||||||
|
launch { convertOutput() }
|
||||||
|
launch { convertInput() }
|
||||||
|
launch { pinger() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
init {
|
||||||
|
// This is iverly important: it requires that
|
||||||
|
// all members are initialized before use. Otherwise kotlin
|
||||||
|
// may execute class members pr
|
||||||
|
debug { "initialization done" }
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
val transportDevice: InetTransportDevice by lazy {
|
||||||
|
InetTransportDevice(inputDataBlocks, outputDataBlocks, address, { close() }, {})
|
||||||
|
}
|
||||||
|
|
||||||
|
private val closedFlag = SyncValue(false)
|
||||||
|
|
||||||
|
val isClosed: Boolean = closedFlag.value
|
||||||
|
|
||||||
|
suspend fun close() {
|
||||||
|
closedFlag.mutate {
|
||||||
|
if (!it) {
|
||||||
|
runCatching { server.sendBlock(UdpBlock.Cancel, socketAddress) }
|
||||||
|
server.disconnectClient(socketAddress)
|
||||||
|
runCatching { inputDataBlocks.close() }
|
||||||
|
runCatching { outputDataBlocks.close() }
|
||||||
|
job.cancel()
|
||||||
|
}
|
||||||
|
true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
private suspend fun send(block: UdpBlock) {
|
||||||
|
server.sendBlock(block, socketAddress)
|
||||||
|
lastSendAt = Clock.System.now()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Process the block recoded by the server. Note that it should properly process all
|
||||||
|
* block types, e.g. close on [UdpBlock.Cancel], etc. Server will not close us!
|
||||||
|
*
|
||||||
|
* __Important: it should not block, instead, server expects it to return ASAP__, so it
|
||||||
|
* executes in a local coroutine context.
|
||||||
|
*
|
||||||
|
* Also it should not throw exceptions.
|
||||||
|
*/
|
||||||
|
fun processIncoming(block: UdpBlock) {
|
||||||
|
inputUdpBlocks.trySend(block)
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun convertInput() {
|
||||||
|
while(!isClosed) {
|
||||||
|
when (val block = inputUdpBlocks.receiveCatching().getOrNull()) {
|
||||||
|
|
||||||
|
null -> break
|
||||||
|
|
||||||
|
is UdpBlock.Cancel -> globalLaunch {
|
||||||
|
debug { "received cancel block, requesting close" }
|
||||||
|
kotlin.runCatching { close() }
|
||||||
|
}
|
||||||
|
|
||||||
|
is UdpBlock.Data -> {
|
||||||
|
// input does not block, it uses DROP_OLDEST policy
|
||||||
|
lastReceived = Clock.System.now()
|
||||||
|
val result = kotlin.runCatching { inputDataBlocks.send(block.data) }
|
||||||
|
when (val e = result.exceptionOrNull()) {
|
||||||
|
null -> {}
|
||||||
|
is ClosedSendChannelException -> {
|
||||||
|
debug { "received close channel" }
|
||||||
|
close()
|
||||||
|
}
|
||||||
|
|
||||||
|
is CancellationException -> {}
|
||||||
|
else -> {
|
||||||
|
exception { "unexpected exception" to e }
|
||||||
|
close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
UdpBlock.Ping -> {
|
||||||
|
lastReceived = Clock.System.now()
|
||||||
|
if (lastSendAt - lastReceived > pingMinTimeout) send(UdpBlock.Ping)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun pinger() {
|
||||||
|
while (!isClosed) {
|
||||||
|
delay(pingSleep)
|
||||||
|
val inactivity = Clock.System.now() - lastSendAt
|
||||||
|
if( inactivity > maxInactivityTimeout) {
|
||||||
|
debug { "inactivity timout: closing the connection" }
|
||||||
|
close()
|
||||||
|
}
|
||||||
|
if (inactivity >= pingTimeout) {
|
||||||
|
debug { "pinger sends a ping on timeout" }
|
||||||
|
send(UdpBlock.Ping)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun convertOutput() {
|
||||||
|
while (!isClosed) {
|
||||||
|
try {
|
||||||
|
server.sendBlock(UdpBlock.Data(outputDataBlocks.receive()), socketAddress)
|
||||||
|
} catch (_: CancellationException) {
|
||||||
|
// this is ok
|
||||||
|
break
|
||||||
|
} catch (_: ClosedReceiveChannelException) {
|
||||||
|
debug { "input channel is closed, closing" }
|
||||||
|
close()
|
||||||
|
break
|
||||||
|
} catch (e: Exception) {
|
||||||
|
exception { "unexpected exception in convertOutput" to e }
|
||||||
|
close()
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
debug { "exiting convertOutput" }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,215 @@
|
|||||||
|
/*
|
||||||
|
* 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
|
||||||
|
|
||||||
|
import assertThrows
|
||||||
|
import kotlinx.coroutines.test.runTest
|
||||||
|
import net.sergeych.crypto2.initCrypto
|
||||||
|
import net.sergeych.kiloparsec.*
|
||||||
|
import net.sergeych.mp_logger.Log
|
||||||
|
import kotlin.random.Random
|
||||||
|
import kotlin.test.Test
|
||||||
|
import kotlin.test.assertEquals
|
||||||
|
import kotlin.test.assertIs
|
||||||
|
|
||||||
|
class InternetTest {
|
||||||
|
class TestException : Exception("test1")
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun tcpTest() = runTest {
|
||||||
|
initCrypto()
|
||||||
|
Log.connectConsole(Log.Level.DEBUG)
|
||||||
|
data class Session(
|
||||||
|
var data: String,
|
||||||
|
)
|
||||||
|
|
||||||
|
val port = 27170 + Random.nextInt(1, 200)
|
||||||
|
|
||||||
|
val cmdSave by command<String, Unit>()
|
||||||
|
val cmdLoad by command<Unit, String>()
|
||||||
|
val cmdDrop by command<Unit, Unit>()
|
||||||
|
val cmdPing by command<String, String>()
|
||||||
|
val cmdException by command<Unit, Unit>()
|
||||||
|
val cmdCallClient by command<String, String>()
|
||||||
|
|
||||||
|
val serverInterface = 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()
|
||||||
|
}
|
||||||
|
on(cmdCallClient) {
|
||||||
|
remote.call(cmdPing, it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val server = KiloServer(serverInterface, acceptTcpDevice(port)) {
|
||||||
|
Session("unknown")
|
||||||
|
}
|
||||||
|
|
||||||
|
data class LocalSession(val localFoo: String)
|
||||||
|
|
||||||
|
val client = KiloClient {
|
||||||
|
addErrors(serverInterface)
|
||||||
|
session { LocalSession("unknown") }
|
||||||
|
// TODO: add register error variant
|
||||||
|
connect { connectTcpDevice("localhost:$port") }
|
||||||
|
local {
|
||||||
|
on(cmdPing) {
|
||||||
|
"pong! $it"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals("start", client.call(cmdLoad))
|
||||||
|
|
||||||
|
client.call(cmdSave, "foobar")
|
||||||
|
assertEquals("foobar", client.call(cmdLoad))
|
||||||
|
|
||||||
|
val res = kotlin.runCatching { client.call(cmdException) }
|
||||||
|
assertIs<TestException>(res.exceptionOrNull())
|
||||||
|
assertEquals("foobar", client.call(cmdLoad))
|
||||||
|
|
||||||
|
assertThrows<RemoteInterface.ClosedException> { client.call(cmdDrop) }
|
||||||
|
|
||||||
|
// reconnect?
|
||||||
|
assertEquals("start", client.call(cmdLoad))
|
||||||
|
assertEquals("pong! 42", client.call(cmdCallClient, "42"))
|
||||||
|
server.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun udpTest() = runTest {
|
||||||
|
initCrypto()
|
||||||
|
Log.connectConsole(Log.Level.DEBUG)
|
||||||
|
data class Session(
|
||||||
|
var data: String,
|
||||||
|
)
|
||||||
|
|
||||||
|
val port = 27170 + Random.nextInt(1, 200)
|
||||||
|
|
||||||
|
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, acceptUdpDevice(port)) {
|
||||||
|
Session("unknown")
|
||||||
|
}
|
||||||
|
|
||||||
|
val client = KiloClient<Unit>() {
|
||||||
|
addErrors(cli)
|
||||||
|
connect { connectUdpDevice("127.0.0.1:$port") }
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals("start", client.call(cmdLoad))
|
||||||
|
|
||||||
|
client.call(cmdSave, "foobar")
|
||||||
|
assertEquals("foobar", client.call(cmdLoad))
|
||||||
|
|
||||||
|
val res = kotlin.runCatching { client.call(cmdException) }
|
||||||
|
assertIs<TestException>(res.exceptionOrNull())
|
||||||
|
assertEquals("foobar", client.call(cmdLoad))
|
||||||
|
|
||||||
|
assertThrows<RemoteInterface.ClosedException> { client.call(cmdDrop) }
|
||||||
|
|
||||||
|
// reconnect?
|
||||||
|
assertEquals("start", client.call(cmdLoad))
|
||||||
|
|
||||||
|
server.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun udpServerTest() = runTest {
|
||||||
|
initCrypto()
|
||||||
|
Log.connectConsole(Log.Level.DEBUG)
|
||||||
|
data class Session(
|
||||||
|
var data: String,
|
||||||
|
)
|
||||||
|
|
||||||
|
val port = 27170 + Random.nextInt(1, 900)
|
||||||
|
|
||||||
|
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 uServer = UdpServer(port)
|
||||||
|
|
||||||
|
KiloServer(cli, uServer.transportFlow) {
|
||||||
|
Session("unknown")
|
||||||
|
}
|
||||||
|
|
||||||
|
// second server
|
||||||
|
KiloServer(cli,acceptUdpDevice(uServer.port+1)) { Session("unknown2") }
|
||||||
|
|
||||||
|
|
||||||
|
val client = KiloClient<Unit>() {
|
||||||
|
addErrors(cli)
|
||||||
|
connect { connectUdpDevice("127.0.0.1:$port") }
|
||||||
|
}
|
||||||
|
val client2 = KiloClient<Unit>() { connect { connectUdpDevice("127.0.0.1:${port+1}") } }
|
||||||
|
|
||||||
|
assertEquals("start", client.call(cmdLoad))
|
||||||
|
assertEquals("start", client2.call(cmdLoad))
|
||||||
|
|
||||||
|
client.call(cmdSave, "foobar")
|
||||||
|
client2.call(cmdSave, "buzz")
|
||||||
|
assertEquals("foobar", client.call(cmdLoad))
|
||||||
|
assertEquals("buzz", client2.call(cmdLoad))
|
||||||
|
|
||||||
|
val res = kotlin.runCatching { client.call(cmdException) }
|
||||||
|
assertIs<TestException>(res.exceptionOrNull())
|
||||||
|
assertEquals("foobar", client.call(cmdLoad))
|
||||||
|
|
||||||
|
assertThrows<RemoteInterface.ClosedException> { client.call(cmdDrop) }
|
||||||
|
|
||||||
|
// reconnect?
|
||||||
|
assertEquals("start", client.call(cmdLoad))
|
||||||
|
|
||||||
|
uServer.close()
|
||||||
|
// server.close()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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")
|
|
||||||
}
|
|
||||||
Reference in new issue
Block a user