handle multiple waiters for the same module

This commit is contained in:
Pierre Tachoire
2025-10-17 17:27:33 +02:00
parent c52dce1c48
commit a5dfe8ab28

View File

@@ -326,15 +326,28 @@ pub fn waitForModule(self: *ScriptManager, url: [:0]const u8) !GetResult {
}; };
const sync = entry.value_ptr.*; const sync = entry.value_ptr.*;
// We can have multiple scripts waiting for the same module in concurrency.
// We use the waiters to ensures only the last waiter deinit the resources.
sync.waiters += 1;
defer sync.waiters -= 1;
var client = self.client; var client = self.client;
while (true) { while (true) {
switch (sync.state) { switch (sync.state) {
.loading => {}, .loading => {},
.done => { .done => {
// Our caller has its own higher level cache (caching the if (sync.waiters == 1) {
// actual compiled module). There's no reason for us to keep this // Our caller has its own higher level cache (caching the
defer self.sync_module_pool.destroy(sync); // actual compiled module). There's no reason for us to keep
defer self.sync_modules.removeByPtr(entry.key_ptr); // this if we are the last waiter.
defer self.sync_module_pool.destroy(sync);
defer self.sync_modules.removeByPtr(entry.key_ptr);
return .{
.buffer = sync.buffer,
.buffer_pool = &self.buffer_pool,
};
}
return .{ return .{
.buffer = sync.buffer, .buffer = sync.buffer,
.buffer_pool = &self.buffer_pool, .buffer_pool = &self.buffer_pool,
@@ -882,6 +895,8 @@ const SyncModule = struct {
manager: *ScriptManager, manager: *ScriptManager,
buffer: std.ArrayListUnmanaged(u8) = .{}, buffer: std.ArrayListUnmanaged(u8) = .{},
state: State = .loading, state: State = .loading,
// number of waiters for the module.
waiters: u8 = 0,
const State = union(enum) { const State = union(enum) {
done, done,