From 65ed53281a5949305d6817eb7032d7fa494b5f53 Mon Sep 17 00:00:00 2001 From: Cory McWilliams Date: Sat, 7 Jun 2025 18:00:05 -0400 Subject: [PATCH] ssb: Shutdown hygiene. #108 --- src/ssb.c | 11 ++++++++++- src/ssb.tests.c | 2 ++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/ssb.c b/src/ssb.c index 624e7c7b..22c4018a 100644 --- a/src/ssb.c +++ b/src/ssb.c @@ -183,6 +183,7 @@ typedef struct _tf_ssb_t sqlite3* db_writer; sqlite3** db_readers; int db_readers_count; + int db_ref_count; uv_loop_t own_loop; uv_loop_t* loop; @@ -2519,6 +2520,7 @@ sqlite3* tf_ssb_acquire_db_reader(tf_ssb_t* ssb) tf_ssb_db_init_reader(db); } tf_trace_sqlite(ssb->trace, db); + ssb->db_ref_count++; uv_mutex_unlock(&ssb->db_readers_lock); sqlite3_set_authorizer(db, NULL, NULL); return db; @@ -2535,10 +2537,17 @@ void tf_ssb_release_db_reader(tf_ssb_t* ssb, sqlite3* db) { sqlite3_db_release_memory(db); uv_mutex_lock(&ssb->db_readers_lock); + ssb->db_ref_count--; + bool destroy = ssb->shutting_down_deferred && ssb->db_ref_count == 0; ssb->db_readers = tf_resize_vec(ssb->db_readers, sizeof(sqlite3*) * (ssb->db_readers_count + 1)); ssb->db_readers[ssb->db_readers_count++] = db; uv_mutex_unlock(&ssb->db_readers_lock); tf_trace_end(ssb->trace); + + if (destroy) + { + tf_ssb_destroy(ssb); + } } sqlite3* tf_ssb_acquire_db_writer(tf_ssb_t* ssb) @@ -2874,7 +2883,7 @@ void tf_ssb_destroy(tf_ssb_t* ssb) } ssb->shutting_down_deferred = true; - if (ssb->connection_ref_count == 0) + if (ssb->connection_ref_count == 0 && ssb->db_ref_count == 0) { uv_mutex_destroy(&ssb->db_readers_lock); uv_mutex_destroy(&ssb->db_writer_lock); diff --git a/src/ssb.tests.c b/src/ssb.tests.c index e356d8d4..ad8abe89 100644 --- a/src/ssb.tests.c +++ b/src/ssb.tests.c @@ -1377,6 +1377,8 @@ void tf_ssb_test_invite(const tf_test_options_t* options) while (count0 != 3 || count1 != 3) { uv_run(&loop, UV_RUN_ONCE); + + tf_printf("count0=%d count1=%d\n", count0, count1); } tf_ssb_set_main_thread(ssb0, false); tf_ssb_set_main_thread(ssb1, false);