-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebworkerModule.kt
More file actions
240 lines (212 loc) · 8.6 KB
/
WebworkerModule.kt
File metadata and controls
240 lines (212 loc) · 8.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
package com.webworker
import android.util.Log
import com.facebook.react.bridge.Arguments
import com.facebook.react.bridge.Promise
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.module.annotations.ReactModule
import okhttp3.Call
import okhttp3.Callback
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import java.io.IOException
import java.util.concurrent.TimeUnit
/**
* React Native TurboModule for WebWorker support.
*
* This is a thin Android wrapper around the shared C++ WebWorkerCore.
* Mirrors the iOS implementation in ios/Webworker.mm.
*/
@ReactModule(name = WebworkerModule.NAME)
class WebworkerModule(reactContext: ReactApplicationContext) :
NativeWebworkerSpec(reactContext), WebWorkerNative.WorkerCallback {
private val client = OkHttpClient()
init {
// Initialize the native core with this module as the callback receiver
WebWorkerNative.initialize(this)
}
override fun getName(): String = NAME
// ============================================================================
// Callback handlers - route events from C++ core to JavaScript
// ============================================================================
override fun onMessage(workerId: String, message: String) {
Log.d(TAG, "[$workerId] Message from worker")
emitOnWorkerMessage(Arguments.createMap().apply {
putString("workerId", workerId)
putString("message", message)
})
}
override fun onError(workerId: String, error: String) {
Log.e(TAG, "[$workerId] Error: $error")
emitOnWorkerError(Arguments.createMap().apply {
putString("workerId", workerId)
putString("error", error)
})
}
override fun onConsole(workerId: String, level: String, message: String) {
Log.d(TAG, "[$workerId] [$level] $message")
emitOnWorkerConsole(Arguments.createMap().apply {
putString("workerId", workerId)
putString("level", level)
putString("message", message)
})
}
override fun onFetch(
workerId: String,
requestId: String,
url: String,
method: String,
headerKeys: Array<String>,
headerValues: Array<String>,
body: ByteArray?,
timeout: Double,
redirect: String
) {
val requestBuilder = Request.Builder()
.url(url)
// Headers
var contentType: MediaType? = null
for (i in headerKeys.indices) {
val key = headerKeys[i]
val value = headerValues[i]
requestBuilder.addHeader(key, value)
if (key.equals("Content-Type", ignoreCase = true)) {
contentType = value.toMediaTypeOrNull()
}
}
// Body
val requestBody = if (body != null && body.isNotEmpty()) {
body.toRequestBody(contentType)
} else if (method.equals("POST", ignoreCase = true) || method.equals("PUT", ignoreCase = true) || method.equals("PATCH", ignoreCase = true)) {
ByteArray(0).toRequestBody(null)
} else {
null
}
requestBuilder.method(method, requestBody)
// Configure client based on options
val requestClient = if (timeout > 0 || redirect != "follow") {
val builder = client.newBuilder()
if (timeout > 0) {
val timeoutMs = timeout.toLong()
builder.callTimeout(timeoutMs, TimeUnit.MILLISECONDS)
builder.readTimeout(timeoutMs, TimeUnit.MILLISECONDS)
builder.connectTimeout(timeoutMs, TimeUnit.MILLISECONDS)
}
if (redirect == "error" || redirect == "manual") {
builder.followRedirects(false)
builder.followSslRedirects(false)
}
builder.build()
} else {
client
}
requestClient.newCall(requestBuilder.build()).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
WebWorkerNative.handleFetchResponse(
workerId, requestId, 0, emptyArray(), emptyArray(), null, e.message
)
}
override fun onResponse(call: Call, response: Response) {
val responseBody = response.body?.bytes()
val headers = response.headers
val keys = mutableListOf<String>()
val values = mutableListOf<String>()
for (i in 0 until headers.size) {
keys.add(headers.name(i))
values.add(headers.value(i))
}
WebWorkerNative.handleFetchResponse(
workerId,
requestId,
response.code,
keys.toTypedArray(),
values.toTypedArray(),
responseBody,
null
)
}
})
}
// ============================================================================
// TurboModule Methods - mirror iOS implementation
// ============================================================================
override fun createWorker(workerId: String, scriptPath: String, promise: Promise) {
try {
val scriptContent = loadScriptFromPath(scriptPath)
val resultId = WebWorkerNative.createWorker(workerId, scriptContent)
promise.resolve(resultId)
} catch (e: Exception) {
Log.e(TAG, "Failed to create worker from path: ${e.message}")
promise.reject("WORKER_ERROR", "Failed to create worker: ${e.message}", e)
}
}
override fun createWorkerWithScript(workerId: String, scriptContent: String, promise: Promise) {
try {
val resultId = WebWorkerNative.createWorker(workerId, scriptContent)
promise.resolve(resultId)
} catch (e: Exception) {
Log.e(TAG, "Failed to create worker: ${e.message}")
promise.reject("WORKER_ERROR", "Failed to create worker: ${e.message}", e)
}
}
override fun terminateWorker(workerId: String, promise: Promise) {
try {
val success = WebWorkerNative.terminateWorker(workerId)
promise.resolve(success)
} catch (e: Exception) {
Log.e(TAG, "Failed to terminate worker: ${e.message}")
promise.reject("WORKER_ERROR", "Failed to terminate worker: ${e.message}", e)
}
}
override fun postMessage(workerId: String, message: String, promise: Promise) {
try {
val success = WebWorkerNative.postMessage(workerId, message)
promise.resolve(success)
} catch (e: Exception) {
Log.e(TAG, "Failed to post message: ${e.message}")
promise.reject("POST_MESSAGE_ERROR", "Failed to post message: ${e.message}", e)
}
}
override fun evalScript(workerId: String, script: String, promise: Promise) {
try {
val result = WebWorkerNative.evalScript(workerId, script)
promise.resolve(result)
} catch (e: Exception) {
Log.e(TAG, "Failed to evaluate script: ${e.message}")
promise.reject("EVAL_ERROR", "Failed to evaluate script: ${e.message}", e)
}
}
// ============================================================================
// Helper methods
// ============================================================================
private fun loadScriptFromPath(scriptPath: String): String {
return try {
val context = reactApplicationContext
if (scriptPath.startsWith("assets://")) {
val assetPath = scriptPath.removePrefix("assets://")
context.assets.open(assetPath).bufferedReader().use { it.readText() }
} else {
java.io.File(scriptPath).readText()
}
} catch (e: Exception) {
throw RuntimeException("Failed to load script from path: $scriptPath", e)
}
}
override fun invalidate() {
super.invalidate()
try {
WebWorkerNative.cleanup()
Log.d(TAG, "WebWorkerModule invalidated and cleaned up")
} catch (e: Exception) {
Log.e(TAG, "Error during cleanup: ${e.message}")
}
}
companion object {
const val NAME = "Webworker"
private const val TAG = "WebworkerModule"
}
}