Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/bright-pandas-lock.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@elgato/utils": patch
---

Added `Mutex` class for mutual exclusion, ensuring only one asynchronous operation can access a protected resource at a time.
5 changes: 5 additions & 0 deletions .changeset/smooth-foxes-run.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@elgato/streamdeck": minor
---

Added `setSettings` overload that accepts an update function, allowing settings to be modified based on the current value.
107 changes: 107 additions & 0 deletions packages/plugin/src/plugin/actions/__tests__/action.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,7 @@ describe("Action", () => {

expect(action.isKey()).toBe(true);
expect(action.isDial()).toBe(false);
expect(action.isNeoInfobar()).toBe(false);
});

/**
Expand Down Expand Up @@ -324,6 +325,112 @@ describe("Action", () => {
});
});

/**
* Asserts {@link ActionBase.setSettings} with a synchronous update function uses cached settings and sends updated settings.
*/
it("setSettings with sync update function", async () => {
// Arrange.
const action = new ActionBase(source);
settingsCache.set(action.id, { name: "Original" });

// Act.
await action.setSettings((current) => ({
...current,
name: `${current.name} Updated`,
}));

// Assert (only setSettings command sent, getSettings used cache).
expect(connection.send).toHaveBeenCalledTimes(1);
expect(connection.send).toHaveBeenLastCalledWith<[SetSettings]>({
context: action.id,
event: "setSettings",
payload: { name: "Original Updated" },
});
});

/**
* Asserts {@link ActionBase.setSettings} with an async update function uses cached settings and sends updated settings.
*/
it("setSettings with async update function", async () => {
// Arrange.
const action = new ActionBase(source);
settingsCache.set(action.id, { name: "Current" });

// Act.
await action.setSettings(async (current) => {
await Promise.resolve(); // Simulate async work.
return {
...current,
name: `${current.name} Async`,
};
});

// Assert (only setSettings command sent, getSettings used cache).
expect(connection.send).toHaveBeenCalledTimes(1);
expect(connection.send).toHaveBeenLastCalledWith<[SetSettings]>({
context: action.id,
event: "setSettings",
payload: { name: "Current Async" },
});
});

/**
* Asserts {@link ActionBase.setSettings} with an update function invalidates the settings cache.
*/
it("setSettings with update function invalidates cache", async () => {
// Arrange.
const action = new ActionBase(source);
settingsCache.set(action.id, { name: "Cached" });

// Act.
await action.setSettings((current) => ({
...current,
name: "Updated via function",
}));

// Assert.
expect(settingsCache.get(action.id)).toBeUndefined();
});

/**
* Asserts {@link ActionBase.setSettings} with concurrent update functions serializes updates correctly.
*/
it("setSettings with concurrent update functions serializes updates", async () => {
// Arrange.
const action = new ActionBase(source);
const callOrder: number[] = [];
let callCount = 0;

// Mock send to track call order and repopulate cache to simulate Stream Deck response.
vi.mocked(connection.send).mockImplementation(async (msg) => {
if (msg.event === "setSettings") {
callOrder.push(++callCount);
// Simulate Stream Deck updating the cache with the new settings.
settingsCache.set(action.id, msg.payload as JsonObject);
}
});

settingsCache.set(action.id, { count: 0 });

// Act - two concurrent increments should both succeed sequentially.
await Promise.all([
action.setSettings((current) => ({ count: (current as { count: number }).count + 1 })),
action.setSettings((current) => ({ count: (current as { count: number }).count + 1 })),
]);

// Assert - both updates should have been serialized (mutex ensures sequential execution).
expect(connection.send).toHaveBeenCalledTimes(2);
expect(callOrder).toEqual([1, 2]); // Sequential, not interleaved.

// Verify the payloads show incremental values (0→1 then 1→2), not both 0→1.
const calls = vi.mocked(connection.send).mock.calls;
const payloads = calls
.filter((call) => call[0].event === "setSettings")
.map((call) => (call[0] as SetSettings).payload);

expect(payloads).toEqual([{ count: 1 }, { count: 2 }]);
});

/**
* Asserts {@link ActionBase.showAlert} forwards the command to the {@link connection}.
*/
Expand Down
39 changes: 33 additions & 6 deletions packages/plugin/src/plugin/actions/action-base.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { type EventArgs, type JsonObject, withResolvers } from "@elgato/utils";
import { type EventArgs, type JsonObject, Mutex, withResolvers } from "@elgato/utils";
import { randomUUID } from "node:crypto";

import type {
Expand All @@ -21,6 +21,8 @@ import type { NeoInfobarAction } from "./neo-infobar.js";

const REQUEST_TIMEOUT = 15 * 1000; // 15s

const setSettingsMutex = new Mutex();

/**
* Provides a contextualized instance of an action, allowing for direct communication with the Stream Deck.
* @template TSettings The type of settings associated with the action.
Expand Down Expand Up @@ -114,15 +116,40 @@ export class ActionBase<TSettings extends JsonObject> extends ActionContext {

/**
* Sets the settings associated with this action instance.
* @param value Settings to persist.
* @returns `Promise` resolved when the settings are sent to Stream Deck.
* @param settings The new settings.
* @returns Promise that resolves when the settings are updated.
*/
public setSettings(settings: TSettings): Promise<void>;
/**
* Sets the settings associated with this action instance.
* @param update Function used to update the current settings.
* @returns Promise that resolves when the settings are updated.
*/
public setSettings(value: TSettings): Promise<void> {
public setSettings(update: (current: TSettings) => Promise<TSettings> | TSettings): Promise<void>;
/**
* Sets the settings associated with this action instance.
* @param settingsOrUpdate The new settings or function used to update the current settings.
* @returns Promise that resolves when the settings are updated.
*/
public async setSettings(
settingsOrUpdate: TSettings | ((current: TSettings) => Promise<TSettings> | TSettings),
): Promise<void> {
if (typeof settingsOrUpdate === "function") {
await setSettingsMutex.run(async () => {
const currSettings = await this.getSettings();
const newSettings = await settingsOrUpdate(currSettings);

await this.setSettings(newSettings);
});

return;
}

settingsCache.delete(this.id);
return connection.send({
await connection.send({
event: "setSettings",
context: this.id,
payload: value,
payload: settingsOrUpdate,
});
}

Expand Down
23 changes: 23 additions & 0 deletions packages/utils/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,29 @@ const lazy = new Lazy(() => "Hello world");
lazy.value; // "Hello world";
```

### `Mutex`

A mutual exclusion lock that ensures only one asynchronous operation can access a protected resource at a time.

```ts
import { Mutex } from "@elgato/utils";

const mutex = new Mutex();

// Using run (recommended)
await mutex.run(async () => {
await updateSharedResource();
});

// Using wait and release
await mutex.wait();
try {
await updateSharedResource();
} finally {
mutex.release();
}
```

## Objects

### `get(source, path)`
Expand Down
Loading
Loading