Move ssb.getPrivateKey's DB work off the main thread.

This commit is contained in:
Cory McWilliams 2024-06-16 08:07:02 -04:00
parent 991022adfc
commit cb3c7afade

View File

@ -390,17 +390,53 @@ static JSValue _tf_ssb_getIdentities(JSContext* context, JSValueConst this_val,
return result; return result;
} }
typedef struct _get_private_key_t
{
JSContext* context;
JSValue promise[2];
char id[k_id_base64_len];
uint8_t private_key[crypto_sign_SECRETKEYBYTES];
bool got_private_key;
char user[];
} get_private_key_t;
static void _tf_ssb_get_private_key_work(tf_ssb_t* ssb, void* user_data)
{
get_private_key_t* work = user_data;
work->got_private_key = tf_ssb_db_identity_get_private_key(ssb, work->user, work->id, work->private_key, sizeof(work->private_key));
}
static void _tf_ssb_get_private_key_after_work(tf_ssb_t* ssb, int status, void* user_data)
{
get_private_key_t* work = user_data;
JSValue result = JS_UNDEFINED;
JSContext* context = work->context;
if (work->got_private_key)
{
result = tf_util_new_uint8_array(context, work->private_key, sizeof(work->private_key) / 2);
}
JSValue error = JS_Call(context, work->promise[0], JS_UNDEFINED, 1, &result);
JS_FreeValue(context, result);
tf_util_report_error(context, error);
JS_FreeValue(context, error);
JS_FreeValue(context, work->promise[0]);
JS_FreeValue(context, work->promise[1]);
tf_free(work);
}
static JSValue _tf_ssb_getPrivateKey(JSContext* context, JSValueConst this_val, int argc, JSValueConst* argv) static JSValue _tf_ssb_getPrivateKey(JSContext* context, JSValueConst this_val, int argc, JSValueConst* argv)
{ {
JSValue result = JS_UNDEFINED;
tf_ssb_t* ssb = JS_GetOpaque(this_val, _tf_ssb_classId); tf_ssb_t* ssb = JS_GetOpaque(this_val, _tf_ssb_classId);
const char* user = JS_ToCString(context, argv[0]); size_t user_length = 0;
const char* user = JS_ToCStringLen(context, &user_length, argv[0]);
const char* id = JS_ToCString(context, argv[1]); const char* id = JS_ToCString(context, argv[1]);
uint8_t private_key[crypto_sign_SECRETKEYBYTES]; get_private_key_t* work = tf_malloc(sizeof(get_private_key_t) + user_length + 1);
if (tf_ssb_db_identity_get_private_key(ssb, user, id, private_key, sizeof(private_key))) *work = (get_private_key_t) { .context = context };
{ memcpy(work->user, user, user_length + 1);
result = tf_util_new_uint8_array(context, private_key, sizeof(private_key) / 2); snprintf(work->id, sizeof(work->id), "%s", id);
} JSValue result = JS_NewPromiseCapability(context, work->promise);
tf_ssb_run_work(ssb, _tf_ssb_get_private_key_work, _tf_ssb_get_private_key_after_work, work);
JS_FreeCString(context, user); JS_FreeCString(context, user);
JS_FreeCString(context, id); JS_FreeCString(context, id);
return result; return result;