Skip to content

Commit

Permalink
fix: race condition when addUniverse called parallel
Browse files Browse the repository at this point in the history
  • Loading branch information
hansSchall committed Nov 24, 2023
1 parent bff3aed commit 3e8d015
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 4 deletions.
2 changes: 1 addition & 1 deletion deno.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"tasks": {
"test": "deno fmt && deno lint && deno check mod.ts && deno test"
"test": "deno fmt && deno lint && deno check mod.ts && deno test --allow-net --unstable"
},
"fmt": {
"indentWidth": 4
Expand Down
27 changes: 27 additions & 0 deletions src/receiver.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/*
* LMGU-Technik sACN-Deno
* Copyright (C) 2023 Hans Schallmoser
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/

import { Receiver } from "../mod.ts";

Deno.test("Add Universe", () => {
using recv = new Receiver();
recv.addUniverse(1);
recv.addUniverse(1);
recv.addUniverse(2);
});
17 changes: 14 additions & 3 deletions src/receiver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,14 +73,20 @@ export class Receiver {
}

// universe => MulticastMembership
private readonly multicast = new Map<number, MulticastV4Membership>();
private readonly multicast = new Map<
number,
MulticastV4Membership | null
>();

// returns true if successful, false if already listening to universe
public async addUniverse(universe: number): Promise<boolean> {
if (this.multicast.has(universe)) {
return false;
}

// prevent race condition when calling multiple times parallel
this.multicast.set(universe, null);

const membership: MulticastV4Membership = await this.socket
.joinMulticastV4(
multicastGroup(universe),
Expand All @@ -92,11 +98,16 @@ export class Receiver {

// returns true if successful, false if not listening to universe
public async removeUniverse(universe: number) {
if (!this.multicast.has(universe)) {
const membership = this.multicast.get(universe);

if (!membership) {
return false;
}

await this.multicast.get(universe)!.leave();
this.multicast.set(universe, null);

await membership!.leave();

this.multicast.delete(universe);
return true;
}
Expand Down

0 comments on commit 3e8d015

Please sign in to comment.