@tokamakdev/platform-android-arm64 0.1.1-beta.49 → 0.1.1-beta.50

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Binary file
@@ -42,7 +42,8 @@ app=$project/app
42
42
  native=$app/src/main/jniLibs/arm64-v8a
43
43
  assets=$app/src/main/assets/app
44
44
  kotlin=$app/src/main/kotlin/com/tokamak/runtime
45
- plugins_root=$app/src/main/kotlin/tokamak/plugins
45
+ plugin_api=$project/tokamak-plugin
46
+ plugin_modules=$project/plugins
46
47
  icons=$input/icons/$platform
47
48
 
48
49
  xml_escape() {
@@ -54,11 +55,22 @@ xml_escape() {
54
55
  -e "s/'/\'/g"
55
56
  }
56
57
 
57
- rm -rf "$app/src/main/assets" "$app/src/main/jniLibs" "$app/src/main/kotlin" "$app/src/main/res" "$app/user" "$output"
58
- mkdir -p "$native" "$assets" "$kotlin" "$plugins_root" "$app/src/main/res"
58
+ rm -rf "$app/src/main/assets" "$app/src/main/jniLibs" "$app/src/main/kotlin" "$app/src/main/res" "$app/user" "$plugin_api" "$plugin_modules" "$output"
59
+ mkdir -p "$native" "$assets" "$kotlin" "$app/src/main/res" "$plugin_api/src/main/kotlin"
59
60
  cp -R "$input/app/." "$assets/"
60
61
  cp "$input/runtime/libtokamak.so" "$native/libtokamak.so"
61
- cp -R "$input/native-shell/." "$kotlin/"
62
+ cp -R "$input/native-shell/app/." "$kotlin/"
63
+ cp -R "$input/native-shell/plugin/." "$plugin_api/src/main/kotlin/"
64
+ cat > "$plugin_api/build.gradle" <<'EOF'
65
+ plugins {
66
+ id 'com.android.library'
67
+ id 'org.jetbrains.kotlin.android'
68
+ }
69
+
70
+ android {
71
+ namespace 'com.tokamak.runtime.plugin'
72
+ }
73
+ EOF
62
74
 
63
75
  has_icon=false
64
76
  if [[ -d "$icons" ]]; then
@@ -72,19 +84,18 @@ if [[ -d "$icons" ]]; then
72
84
  has_icon=true
73
85
  fi
74
86
 
87
+ # Each plugin is a library module, so its manifest merges below the app's and
88
+ # its dependencies stay its own.
75
89
  shopt -s nullglob
76
- plugin_classes=()
77
- for plugin in "$input/plugins"/*; do
78
- [[ -d "$plugin" ]] || continue
90
+ for plugin in "$input/plugins"/*/; do
79
91
  plugin_id=$(basename "$plugin")
80
- plugin_classes+=("$(cat "$plugin/class")")
81
- plugin_sources=$plugins_root/$plugin_id
82
- mkdir -p "$plugin_sources"
92
+ module=$plugin_modules/$plugin_id
93
+ mkdir -p "$module/src/main/kotlin"
83
94
  for source in "$plugin/sources"/*; do
84
95
  [[ -f "$source" ]] || continue
85
96
  case "$source" in
86
97
  *.kt)
87
- cp "$source" "$plugin_sources/$(basename "$source")"
98
+ cp "$source" "$module/src/main/kotlin/$(basename "$source")"
88
99
  ;;
89
100
  *)
90
101
  echo "Android plugin source must be Kotlin: $source" >&2
@@ -92,6 +103,24 @@ for plugin in "$input/plugins"/*; do
92
103
  ;;
93
104
  esac
94
105
  done
106
+ if [[ -f "$plugin/AndroidManifest.xml" ]]; then
107
+ cp "$plugin/AndroidManifest.xml" "$module/src/main/AndroidManifest.xml"
108
+ fi
109
+ {
110
+ printf '%s\n' 'plugins {'
111
+ printf '%s\n' " id 'com.android.library'"
112
+ printf '%s\n' " id 'org.jetbrains.kotlin.android'"
113
+ printf '%s\n\n' '}'
114
+ printf '%s\n' 'android {'
115
+ printf " namespace 'tokamak.plugins.%s'\n" "${plugin_id//-/_}"
116
+ printf '%s\n\n' '}'
117
+ printf '%s\n' 'dependencies {'
118
+ printf '%s\n' " implementation project(':tokamak-plugin')"
119
+ for dependency in "$plugin/dependencies"/*; do
120
+ printf " implementation '%s'\n" "$(cat "$dependency")"
121
+ done
122
+ printf '%s\n' '}'
123
+ } > "$module/build.gradle"
95
124
  done
96
125
 
97
126
  mkdir -p "$project/app/src/main"
@@ -111,14 +140,43 @@ dependencyResolutionManagement {
111
140
  }
112
141
  }
113
142
  rootProject.name = 'tokamak'
114
- include ':app'
143
+ include ':app', ':tokamak-plugin'
115
144
  EOF
145
+ for plugin in "$input/plugins"/*/; do
146
+ printf "include ':plugins:%s'\n" "$(basename "$plugin")" >> "$project/settings.gradle"
147
+ done
116
148
 
117
149
  cat > "$project/build.gradle" <<'EOF'
118
150
  plugins {
119
151
  id 'com.android.application' version '8.7.3' apply false
152
+ id 'com.android.library' version '8.7.3' apply false
120
153
  id 'org.jetbrains.kotlin.android' version '2.1.0' apply false
121
154
  }
155
+
156
+ subprojects {
157
+ plugins.withId('com.android.library') {
158
+ android {
159
+ compileSdk 35
160
+ defaultConfig {
161
+ minSdk 31
162
+ }
163
+ sourceSets {
164
+ main {
165
+ kotlin.srcDirs += 'src/main/kotlin'
166
+ }
167
+ }
168
+ compileOptions {
169
+ sourceCompatibility JavaVersion.VERSION_17
170
+ targetCompatibility JavaVersion.VERSION_17
171
+ }
172
+ }
173
+ }
174
+ plugins.withId('org.jetbrains.kotlin.android') {
175
+ kotlin {
176
+ jvmToolchain(17)
177
+ }
178
+ }
179
+ }
122
180
  EOF
123
181
 
124
182
  printf '%s\n' 'android.useAndroidX=true' > "$project/gradle.properties"
@@ -158,17 +216,18 @@ android {
158
216
  lint {
159
217
  checkOnly 'NewApi'
160
218
  abortOnError true
219
+ checkDependencies true
161
220
  }
162
221
  }
163
222
 
164
- kotlin {
165
- jvmToolchain(17)
166
- }
167
-
168
223
  dependencies {
169
224
  implementation 'androidx.webkit:webkit:1.12.1'
170
- }
225
+ implementation project(':tokamak-plugin')
171
226
  EOF
227
+ for plugin in "$input/plugins"/*/; do
228
+ printf " implementation project(':plugins:%s')\n" "$(basename "$plugin")" >> "$project/app/build.gradle"
229
+ done
230
+ printf '%s\n' '}' >> "$project/app/build.gradle"
172
231
 
173
232
  if [[ -n "$user_manifest" ]]; then
174
233
  mkdir -p "$app/user"
@@ -186,14 +245,11 @@ fi
186
245
  registry=$kotlin/TokamakPluginRegistry.kt
187
246
  {
188
247
  printf '%s\n\n' 'package com.tokamak.runtime'
189
- printf '%s\n\n' 'import android.app.Activity'
190
- printf '%s\n' 'internal fun tokamakPlugins(activity: Activity): List<TokamakPlugin> ='
248
+ printf '%s\n' 'internal fun tokamakPlugins(host: TokamakHost): List<TokamakPlugin> ='
191
249
  printf '%s\n' ' listOf('
192
- if ((${#plugin_classes[@]} > 0)); then
193
- for class in "${plugin_classes[@]}"; do
194
- printf ' %s(activity),\n' "$class"
195
- done
196
- fi
250
+ for plugin in "$input/plugins"/*/; do
251
+ printf ' %s(host),\n' "$(cat "$plugin/class")"
252
+ done
197
253
  printf '%s\n' ' )'
198
254
  } > "$registry"
199
255
 
@@ -212,7 +268,7 @@ manifest=$app/src/main/AndroidManifest.xml
212
268
  if [[ "$has_icon" == true ]]; then
213
269
  icon_attribute=' android:icon="@mipmap/ic_launcher"'
214
270
  fi
215
- printf ' <application android:label="%s"%s android:usesCleartextTraffic="false">\n' "$(xml_escape "$app_name")" "$icon_attribute"
271
+ printf ' <application android:name=".TokamakApplication" android:label="%s"%s android:usesCleartextTraffic="false">\n' "$(xml_escape "$app_name")" "$icon_attribute"
216
272
  printf ' <meta-data android:name="tokamak.host" android:value="%s" />\n' "$host"
217
273
  if [[ -n "$dev_endpoint" ]]; then
218
274
  printf ' <meta-data android:name="tokamak.dev.endpoint" android:value="%s" />\n' "$dev_endpoint"
@@ -1,7 +1,7 @@
1
1
  package com.tokamak.runtime
2
2
 
3
3
  import android.app.Activity
4
- import android.content.pm.PackageManager
4
+ import android.content.Intent
5
5
  import android.os.Bundle
6
6
  import android.util.Log
7
7
  import android.view.ViewGroup
@@ -9,20 +9,18 @@ import android.view.WindowInsets
9
9
  import android.webkit.WebView
10
10
  import android.widget.FrameLayout
11
11
  import androidx.webkit.WebViewFeature
12
- import java.io.File
13
12
 
14
13
  private const val TAG = "tokamak"
15
- private const val HOST_METADATA = "tokamak.host"
16
- private const val DEV_ENDPOINT_METADATA = "tokamak.dev.endpoint"
17
- private const val DEV_SESSION_TOKEN_METADATA = "tokamak.dev.session-token"
18
14
  private const val FAILED =
19
15
  "<!doctype html><title>tokamak</title><h1>App failed to start</h1><p>See logcat for details.</p>"
20
16
  private const val UNSUPPORTED =
21
17
  "<!doctype html><title>tokamak</title><h1>Unsupported WebView</h1>" +
22
18
  "<p>This device's WebView cannot serve the app's secure origin.</p>"
23
19
 
24
- /** The tokamak application: owns the window, WebView, and runtime lifecycle. */
20
+ /** The tokamak window: shows the app's WebView over the process's runtime. */
25
21
  class TokamakActivity : Activity() {
22
+ private val tokamak: TokamakApplication
23
+ get() = application as TokamakApplication
26
24
  private lateinit var webView: WebView
27
25
  private lateinit var pluginBridge: TokamakPluginBridge
28
26
  private lateinit var chromeClient: TokamakWebChromeClient
@@ -33,18 +31,22 @@ class TokamakActivity : Activity() {
33
31
 
34
32
  override fun onCreate(savedInstanceState: Bundle?) {
35
33
  super.onCreate(savedInstanceState)
34
+ tokamak.activity = this
36
35
  webView = WebView(this).apply {
37
36
  settings.javaScriptEnabled = true
38
37
  settings.domStorageEnabled = true
39
38
  settings.setSupportMultipleWindows(false)
40
39
  }
41
- chromeClient = TokamakWebChromeClient(this, appHost())
40
+ chromeClient = TokamakWebChromeClient(this, tokamak.appHost)
42
41
  webView.webChromeClient = chromeClient
43
- pluginBridge = TokamakPluginBridge(this, appHost(), tokamakPlugins(this))
42
+ pluginBridge = TokamakPluginBridge(this, tokamak.appHost, tokamak.plugins)
44
43
  if (WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)) {
45
44
  pluginBridge.install(webView)
46
45
  }
47
46
  setContentView(webViewContainer())
47
+ // A recreated activity or one reopened from Recents carries an intent plugins have had.
48
+ val launchedFromHistory = intent.flags and Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY != 0
49
+ if (savedInstanceState == null && !launchedFromHistory) deliver(intent)
48
50
  if (!proxyIsSupported()) {
49
51
  show(UNSUPPORTED)
50
52
  return
@@ -52,6 +54,12 @@ class TokamakActivity : Activity() {
52
54
  Thread(::startRuntime, "tokamak-startup").start()
53
55
  }
54
56
 
57
+ override fun onNewIntent(intent: Intent) {
58
+ super.onNewIntent(intent)
59
+ setIntent(intent)
60
+ deliver(intent)
61
+ }
62
+
55
63
  override fun onResume() {
56
64
  super.onResume()
57
65
  restoreGeneration += 1
@@ -62,12 +70,11 @@ class TokamakActivity : Activity() {
62
70
  override fun onDestroy() {
63
71
  destroyed = true
64
72
  restoreGeneration += 1
73
+ if (tokamak.activity === this) tokamak.activity = null
65
74
  TokamakProxy.release(this)
66
75
  pluginBridge.close()
67
76
  webView.stopLoading()
68
77
  webView.destroy()
69
- runtime?.stop()
70
- runtime = null
71
78
  super.onDestroy()
72
79
  }
73
80
 
@@ -78,32 +85,22 @@ class TokamakActivity : Activity() {
78
85
  ) {
79
86
  super.onRequestPermissionsResult(requestCode, permissions, grantResults)
80
87
  chromeClient.onRequestPermissionsResult(requestCode)
81
- pluginBridge.onRequestPermissionsResult(requestCode, permissions, grantResults)
88
+ tokamak.plugins.values.forEach {
89
+ it.onRequestPermissionsResult(requestCode, permissions, grantResults)
90
+ }
82
91
  }
83
92
 
84
- private fun startRuntime() {
85
- val started = runCatching { startConfiguredRuntime() }
86
- runOnUiThread { finishStart(started) }
93
+ private fun deliver(intent: Intent) {
94
+ tokamak.plugins.values.forEach { it.onIntent(intent) }
87
95
  }
88
96
 
89
- private fun startConfiguredRuntime(): TokamakRuntime {
90
- val metadata = packageManager
91
- .getApplicationInfo(packageName, PackageManager.GET_META_DATA)
92
- .metaData
93
- val endpoint = metadata?.getString(DEV_ENDPOINT_METADATA)
94
- val sessionToken = metadata?.getString(DEV_SESSION_TOKEN_METADATA)
95
- return if (!endpoint.isNullOrEmpty() && !sessionToken.isNullOrEmpty()) {
96
- TokamakRuntime.startDevelopment(stateDir(), appHost(), endpoint, sessionToken)
97
- } else {
98
- TokamakRuntime.start(unpackApp(), stateDir(), appHost())
99
- }
97
+ private fun startRuntime() {
98
+ val started = runCatching { tokamak.runtime }
99
+ runOnUiThread { finishStart(started) }
100
100
  }
101
101
 
102
102
  private fun finishStart(started: Result<TokamakRuntime>) {
103
- if (destroyed) {
104
- started.getOrNull()?.stop()
105
- return
106
- }
103
+ if (destroyed) return
107
104
  val runtime = started.getOrElse { error ->
108
105
  Log.e(TAG, "tokamak failed to start", error)
109
106
  show(FAILED)
@@ -111,7 +108,7 @@ class TokamakActivity : Activity() {
111
108
  }
112
109
  this.runtime = runtime
113
110
  proxyPort = runtime.port
114
- TokamakProxy.acquire(this, appHost(), runtime.port)
111
+ TokamakProxy.acquire(this, tokamak.appHost, runtime.port)
115
112
  }
116
113
 
117
114
  private fun restoreGateway(runtime: TokamakRuntime, generation: Long) {
@@ -128,7 +125,7 @@ class TokamakActivity : Activity() {
128
125
  if (port != runtime.port) return@onSuccess
129
126
  if (port != proxyPort) {
130
127
  proxyPort = port
131
- TokamakProxy.acquire(this, appHost(), port)
128
+ TokamakProxy.acquire(this, tokamak.appHost, port)
132
129
  }
133
130
  }
134
131
  .onFailure { error ->
@@ -141,8 +138,9 @@ class TokamakActivity : Activity() {
141
138
  internal fun proxyReady() {
142
139
  if (destroyed) return
143
140
  val runtime = runtime ?: return
144
- webView.webViewClient = TokamakWebViewClient(this, appHost(), runtime, pluginBridge)
145
- webView.loadUrl("https://${appHost()}/")
141
+ webView.webViewClient =
142
+ TokamakWebViewClient(this, tokamak.appHost, runtime, pluginBridge)
143
+ webView.loadUrl("https://${tokamak.appHost}/")
146
144
  }
147
145
 
148
146
  private fun proxyIsSupported(): Boolean =
@@ -167,35 +165,4 @@ class TokamakActivity : Activity() {
167
165
  insets
168
166
  }
169
167
  }
170
-
171
- /** Copy the packaged app out of the APK so the runtime can read it as files. */
172
- private fun unpackApp(): File {
173
- val app = File(filesDir, "tokamak/app")
174
- app.deleteRecursively()
175
- copyAsset("app", app)
176
- return app
177
- }
178
-
179
- private fun copyAsset(source: String, destination: File) {
180
- val entries = assets.list(source) ?: emptyArray()
181
- if (entries.isEmpty()) {
182
- destination.parentFile?.mkdirs()
183
- assets.open(source).use { input ->
184
- destination.outputStream().use(input::copyTo)
185
- }
186
- return
187
- }
188
- destination.mkdirs()
189
- for (entry in entries) copyAsset("$source/$entry", File(destination, entry))
190
- }
191
-
192
- private fun stateDir(): File = File(filesDir, "tokamak/state").apply { mkdirs() }
193
-
194
- private fun appHost(): String {
195
- val info = packageManager.getApplicationInfo(packageName, PackageManager.GET_META_DATA)
196
- return requireNotNull(info.metaData?.getString(HOST_METADATA)) {
197
- "$HOST_METADATA is required"
198
- }
199
- }
200
-
201
168
  }
@@ -0,0 +1,86 @@
1
+ package com.tokamak.runtime
2
+
3
+ import android.app.Activity
4
+ import android.app.Application
5
+ import android.content.Context
6
+ import android.content.pm.PackageManager
7
+ import java.io.File
8
+
9
+ private const val HOST_METADATA = "tokamak.host"
10
+ private const val DEV_ENDPOINT_METADATA = "tokamak.dev.endpoint"
11
+ private const val DEV_SESSION_TOKEN_METADATA = "tokamak.dev.session-token"
12
+
13
+ /**
14
+ * The tokamak process. Owns the runtime and native plugins, which outlive any activity, so a
15
+ * plugin can run Worker code when the system starts the app in the background.
16
+ */
17
+ class TokamakApplication : Application(), TokamakHost {
18
+ override val context: Context
19
+ get() = this
20
+
21
+ @Volatile
22
+ override var activity: Activity? = null
23
+
24
+ /** Every plugin, by ID. */
25
+ val plugins: Map<String, TokamakPlugin> by lazy {
26
+ buildMap {
27
+ tokamakPlugins(this@TokamakApplication).forEach { plugin ->
28
+ check(put(plugin.id, plugin) == null) { "Duplicate plugin ID" }
29
+ }
30
+ }
31
+ }
32
+
33
+ /** The running runtime, started on first use. Blocks while it starts. */
34
+ internal val runtime: TokamakRuntime by lazy(::startRuntime)
35
+
36
+ /** The host of the app origin, `https://<appHost>`. */
37
+ val appHost: String by lazy {
38
+ requireNotNull(metadata()?.getString(HOST_METADATA)) { "$HOST_METADATA is required" }
39
+ }
40
+
41
+ override fun dispatch(event: String, payload: String, timeoutMillis: Long): String? =
42
+ runtime.dispatch(event, payload, timeoutMillis)
43
+
44
+ override fun plugin(id: String): TokamakPlugin? = plugins[id]
45
+
46
+ private fun startRuntime(): TokamakRuntime {
47
+ val metadata = metadata()
48
+ val endpoint = metadata?.getString(DEV_ENDPOINT_METADATA)
49
+ val sessionToken = metadata?.getString(DEV_SESSION_TOKEN_METADATA)
50
+ return if (!endpoint.isNullOrEmpty() && !sessionToken.isNullOrEmpty()) {
51
+ TokamakRuntime.startDevelopment(stateDir(), appHost, endpoint, sessionToken)
52
+ } else {
53
+ TokamakRuntime.start(unpackApp(), stateDir(), appHost)
54
+ }
55
+ }
56
+
57
+ private fun metadata() =
58
+ packageManager.getApplicationInfo(packageName, PackageManager.GET_META_DATA).metaData
59
+
60
+ /** Copy the packaged app out of the APK once per install, so the runtime can read it as files. */
61
+ private fun unpackApp(): File {
62
+ val app = File(filesDir, "tokamak/app")
63
+ val unpacked = File(filesDir, "tokamak/app.installed")
64
+ val installed = packageManager.getPackageInfo(packageName, 0).lastUpdateTime.toString()
65
+ if (unpacked.isFile && unpacked.readText() == installed) return app
66
+ app.deleteRecursively()
67
+ copyAsset("app", app)
68
+ unpacked.writeText(installed)
69
+ return app
70
+ }
71
+
72
+ private fun copyAsset(source: String, destination: File) {
73
+ val entries = assets.list(source) ?: emptyArray()
74
+ if (entries.isEmpty()) {
75
+ destination.parentFile?.mkdirs()
76
+ assets.open(source).use { input ->
77
+ destination.outputStream().use(input::copyTo)
78
+ }
79
+ return
80
+ }
81
+ destination.mkdirs()
82
+ for (entry in entries) copyAsset("$source/$entry", File(destination, entry))
83
+ }
84
+
85
+ private fun stateDir(): File = File(filesDir, "tokamak/state").apply { mkdirs() }
86
+ }
@@ -8,53 +8,14 @@ import androidx.webkit.WebMessageCompat
8
8
  import androidx.webkit.WebViewCompat
9
9
  import org.json.JSONObject
10
10
 
11
- internal class TokamakPluginError(
12
- val errorName: String,
13
- message: String,
14
- ) : Exception(message) {
15
- companion object {
16
- fun notSupported(message: String) = TokamakPluginError("NotSupportedError", message)
17
- }
18
- }
19
-
20
- internal typealias TokamakPluginReply = (Result<Any?>) -> Unit
21
-
22
- internal interface TokamakPlugin {
23
- val id: String
24
-
25
- fun call(method: String, arguments: Any?, reply: TokamakPluginReply) {
26
- reply(Result.failure(TokamakPluginError.notSupported("$id.$method is not supported")))
27
- }
28
-
29
- fun subscribe(
30
- method: String,
31
- arguments: Any?,
32
- reply: TokamakPluginReply,
33
- ): () -> Unit {
34
- reply(Result.failure(TokamakPluginError.notSupported("$id.$method is not supported")))
35
- return {}
36
- }
37
-
38
- fun onRequestPermissionsResult(
39
- requestCode: Int,
40
- permissions: Array<out String>,
41
- grantResults: IntArray,
42
- ) = Unit
43
- }
44
-
11
+ /** Carries calls and subscriptions between the page and the app's plugins. */
45
12
  internal class TokamakPluginBridge(
46
13
  private val activity: Activity,
47
14
  private val host: String,
48
- plugins: List<TokamakPlugin>,
15
+ private val plugins: Map<String, TokamakPlugin>,
49
16
  ) : WebViewCompat.WebMessageListener {
50
17
  private data class RequestKey(val session: String, val id: Int)
51
18
 
52
- private val plugins =
53
- buildMap {
54
- plugins.forEach { plugin ->
55
- check(put(plugin.id, plugin) == null) { "Duplicate plugin ID" }
56
- }
57
- }
58
19
  private val cancellations = mutableMapOf<RequestKey, () -> Unit>()
59
20
  private var activeSession: String? = null
60
21
 
@@ -74,16 +35,6 @@ internal class TokamakPluginBridge(
74
35
  cancelAll.forEach { it() }
75
36
  }
76
37
 
77
- fun onRequestPermissionsResult(
78
- requestCode: Int,
79
- permissions: Array<out String>,
80
- grantResults: IntArray,
81
- ) {
82
- plugins.values.forEach {
83
- it.onRequestPermissionsResult(requestCode, permissions, grantResults)
84
- }
85
- }
86
-
87
38
  override fun onPostMessage(
88
39
  view: WebView,
89
40
  message: WebMessageCompat,
@@ -2,56 +2,38 @@ package com.tokamak.runtime
2
2
 
3
3
  import java.io.File
4
4
 
5
- /** The tokamak runtime running in this process. */
6
- internal class TokamakRuntime private constructor(private var handle: Long) {
7
- private val lock = Any()
8
-
5
+ /** The tokamak runtime, running for the life of the process. */
6
+ internal class TokamakRuntime private constructor(private val handle: Long) {
9
7
  /** The loopback port the gateway bound. */
10
8
  val port: Int
11
- get() = synchronized(lock) { nativePort(requireHandle()) }
9
+ get() = nativePort(handle)
12
10
 
13
- fun restoreGateway(): Int = synchronized(lock) {
14
- nativeRestoreGateway(requireHandle())
15
- }
11
+ fun restoreGateway(): Int = nativeRestoreGateway(handle)
16
12
 
17
- fun suspend() = synchronized(lock) {
18
- handle.takeIf { it != 0L }?.let(::nativeSuspend)
19
- }
13
+ fun suspend() = nativeSuspend(handle)
20
14
 
21
- fun resume() = synchronized(lock) {
22
- handle.takeIf { it != 0L }?.let(::nativeResume)
23
- }
15
+ fun resume() = nativeResume(handle)
24
16
 
25
- fun stop() = synchronized(lock) {
26
- if (handle == 0L) return
27
- val stopped = handle
28
- handle = 0
29
- nativeStop(stopped)
30
- }
17
+ /**
18
+ * Runs the Worker's [event] handler with a JSON [payload], blocking until it settles or
19
+ * [timeoutMillis] passes. Returns the handler's JSON result, or null when the Worker has
20
+ * no such handler.
21
+ */
22
+ fun dispatch(event: String, payload: String, timeoutMillis: Long): String? =
23
+ nativeDispatch(handle, event, payload, timeoutMillis)
31
24
 
32
25
  /**
33
26
  * The authority a server certificate for [host] must chain to, or null
34
27
  * when tokamak does not vouch for the host.
35
28
  */
36
- fun serverAuthority(host: String): ByteArray? = synchronized(lock) {
37
- handle.takeIf { it != 0L }?.let { nativeServerAuthority(it, host) }
38
- }
29
+ fun serverAuthority(host: String): ByteArray? = nativeServerAuthority(handle, host)
39
30
 
40
31
  /**
41
32
  * The client certificate and PKCS#8 private key, both DER, to present for
42
33
  * [host]. Null when tokamak cannot authenticate the connection.
43
34
  */
44
35
  fun clientIdentity(host: String, previousFailures: Int): Array<ByteArray>? =
45
- synchronized(lock) {
46
- handle.takeIf { it != 0L }?.let {
47
- nativeClientIdentity(it, host, previousFailures)
48
- }
49
- }
50
-
51
- private fun requireHandle(): Long {
52
- check(handle != 0L) { "tokamak runtime has stopped" }
53
- return handle
54
- }
36
+ nativeClientIdentity(handle, host, previousFailures)
55
37
 
56
38
  companion object {
57
39
  init {
@@ -95,7 +77,12 @@ internal class TokamakRuntime private constructor(private var handle: Long) {
95
77
  private external fun nativeResume(handle: Long)
96
78
 
97
79
  @JvmStatic
98
- private external fun nativeStop(handle: Long)
80
+ private external fun nativeDispatch(
81
+ handle: Long,
82
+ event: String,
83
+ payload: String,
84
+ timeoutMillis: Long,
85
+ ): String?
99
86
 
100
87
  @JvmStatic
101
88
  private external fun nativeServerAuthority(handle: Long, host: String): ByteArray?
@@ -0,0 +1,68 @@
1
+ package com.tokamak.runtime
2
+
3
+ import android.app.Activity
4
+ import android.content.Context
5
+ import android.content.Intent
6
+
7
+ /** A failure a plugin reports to the page as a `DOMException` named [errorName]. */
8
+ class TokamakPluginError(
9
+ val errorName: String,
10
+ message: String,
11
+ ) : Exception(message) {
12
+ companion object {
13
+ fun notSupported(message: String) = TokamakPluginError("NotSupportedError", message)
14
+ }
15
+ }
16
+
17
+ typealias TokamakPluginReply = (Result<Any?>) -> Unit
18
+
19
+ /** A native plugin, created once per process with the app's [TokamakHost]. */
20
+ interface TokamakPlugin {
21
+ val id: String
22
+
23
+ fun call(method: String, arguments: Any?, reply: TokamakPluginReply) {
24
+ reply(Result.failure(TokamakPluginError.notSupported("$id.$method is not supported")))
25
+ }
26
+
27
+ fun subscribe(
28
+ method: String,
29
+ arguments: Any?,
30
+ reply: TokamakPluginReply,
31
+ ): () -> Unit {
32
+ reply(Result.failure(TokamakPluginError.notSupported("$id.$method is not supported")))
33
+ return {}
34
+ }
35
+
36
+ fun onRequestPermissionsResult(
37
+ requestCode: Int,
38
+ permissions: Array<out String>,
39
+ grantResults: IntArray,
40
+ ) = Unit
41
+
42
+ /** Receives the intent that started the app's activity, and each intent it receives later. */
43
+ fun onIntent(intent: Intent) = Unit
44
+ }
45
+
46
+ /** The app as a plugin sees it: its context, its activity, and its Worker. */
47
+ interface TokamakHost {
48
+ /** The application context. */
49
+ val context: Context
50
+
51
+ /** The app's activity, or null while it has none. */
52
+ val activity: Activity?
53
+
54
+ /**
55
+ * Runs the Worker's [event] handler with a JSON [payload], including work it passes to
56
+ * `ctx.waitUntil`, and returns the handler's JSON result; null when the Worker has no
57
+ * handler for [event]. Starts the runtime when it is not running. Blocks, so call it
58
+ * off the main thread; throws when the handler fails or runs longer than [timeoutMillis].
59
+ */
60
+ fun dispatch(event: String, payload: String, timeoutMillis: Long): String?
61
+
62
+ /** The plugin with [id], or null when the app does not include it. */
63
+ fun plugin(id: String): TokamakPlugin?
64
+ }
65
+
66
+ /** The host of the app this context belongs to. */
67
+ val Context.tokamakHost: TokamakHost
68
+ get() = applicationContext as TokamakHost
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokamakdev/platform-android-arm64",
3
- "version": "0.1.1-beta.49",
3
+ "version": "0.1.1-beta.50",
4
4
  "description": "The tokamak platform pack for android-arm64",
5
5
  "repository": {
6
6
  "type": "git",