Execute oxfmt (#1166)

Ran
pnpm oxfmt .

This should get the web repo aligned so that we can better enforce oxfmt going forward.
This commit is contained in:
Austin
2026-06-16 20:30:08 -04:00
committed by GitHub
parent c5690d1edb
commit d2cb51d489
378 changed files with 5548 additions and 1974 deletions
@@ -23,7 +23,11 @@ describe("ChannelsClient", () => {
);
expect(client.channels.list.value.length).toBe(2);
expect(client.channels.get(0)?.role).toBe(Protobuf.Channel.Channel_Role.PRIMARY);
expect(client.channels.get(1)?.role).toBe(Protobuf.Channel.Channel_Role.SECONDARY);
expect(client.channels.get(0)?.role).toBe(
Protobuf.Channel.Channel_Role.PRIMARY,
);
expect(client.channels.get(1)?.role).toBe(
Protobuf.Channel.Channel_Role.SECONDARY,
);
});
});
@@ -2,7 +2,11 @@ import type * as Protobuf from "@meshtastic/protobufs";
import type { ResultType } from "better-result";
import type { MeshClient } from "../../core/client/MeshClient.ts";
import type { ReadonlySignal } from "../../core/signals/createStore.ts";
import { clearChannel, getChannel, setChannel } from "./application/ChannelUseCases.ts";
import {
clearChannel,
getChannel,
setChannel,
} from "./application/ChannelUseCases.ts";
import type { Channel } from "./domain/Channel.ts";
import { ChannelMapper } from "./infrastructure/ChannelMapper.ts";
import { ChannelsStore } from "./state/channelsStore.ts";
@@ -26,7 +30,9 @@ export class ChannelsClient {
return this.store.get(index);
}
public set(channel: Protobuf.Channel.Channel): Promise<ResultType<number, Error>> {
public set(
channel: Protobuf.Channel.Channel,
): Promise<ResultType<number, Error>> {
return setChannel(this.client, channel);
}
@@ -10,7 +10,10 @@ export async function setChannel(
channel: Protobuf.Channel.Channel,
): Promise<ResultType<number, Error>> {
try {
const id = await sendAdminMessage(client, { case: "setChannel", value: channel });
const id = await sendAdminMessage(client, {
case: "setChannel",
value: channel,
});
return Result.ok(id);
} catch (e) {
return Result.err(e instanceof Error ? e : new Error(String(e)));
@@ -22,7 +25,10 @@ export async function getChannel(
index: number,
): Promise<ResultType<number, Error>> {
try {
const id = await sendAdminMessage(client, { case: "getChannelRequest", value: index + 1 });
const id = await sendAdminMessage(client, {
case: "getChannelRequest",
value: index + 1,
});
return Result.ok(id);
} catch (e) {
return Result.err(e instanceof Error ? e : new Error(String(e)));
@@ -36,10 +36,16 @@ describe("ChatClient drafts", () => {
const { transport } = createFakeTransport();
const client = new MeshClient({ transport, chat: { draftRepository } });
client.chat.drafts.set({ kind: "channel", channel: ChannelNumber.Primary }, "hello");
await new Promise((r) => setTimeout(r, 5));
expect(await draftRepository.load({ kind: "channel", channel: ChannelNumber.Primary })).toBe(
client.chat.drafts.set(
{ kind: "channel", channel: ChannelNumber.Primary },
"hello",
);
await new Promise((r) => setTimeout(r, 5));
expect(
await draftRepository.load({
kind: "channel",
channel: ChannelNumber.Primary,
}),
).toBe("hello");
});
});
@@ -22,7 +22,10 @@ function seedMessage(id: number, ms: number, text: string): Message {
describe("ChatClient persistence", () => {
it("hydrates messages from the repository on first subscription", async () => {
const repository = new InMemoryMessageRepository();
await repository.appendBatch([seedMessage(1, 1000, "first"), seedMessage(2, 2000, "second")]);
await repository.appendBatch([
seedMessage(1, 1000, "first"),
seedMessage(2, 2000, "second"),
]);
const { transport } = createFakeTransport();
const client = new MeshClient({
@@ -60,7 +63,11 @@ describe("ChatClient persistence", () => {
new Date(3000),
50,
);
expect(sig.value.map((m) => m.text)).toEqual(["oldest", "middle", "newest"]);
expect(sig.value.map((m) => m.text)).toEqual([
"oldest",
"middle",
"newest",
]);
});
it("persists inbound messages through the repository", async () => {
@@ -14,9 +14,13 @@ type SendResult = ResultType<number, SendTextError>;
* for us, so this helper polls the queue and acks any pending items
* until the send promise settles.
*/
async function withAckFlush<T>(client: MeshClient, run: () => Promise<T>): Promise<T> {
async function withAckFlush<T>(
client: MeshClient,
run: () => Promise<T>,
): Promise<T> {
const flush = setInterval(() => {
for (const item of client.queue.getState()) client.queue.processAck(item.id);
for (const item of client.queue.getState())
client.queue.processAck(item.id);
}, 5);
try {
return await run();
@@ -112,7 +116,8 @@ describe("ChatClient.send optimistic append", () => {
expect(messages.value[0]!.state).toBe(MessageState.Pending);
// Now drain the queue so the test doesn't dangle.
for (const item of client.queue.getState()) client.queue.processAck(item.id);
for (const item of client.queue.getState())
client.queue.processAck(item.id);
await sendPromise;
});
+40 -11
View File
@@ -3,7 +3,10 @@ import type { ResultType } from "better-result";
import type { MeshClient } from "../../core/client/MeshClient.ts";
import { Constants } from "../../core/constants/index.ts";
import { generatePacketId } from "../../core/identifiers/PacketId.ts";
import { type ReadonlySignal, toReadonly } from "../../core/signals/createStore.ts";
import {
type ReadonlySignal,
toReadonly,
} from "../../core/signals/createStore.ts";
import type { ChannelNumber } from "../../core/types.ts";
import type { DraftRepository } from "./domain/DraftRepository.ts";
import type { Message } from "./domain/Message.ts";
@@ -16,7 +19,11 @@ import { MessageState } from "./domain/MessageState.ts";
import { MessageMapper } from "./infrastructure/MessageMapper.ts";
import { InMemoryDraftRepository } from "./infrastructure/repositories/InMemoryDraftRepository.ts";
import { InMemoryMessageRepository } from "./infrastructure/repositories/InMemoryMessageRepository.ts";
import { type SendTextError, type SendTextInput, sendText } from "./application/SendTextUseCase.ts";
import {
type SendTextError,
type SendTextInput,
sendText,
} from "./application/SendTextUseCase.ts";
import { ChatStore } from "./state/chatStore.ts";
import { DraftStore } from "./state/draftStore.ts";
@@ -80,7 +87,8 @@ export class ChatClient {
this.store = new ChatStore();
this.draftStore = new DraftStore();
this.repository = options.repository ?? new InMemoryMessageRepository();
this.draftRepository = options.draftRepository ?? new InMemoryDraftRepository();
this.draftRepository =
options.draftRepository ?? new InMemoryDraftRepository();
this.retention = options.retention;
this.initialLoadLimit = options.initialLoadLimit ?? 50;
@@ -101,7 +109,10 @@ export class ChatClient {
const message = MessageMapper.fromPacket(packet);
const conv: ConversationKey =
packet.type === "direct" && packet.to !== Constants.broadcastNum
? { kind: "direct", peer: packet.from === client.myNodeNum ? packet.to : packet.from }
? {
kind: "direct",
peer: packet.from === client.myNodeNum ? packet.to : packet.from,
}
: { kind: "channel", channel: packet.channel };
const key = this.keyFor(conv);
@@ -121,7 +132,10 @@ export class ChatClient {
client.events.onRoutingPacket.subscribe((packet) => {
if (packet.data.variant.case === "errorReason") {
const state = packet.data.variant.value === 0 ? MessageState.Ack : MessageState.Failed;
const state =
packet.data.variant.value === 0
? MessageState.Ack
: MessageState.Failed;
this.store.updateState(packet.id, state);
void this.repository.updateState(packet.id, state).catch(() => {});
}
@@ -138,10 +152,15 @@ export class ChatClient {
return this.store.messagesForDirect(peer);
}
public async loadOlder(conv: ConversationKey, before: Date, limit = 50): Promise<Message[]> {
public async loadOlder(
conv: ConversationKey,
before: Date,
limit = 50,
): Promise<Message[]> {
const older = await this.repository.loadBefore(conv, before, limit);
const key = this.keyFor(conv);
for (let i = older.length - 1; i >= 0; i--) this.store.prepend(key, older[i]!);
for (let i = older.length - 1; i >= 0; i--)
this.store.prepend(key, older[i]!);
return older;
}
@@ -174,7 +193,9 @@ export class ChatClient {
}
}
public async send(input: SendTextInput): Promise<ResultType<number, SendTextError>> {
public async send(
input: SendTextInput,
): Promise<ResultType<number, SendTextError>> {
const conv: ConversationKey =
typeof input.destination === "number"
? { kind: "direct", peer: input.destination }
@@ -196,7 +217,10 @@ export class ChatClient {
const message: Message = {
id: packetId,
from: this.client.myNodeNum,
to: typeof input.destination === "number" ? input.destination : Constants.broadcastNum,
to:
typeof input.destination === "number"
? input.destination
: Constants.broadcastNum,
channel: input.channel ?? 0,
rxTime: new Date(),
type: typeof input.destination === "number" ? "direct" : "broadcast",
@@ -216,7 +240,9 @@ export class ChatClient {
// the optimistic message visible but mark it Failed so the user
// sees the error state next to their bubble.
this.store.updateState(packetId, MessageState.Failed);
void this.repository.updateState(packetId, MessageState.Failed).catch(() => {});
void this.repository
.updateState(packetId, MessageState.Failed)
.catch(() => {});
}
return result;
}
@@ -227,7 +253,10 @@ export class ChatClient {
this.hydrated.add(key);
void (async () => {
try {
const recent = await this.repository.loadRecent(conv, this.initialLoadLimit);
const recent = await this.repository.loadRecent(
conv,
this.initialLoadLimit,
);
for (const m of recent) this.store.append(key, m);
} catch {
// adapter may not have history yet; safe to ignore
@@ -41,7 +41,10 @@ describe("ChatClient unread counts", () => {
const client = new MeshClient({ transport });
expect(client.chat.unread.total.value).toBe(0);
expect(
client.chat.unread.count({ kind: "channel", channel: ChannelNumber.Primary }).value,
client.chat.unread.count({
kind: "channel",
channel: ChannelNumber.Primary,
}).value,
).toBe(0);
});
@@ -54,11 +57,17 @@ describe("ChatClient unread counts", () => {
dispatchInbound(client, { from: 200, ms: 2000 });
expect(
client.chat.unread.count({ kind: "channel", channel: ChannelNumber.Primary }).value,
client.chat.unread.count({
kind: "channel",
channel: ChannelNumber.Primary,
}).value,
).toBe(2);
expect(client.chat.unread.total.value).toBe(2);
client.chat.unread.markRead({ kind: "channel", channel: ChannelNumber.Primary });
client.chat.unread.markRead({
kind: "channel",
channel: ChannelNumber.Primary,
});
expect(client.chat.unread.total.value).toBe(0);
});
@@ -76,10 +85,20 @@ describe("ChatClient unread counts", () => {
const client = new MeshClient({ transport });
setMyNode(client);
dispatchInbound(client, { from: 50, to: MY_NODE, type: "direct", ms: 1000 });
expect(client.chat.unread.count({ kind: "direct", peer: 50 }).value).toBe(1);
dispatchInbound(client, {
from: 50,
to: MY_NODE,
type: "direct",
ms: 1000,
});
expect(client.chat.unread.count({ kind: "direct", peer: 50 }).value).toBe(
1,
);
expect(
client.chat.unread.count({ kind: "channel", channel: ChannelNumber.Primary }).value,
client.chat.unread.count({
kind: "channel",
channel: ChannelNumber.Primary,
}).value,
).toBe(0);
});
});
@@ -1,6 +1,10 @@
import { Result } from "better-result";
import { describe, expect, it, vi } from "vitest";
import { EmptyMessageError, MessageTooLongError, sendText } from "./SendTextUseCase.ts";
import {
EmptyMessageError,
MessageTooLongError,
sendText,
} from "./SendTextUseCase.ts";
import type { MeshClient } from "../../../core/client/MeshClient.ts";
function makeClient(sendPacket = vi.fn().mockResolvedValue(123)) {
@@ -2,7 +2,11 @@ import * as Protobuf from "@meshtastic/protobufs";
import { Result } from "better-result";
import type { ResultType } from "better-result";
import type { MeshClient } from "../../../core/client/MeshClient.ts";
import { ChannelNumber, type Destination, Emitter } from "../../../core/types.ts";
import {
ChannelNumber,
type Destination,
Emitter,
} from "../../../core/types.ts";
export interface SendTextInput {
text: string;
@@ -30,7 +34,9 @@ export class EmptyMessageError extends Error {
export class MessageTooLongError extends Error {
readonly _tag = "MessageTooLongError";
constructor(readonly byteLength: number) {
super(`Message text encodes to ${byteLength} bytes; max payload is ~228 bytes`);
super(
`Message text encodes to ${byteLength} bytes; max payload is ~228 bytes`,
);
this.name = "MessageTooLongError";
}
}
@@ -4,7 +4,11 @@ import { Result } from "better-result";
import type { ResultType } from "better-result";
import type { MeshClient } from "../../../core/client/MeshClient.ts";
import { generatePacketId } from "../../../core/identifiers/PacketId.ts";
import { ChannelNumber, type Destination, Emitter } from "../../../core/types.ts";
import {
ChannelNumber,
type Destination,
Emitter,
} from "../../../core/types.ts";
export async function sendWaypoint(
client: MeshClient,
@@ -26,7 +26,11 @@ export interface RetentionPolicy {
*/
export interface MessageRepository {
loadRecent(key: ConversationKey, limit: number): Promise<Message[]>;
loadBefore(key: ConversationKey, cursor: Date, limit: number): Promise<Message[]>;
loadBefore(
key: ConversationKey,
cursor: Date,
limit: number,
): Promise<Message[]>;
append(message: Message): Promise<void>;
appendBatch(messages: ReadonlyArray<Message>): Promise<void>;
updateState(id: number, state: MessageState): Promise<void>;
@@ -38,5 +42,7 @@ export interface MessageRepository {
}
export function conversationKeyString(key: ConversationKey): string {
return key.kind === "channel" ? `channel:${key.channel}` : `direct:${key.peer}`;
return key.kind === "channel"
? `channel:${key.channel}`
: `direct:${key.peer}`;
}
+5 -1
View File
@@ -1,5 +1,9 @@
export { ChatClient } from "./ChatClient.ts";
export type { ChatClientOptions, ChatDrafts, ChatUnread } from "./ChatClient.ts";
export type {
ChatClientOptions,
ChatDrafts,
ChatUnread,
} from "./ChatClient.ts";
export type { DraftRepository } from "./domain/DraftRepository.ts";
export { InMemoryDraftRepository } from "./infrastructure/repositories/InMemoryDraftRepository.ts";
export type { Message } from "./domain/Message.ts";
@@ -3,7 +3,10 @@ import type { Message } from "../domain/Message.ts";
import { MessageState } from "../domain/MessageState.ts";
export const MessageMapper = {
fromPacket(packet: PacketMetadata<string>, state: MessageState = MessageState.Ack): Message {
fromPacket(
packet: PacketMetadata<string>,
state: MessageState = MessageState.Ack,
): Message {
return {
id: packet.id,
from: packet.from,
@@ -1,8 +1,14 @@
import { type ConversationKey, conversationKeyString } from "../../domain/MessageRepository.ts";
import {
type ConversationKey,
conversationKeyString,
} from "../../domain/MessageRepository.ts";
import type { DraftRepository } from "../../domain/DraftRepository.ts";
export class InMemoryDraftRepository implements DraftRepository {
private readonly map = new Map<string, { key: ConversationKey; text: string }>();
private readonly map = new Map<
string,
{ key: ConversationKey; text: string }
>();
async load(key: ConversationKey): Promise<string> {
return this.map.get(conversationKeyString(key))?.text ?? "";
@@ -20,7 +26,9 @@ export class InMemoryDraftRepository implements DraftRepository {
this.map.delete(conversationKeyString(key));
}
async loadAll(): Promise<ReadonlyArray<{ key: ConversationKey; text: string }>> {
async loadAll(): Promise<
ReadonlyArray<{ key: ConversationKey; text: string }>
> {
return Array.from(this.map.values());
}
}
@@ -21,13 +21,21 @@ describe("InMemoryMessageRepository", () => {
it("loadRecent returns the tail of a bucket", async () => {
const repo = new InMemoryMessageRepository();
await repo.appendBatch([msg(1, 1000), msg(2, 2000), msg(3, 3000)]);
const out = await repo.loadRecent({ kind: "channel", channel: ChannelNumber.Primary }, 2);
const out = await repo.loadRecent(
{ kind: "channel", channel: ChannelNumber.Primary },
2,
);
expect(out.map((m) => m.id)).toEqual([2, 3]);
});
it("loadBefore paginates older messages", async () => {
const repo = new InMemoryMessageRepository();
await repo.appendBatch([msg(1, 1000), msg(2, 2000), msg(3, 3000), msg(4, 4000)]);
await repo.appendBatch([
msg(1, 1000),
msg(2, 2000),
msg(3, 3000),
msg(4, 4000),
]);
const out = await repo.loadBefore(
{ kind: "channel", channel: ChannelNumber.Primary },
new Date(3000),
@@ -40,24 +48,41 @@ describe("InMemoryMessageRepository", () => {
const repo = new InMemoryMessageRepository();
await repo.append(msg(42, 1000));
await repo.updateState(42, MessageState.Failed);
const [found] = await repo.loadRecent({ kind: "channel", channel: ChannelNumber.Primary }, 1);
const [found] = await repo.loadRecent(
{ kind: "channel", channel: ChannelNumber.Primary },
1,
);
expect(found?.state).toBe(MessageState.Failed);
});
it("prune enforces maxPerBucket", async () => {
const repo = new InMemoryMessageRepository();
await repo.appendBatch([msg(1, 1000), msg(2, 2000), msg(3, 3000), msg(4, 4000)]);
await repo.appendBatch([
msg(1, 1000),
msg(2, 2000),
msg(3, 3000),
msg(4, 4000),
]);
await repo.prune({ maxPerBucket: 2 });
const out = await repo.loadRecent({ kind: "channel", channel: ChannelNumber.Primary }, 10);
const out = await repo.loadRecent(
{ kind: "channel", channel: ChannelNumber.Primary },
10,
);
expect(out.map((m) => m.id)).toEqual([3, 4]);
});
it("prune enforces olderThanMs", async () => {
const repo = new InMemoryMessageRepository();
const now = Date.now();
await repo.appendBatch([msg(1, now - 1000 * 60 * 60 * 24 * 10), msg(2, now)]);
await repo.appendBatch([
msg(1, now - 1000 * 60 * 60 * 24 * 10),
msg(2, now),
]);
await repo.prune({ olderThanMs: 1000 * 60 * 60 * 24 });
const out = await repo.loadRecent({ kind: "channel", channel: ChannelNumber.Primary }, 10);
const out = await repo.loadRecent(
{ kind: "channel", channel: ChannelNumber.Primary },
10,
);
expect(out.map((m) => m.id)).toEqual([2]);
});
});
@@ -19,7 +19,11 @@ export class InMemoryMessageRepository implements MessageRepository {
return bucket.slice(-limit);
}
async loadBefore(key: ConversationKey, cursor: Date, limit: number): Promise<Message[]> {
async loadBefore(
key: ConversationKey,
cursor: Date,
limit: number,
): Promise<Message[]> {
const bucket = this.buckets.get(conversationKeyString(key)) ?? [];
const idx = bucket.findIndex((m) => m.rxTime >= cursor);
const end = idx === -1 ? bucket.length : idx;
@@ -59,8 +63,13 @@ export class InMemoryMessageRepository implements MessageRepository {
let filtered =
policy.olderThanMs === undefined
? bucket
: bucket.filter((m) => nowMs - m.rxTime.getTime() <= policy.olderThanMs!);
if (policy.maxPerBucket !== undefined && filtered.length > policy.maxPerBucket) {
: bucket.filter(
(m) => nowMs - m.rxTime.getTime() <= policy.olderThanMs!,
);
if (
policy.maxPerBucket !== undefined &&
filtered.length > policy.maxPerBucket
) {
filtered = filtered.slice(-policy.maxPerBucket);
}
this.buckets.set(key, filtered);
@@ -1,6 +1,12 @@
import { type Signal, signal } from "@preact/signals-core";
import { type ReadonlySignal, toReadonly } from "../../../core/signals/createStore.ts";
import { type ConversationKey, conversationKeyString } from "../domain/MessageRepository.ts";
import {
type ReadonlySignal,
toReadonly,
} from "../../../core/signals/createStore.ts";
import {
type ConversationKey,
conversationKeyString,
} from "../domain/MessageRepository.ts";
/**
* Per-conversation draft text exposed as readonly signals. Lazy creation:
@@ -2,7 +2,10 @@ import * as Protobuf from "@meshtastic/protobufs";
import { computed } from "@preact/signals-core";
import type { ResultType } from "better-result";
import type { MeshClient } from "../../core/client/MeshClient.ts";
import { type ReadonlySignal, toReadonly } from "../../core/signals/createStore.ts";
import {
type ReadonlySignal,
toReadonly,
} from "../../core/signals/createStore.ts";
import {
beginEditSettings,
commitEditSettings,
@@ -45,12 +48,17 @@ export class ConfigClient {
computed(() => {
const lora = this.store.radio.write.value.lora;
if (!lora) return false;
return lora.region === Protobuf.Config.Config_LoRaConfig_RegionCode.UNSET;
return (
lora.region === Protobuf.Config.Config_LoRaConfig_RegionCode.UNSET
);
}),
);
client.events.onConfigPacket.subscribe((config) => {
this.store.radio.write.value = ConfigMapper.mergeRadio(this.store.radio.write.value, config);
this.store.radio.write.value = ConfigMapper.mergeRadio(
this.store.radio.write.value,
config,
);
});
client.events.onModuleConfigPacket.subscribe((moduleConfig) => {
this.store.modules.write.value = ConfigMapper.mergeModule(
@@ -68,7 +76,9 @@ export class ConfigClient {
return commitEditSettings(this.client);
}
public setRadio(config: Protobuf.Config.Config): Promise<ResultType<number, Error>> {
public setRadio(
config: Protobuf.Config.Config,
): Promise<ResultType<number, Error>> {
return setConfig(this.client, config);
}
@@ -18,7 +18,9 @@ function mqttPacket(enabled: boolean): Protobuf.ModuleConfig.ModuleConfig {
return create(Protobuf.ModuleConfig.ModuleConfigSchema, {
payloadVariant: {
case: "mqtt",
value: create(Protobuf.ModuleConfig.ModuleConfig_MQTTConfigSchema, { enabled }),
value: create(Protobuf.ModuleConfig.ModuleConfig_MQTTConfigSchema, {
enabled,
}),
},
});
}
@@ -43,7 +45,10 @@ describe("ConfigEditor", () => {
expect(editor.isDirty.value).toBe(false);
expect(editor.radio.value.lora?.region).toBe(4);
editor.setRadioSection("lora", create(Protobuf.Config.Config_LoRaConfigSchema, { region: 7 }));
editor.setRadioSection(
"lora",
create(Protobuf.Config.Config_LoRaConfigSchema, { region: 7 }),
);
expect(editor.isDirty.value).toBe(true);
expect(editor.dirtyRadioSections.value).toEqual(["lora"]);
});
@@ -58,7 +63,9 @@ describe("ConfigEditor", () => {
editor.setModuleSection(
"mqtt",
create(Protobuf.ModuleConfig.ModuleConfig_MQTTConfigSchema, { enabled: true }),
create(Protobuf.ModuleConfig.ModuleConfig_MQTTConfigSchema, {
enabled: true,
}),
);
expect(editor.dirtyModuleSections.value).toEqual(["mqtt"]);
@@ -73,7 +80,10 @@ describe("ConfigEditor", () => {
const editor = client.config.editor;
client.events.onConfigPacket.dispatch(loraPacket(4));
editor.setRadioSection("lora", create(Protobuf.Config.Config_LoRaConfigSchema, { region: 7 }));
editor.setRadioSection(
"lora",
create(Protobuf.Config.Config_LoRaConfigSchema, { region: 7 }),
);
expect(editor.isDirty.value).toBe(true);
editor.reset();
@@ -88,7 +98,10 @@ describe("ConfigEditor", () => {
// User edits lora region
client.events.onConfigPacket.dispatch(loraPacket(4));
editor.setRadioSection("lora", create(Protobuf.Config.Config_LoRaConfigSchema, { region: 7 }));
editor.setRadioSection(
"lora",
create(Protobuf.Config.Config_LoRaConfigSchema, { region: 7 }),
);
// Device pushes a baseline change for the same section while user is editing
client.events.onConfigPacket.dispatch(loraPacket(8));
@@ -104,7 +117,10 @@ describe("ConfigEditor", () => {
const editor = client.config.editor;
client.events.onConfigPacket.dispatch(loraPacket(4));
editor.setRadioSection("lora", create(Protobuf.Config.Config_LoRaConfigSchema, { region: 7 }));
editor.setRadioSection(
"lora",
create(Protobuf.Config.Config_LoRaConfigSchema, { region: 7 }),
);
expect(editor.isDirty.value).toBe(true);
client.events.onDeviceStatus.dispatch(DeviceStatusEnum.DeviceDisconnected);
@@ -4,20 +4,30 @@ import type { ResultType } from "better-result";
import type { MeshClient } from "../../../core/client/MeshClient.ts";
import { sendAdminMessage } from "../../device/infrastructure/AdminMessageSender.ts";
export async function beginEditSettings(client: MeshClient): Promise<ResultType<number, Error>> {
export async function beginEditSettings(
client: MeshClient,
): Promise<ResultType<number, Error>> {
client.events.onPendingSettingsChange.dispatch(true);
try {
const id = await sendAdminMessage(client, { case: "beginEditSettings", value: true });
const id = await sendAdminMessage(client, {
case: "beginEditSettings",
value: true,
});
return Result.ok(id);
} catch (e) {
return Result.err(e instanceof Error ? e : new Error(String(e)));
}
}
export async function commitEditSettings(client: MeshClient): Promise<ResultType<number, Error>> {
export async function commitEditSettings(
client: MeshClient,
): Promise<ResultType<number, Error>> {
client.events.onPendingSettingsChange.dispatch(false);
try {
const id = await sendAdminMessage(client, { case: "commitEditSettings", value: true });
const id = await sendAdminMessage(client, {
case: "commitEditSettings",
value: true,
});
return Result.ok(id);
} catch (e) {
return Result.err(e instanceof Error ? e : new Error(String(e)));
@@ -29,7 +39,10 @@ export async function setConfig(
config: Protobuf.Config.Config,
): Promise<ResultType<number, Error>> {
try {
const id = await sendAdminMessage(client, { case: "setConfig", value: config });
const id = await sendAdminMessage(client, {
case: "setConfig",
value: config,
});
return Result.ok(id);
} catch (e) {
return Result.err(e instanceof Error ? e : new Error(String(e)));
@@ -41,7 +54,10 @@ export async function getConfig(
type: Protobuf.Admin.AdminMessage_ConfigType,
): Promise<ResultType<number, Error>> {
try {
const id = await sendAdminMessage(client, { case: "getConfigRequest", value: type });
const id = await sendAdminMessage(client, {
case: "getConfigRequest",
value: type,
});
return Result.ok(id);
} catch (e) {
return Result.err(e instanceof Error ? e : new Error(String(e)));
@@ -53,7 +69,10 @@ export async function setModuleConfig(
moduleConfig: Protobuf.ModuleConfig.ModuleConfig,
): Promise<ResultType<number, Error>> {
try {
const id = await sendAdminMessage(client, { case: "setModuleConfig", value: moduleConfig });
const id = await sendAdminMessage(client, {
case: "setModuleConfig",
value: moduleConfig,
});
return Result.ok(id);
} catch (e) {
return Result.err(e instanceof Error ? e : new Error(String(e)));
@@ -65,7 +84,10 @@ export async function getModuleConfig(
type: Protobuf.Admin.AdminMessage_ModuleConfigType,
): Promise<ResultType<number, Error>> {
try {
const id = await sendAdminMessage(client, { case: "getModuleConfigRequest", value: type });
const id = await sendAdminMessage(client, {
case: "getModuleConfigRequest",
value: type,
});
return Result.ok(id);
} catch (e) {
return Result.err(e instanceof Error ? e : new Error(String(e)));
@@ -4,7 +4,10 @@ import { signal } from "@preact/signals-core";
import { Result } from "better-result";
import type { ResultType } from "better-result";
import type { MeshClient } from "../../../core/client/MeshClient.ts";
import { type ReadonlySignal, toReadonly } from "../../../core/signals/createStore.ts";
import {
type ReadonlySignal,
toReadonly,
} from "../../../core/signals/createStore.ts";
import { setChannel } from "../../channels/application/ChannelUseCases.ts";
import { DeviceStatusEnum } from "../../device/domain/DeviceStatus.ts";
import { sendAdminMessage } from "../../device/infrastructure/AdminMessageSender.ts";
@@ -39,40 +42,56 @@ export class ConfigEditor {
private readonly client: MeshClient;
private readonly baselineRadio = signal<RadioConfig>({});
private readonly baselineModules = signal<ModuleConfig>({});
private readonly baselineChannels = signal<ReadonlyMap<number, Protobuf.Channel.Channel>>(
new Map(),
);
private readonly baselineChannels = signal<
ReadonlyMap<number, Protobuf.Channel.Channel>
>(new Map());
private readonly workingRadio = signal<RadioConfig>({});
private readonly workingModules = signal<ModuleConfig>({});
private readonly workingChannels = signal<ReadonlyMap<number, Protobuf.Channel.Channel>>(
new Map(),
private readonly workingChannels = signal<
ReadonlyMap<number, Protobuf.Channel.Channel>
>(new Map());
private readonly baselineOwner = signal<Protobuf.Mesh.User | undefined>(
undefined,
);
private readonly baselineOwner = signal<Protobuf.Mesh.User | undefined>(undefined);
private readonly workingOwner = signal<Protobuf.Mesh.User | undefined>(undefined);
private readonly queuedAdminMessages = signal<readonly Protobuf.Admin.AdminMessage[]>([]);
private readonly _dirtyRadioSections = signal<readonly RadioConfigSection[]>([]);
private readonly _dirtyModuleSections = signal<readonly ModuleConfigSection[]>([]);
private readonly workingOwner = signal<Protobuf.Mesh.User | undefined>(
undefined,
);
private readonly queuedAdminMessages = signal<
readonly Protobuf.Admin.AdminMessage[]
>([]);
private readonly _dirtyRadioSections = signal<readonly RadioConfigSection[]>(
[],
);
private readonly _dirtyModuleSections = signal<
readonly ModuleConfigSection[]
>([]);
private readonly _dirtyChannels = signal<readonly number[]>([]);
private readonly _isOwnerDirty = signal<boolean>(false);
private readonly _isDirty = signal<boolean>(false);
public readonly radio: ReadonlySignal<RadioConfig> = toReadonly(this.workingRadio);
public readonly modules: ReadonlySignal<ModuleConfig> = toReadonly(this.workingModules);
public readonly channels: ReadonlySignal<ReadonlyMap<number, Protobuf.Channel.Channel>> =
toReadonly(this.workingChannels);
public readonly dirtyRadioSections: ReadonlySignal<readonly RadioConfigSection[]> = toReadonly(
this._dirtyRadioSections,
public readonly radio: ReadonlySignal<RadioConfig> = toReadonly(
this.workingRadio,
);
public readonly dirtyModuleSections: ReadonlySignal<readonly ModuleConfigSection[]> = toReadonly(
this._dirtyModuleSections,
public readonly modules: ReadonlySignal<ModuleConfig> = toReadonly(
this.workingModules,
);
public readonly channels: ReadonlySignal<
ReadonlyMap<number, Protobuf.Channel.Channel>
> = toReadonly(this.workingChannels);
public readonly dirtyRadioSections: ReadonlySignal<
readonly RadioConfigSection[]
> = toReadonly(this._dirtyRadioSections);
public readonly dirtyModuleSections: ReadonlySignal<
readonly ModuleConfigSection[]
> = toReadonly(this._dirtyModuleSections);
public readonly dirtyChannels: ReadonlySignal<readonly number[]> = toReadonly(
this._dirtyChannels,
);
public readonly owner: ReadonlySignal<Protobuf.Mesh.User | undefined> = toReadonly(
this.workingOwner,
public readonly owner: ReadonlySignal<Protobuf.Mesh.User | undefined> =
toReadonly(this.workingOwner);
public readonly isOwnerDirty: ReadonlySignal<boolean> = toReadonly(
this._isOwnerDirty,
);
public readonly isOwnerDirty: ReadonlySignal<boolean> = toReadonly(this._isOwnerDirty);
public readonly isDirty: ReadonlySignal<boolean> = toReadonly(this._isDirty);
constructor(client: MeshClient) {
@@ -88,14 +107,20 @@ export class ConfigEditor {
// their edit in place; the dirty bookkeeping will refresh below.
const wasDirty = this._dirtyRadioSections.peek().includes(variant);
if (!wasDirty) {
this.workingRadio.value = { ...this.workingRadio.peek(), [variant]: next[variant] };
this.workingRadio.value = {
...this.workingRadio.peek(),
[variant]: next[variant],
};
}
}
this.recomputeDirty();
});
client.events.onModuleConfigPacket.subscribe((moduleConfig) => {
const next = ConfigMapper.mergeModule(this.baselineModules.peek(), moduleConfig);
const next = ConfigMapper.mergeModule(
this.baselineModules.peek(),
moduleConfig,
);
this.baselineModules.value = next;
const variant = moduleConfig.payloadVariant.case;
if (variant) {
@@ -168,7 +193,10 @@ export class ConfigEditor {
* alongside their other edits.
*/
public queueAdminMessage(message: Protobuf.Admin.AdminMessage): void {
this.queuedAdminMessages.value = [...this.queuedAdminMessages.peek(), message];
this.queuedAdminMessages.value = [
...this.queuedAdminMessages.peek(),
message,
];
this.recomputeDirty();
}
@@ -279,10 +307,16 @@ export class ConfigEditor {
const radioBase = this.baselineRadio.peek();
const radioWorking = this.workingRadio.peek();
const radioDirty: RadioConfigSection[] = [];
const radioKeys = new Set<string>([...Object.keys(radioBase), ...Object.keys(radioWorking)]);
const radioKeys = new Set<string>([
...Object.keys(radioBase),
...Object.keys(radioWorking),
]);
for (const key of radioKeys) {
if (
!shallowEqual(radioBase[key as keyof RadioConfig], radioWorking[key as keyof RadioConfig])
!shallowEqual(
radioBase[key as keyof RadioConfig],
radioWorking[key as keyof RadioConfig],
)
) {
radioDirty.push(key as RadioConfigSection);
}
@@ -291,7 +325,10 @@ export class ConfigEditor {
const moduleBase = this.baselineModules.peek();
const moduleWorking = this.workingModules.peek();
const moduleDirty: ModuleConfigSection[] = [];
const moduleKeys = new Set<string>([...Object.keys(moduleBase), ...Object.keys(moduleWorking)]);
const moduleKeys = new Set<string>([
...Object.keys(moduleBase),
...Object.keys(moduleWorking),
]);
for (const key of moduleKeys) {
if (
!shallowEqual(
@@ -306,14 +343,20 @@ export class ConfigEditor {
const channelDirty: number[] = [];
const channelBase = this.baselineChannels.peek();
const channelWorking = this.workingChannels.peek();
const channelKeys = new Set<number>([...channelBase.keys(), ...channelWorking.keys()]);
const channelKeys = new Set<number>([
...channelBase.keys(),
...channelWorking.keys(),
]);
for (const idx of channelKeys) {
if (!shallowEqual(channelBase.get(idx), channelWorking.get(idx))) {
channelDirty.push(idx);
}
}
const ownerDirty = !shallowEqual(this.baselineOwner.peek(), this.workingOwner.peek());
const ownerDirty = !shallowEqual(
this.baselineOwner.peek(),
this.workingOwner.peek(),
);
const hasQueuedAdmin = this.queuedAdminMessages.peek().length > 0;
this._dirtyRadioSections.value = radioDirty;
@@ -329,9 +372,15 @@ export class ConfigEditor {
}
}
function buildRadioConfig(variant: RadioConfigSection, value: unknown): Protobuf.Config.Config {
function buildRadioConfig(
variant: RadioConfigSection,
value: unknown,
): Protobuf.Config.Config {
return create(Protobuf.Config.ConfigSchema, {
payloadVariant: { case: variant, value } as Protobuf.Config.Config["payloadVariant"],
payloadVariant: {
case: variant,
value,
} as Protobuf.Config.Config["payloadVariant"],
});
}
+4 -1
View File
@@ -1,5 +1,8 @@
export { ConfigClient } from "./ConfigClient.ts";
export { ConfigEditor } from "./domain/ConfigEditor.ts";
export type { RadioConfig, RadioConfigSection } from "./domain/RadioConfig.ts";
export type { ModuleConfig, ModuleConfigSection } from "./domain/ModuleConfig.ts";
export type {
ModuleConfig,
ModuleConfigSection,
} from "./domain/ModuleConfig.ts";
export { ConfigMapper } from "./infrastructure/ConfigMapper.ts";
@@ -3,12 +3,18 @@ import type { ModuleConfig } from "../domain/ModuleConfig.ts";
import type { RadioConfig } from "../domain/RadioConfig.ts";
export const ConfigMapper = {
mergeRadio(existing: RadioConfig, incoming: Protobuf.Config.Config): RadioConfig {
mergeRadio(
existing: RadioConfig,
incoming: Protobuf.Config.Config,
): RadioConfig {
const variant = incoming.payloadVariant;
if (!variant.case) return existing;
return { ...existing, [variant.case]: variant.value };
},
mergeModule(existing: ModuleConfig, incoming: Protobuf.ModuleConfig.ModuleConfig): ModuleConfig {
mergeModule(
existing: ModuleConfig,
incoming: Protobuf.ModuleConfig.ModuleConfig,
): ModuleConfig {
const variant = incoming.payloadVariant;
if (!variant.case) return existing;
return { ...existing, [variant.case]: variant.value };
@@ -18,8 +18,12 @@ export class DeviceClient {
public readonly isConfigured: ReadonlySignal<boolean>;
public readonly pendingSettingsChanges: ReadonlySignal<boolean>;
public readonly myNodeNum: ReadonlySignal<number | undefined>;
public readonly metadata: ReadonlySignal<Protobuf.Mesh.DeviceMetadata | undefined>;
public readonly myNodeInfo: ReadonlySignal<Protobuf.Mesh.MyNodeInfo | undefined>;
public readonly metadata: ReadonlySignal<
Protobuf.Mesh.DeviceMetadata | undefined
>;
public readonly myNodeInfo: ReadonlySignal<
Protobuf.Mesh.MyNodeInfo | undefined
>;
constructor(client: MeshClient) {
this.client = client;
@@ -2,7 +2,10 @@ import type { MeshClient } from "../../../core/client/MeshClient.ts";
import { ChannelNumber } from "../../../core/types.ts";
import { sendAdminMessage } from "../infrastructure/AdminMessageSender.ts";
export function getMetadata(client: MeshClient, nodeNum: number): Promise<number> {
export function getMetadata(
client: MeshClient,
nodeNum: number,
): Promise<number> {
return sendAdminMessage(
client,
{ case: "getDeviceMetadataRequest", value: true },
@@ -9,7 +9,10 @@ export function reboot(client: MeshClient, seconds: number): Promise<number> {
return sendAdminMessage(client, { case: "rebootSeconds", value: seconds });
}
export function rebootOta(client: MeshClient, seconds: number): Promise<number> {
export function rebootOta(
client: MeshClient,
seconds: number,
): Promise<number> {
return sendAdminMessage(client, { case: "rebootOtaSeconds", value: seconds });
}
+5 -1
View File
@@ -1,3 +1,7 @@
export { DeviceClient } from "./DeviceClient.ts";
export type { Device } from "./domain/Device.ts";
export { DeviceStatusEnum, isConfigured, isConnected } from "./domain/DeviceStatus.ts";
export {
DeviceStatusEnum,
isConfigured,
isConnected,
} from "./domain/DeviceStatus.ts";
@@ -8,14 +8,27 @@ import { DeviceStatusEnum } from "../../../core/transport/Transport.ts";
* DeviceClient.
*/
export function createDeviceStore() {
const status = createStore<DeviceStatusEnum>(DeviceStatusEnum.DeviceDisconnected);
const status = createStore<DeviceStatusEnum>(
DeviceStatusEnum.DeviceDisconnected,
);
const isConfigured = createStore(false);
const pendingSettingsChanges = createStore(false);
const myNodeNum = createStore<number | undefined>(undefined);
const metadata = createStore<Protobuf.Mesh.DeviceMetadata | undefined>(undefined);
const myNodeInfo = createStore<Protobuf.Mesh.MyNodeInfo | undefined>(undefined);
const metadata = createStore<Protobuf.Mesh.DeviceMetadata | undefined>(
undefined,
);
const myNodeInfo = createStore<Protobuf.Mesh.MyNodeInfo | undefined>(
undefined,
);
return { status, isConfigured, pendingSettingsChanges, myNodeNum, metadata, myNodeInfo };
return {
status,
isConfigured,
pendingSettingsChanges,
myNodeNum,
metadata,
myNodeInfo,
};
}
export type DeviceStore = ReturnType<typeof createDeviceStore>;
@@ -42,7 +42,9 @@ export class FilesClient {
}
}
public async download(filename: string): Promise<ResultType<FileTransfer, Error>> {
public async download(
filename: string,
): Promise<ResultType<FileTransfer, Error>> {
const id = generatePacketId();
const transfer: FileTransfer = {
id,
@@ -81,7 +81,9 @@ describe("NodesClient PKI error tracking", () => {
}),
});
expect(client.nodes.errorFor(99)?.error).toBe(Protobuf.Mesh.Routing_Error.PKI_UNKNOWN_PUBKEY);
expect(client.nodes.errorFor(99)?.error).toBe(
Protobuf.Mesh.Routing_Error.PKI_UNKNOWN_PUBKEY,
);
});
it("clearError / clearAllErrors", () => {
@@ -11,7 +11,9 @@ describe("NodesClient", () => {
expect(client.nodes.list.value).toEqual([]);
client.events.onNodeInfoPacket.dispatch(create(Protobuf.Mesh.NodeInfoSchema, { num: 1 }));
client.events.onNodeInfoPacket.dispatch(
create(Protobuf.Mesh.NodeInfoSchema, { num: 1 }),
);
client.events.onNodeInfoPacket.dispatch(
create(Protobuf.Mesh.NodeInfoSchema, { num: 2, isFavorite: true }),
);
+18 -5
View File
@@ -11,9 +11,18 @@ import { InMemoryNodesRepository } from "./infrastructure/repositories/InMemoryN
import { validateIncomingNode } from "./infrastructure/nodeValidation.ts";
import { NodeErrorsStore } from "./state/nodeErrorsStore.ts";
import { NodesStore } from "./state/nodesStore.ts";
import { favoriteNode, removeFavoriteNode } from "./application/FavoriteNodeUseCase.ts";
import { ignoreNode, removeIgnoredNode } from "./application/IgnoreNodeUseCase.ts";
import { removeNodeByNum, resetNodes } from "./application/RemoveNodeUseCase.ts";
import {
favoriteNode,
removeFavoriteNode,
} from "./application/FavoriteNodeUseCase.ts";
import {
ignoreNode,
removeIgnoredNode,
} from "./application/IgnoreNodeUseCase.ts";
import {
removeNodeByNum,
resetNodes,
} from "./application/RemoveNodeUseCase.ts";
export interface NodesClientOptions {
repository?: NodesRepository;
@@ -42,7 +51,9 @@ export class NodesClient {
this.list = this.store.read;
this.errors = this.errorsStore.read;
client.events.onNodeInfoPacket.subscribe((info) => this.handleIncoming(info));
client.events.onNodeInfoPacket.subscribe((info) =>
this.handleIncoming(info),
);
client.events.onUserPacket.subscribe((packet) => {
this.patch(packet.from, { user: packet.data });
@@ -191,7 +202,9 @@ export class NodesClient {
* removeAllNodes(true) + resetNodes flow that the ResetNodeDb dialog
* relied on.
*/
public async reset(options: { keepMyNode?: boolean } = {}): Promise<ResultType<number, Error>> {
public async reset(
options: { keepMyNode?: boolean } = {},
): Promise<ResultType<number, Error>> {
const myNodeNum = this.client.device.myNodeNum.value;
if (options.keepMyNode && myNodeNum !== undefined) {
const me = this.store.get(myNodeNum);
@@ -8,7 +8,10 @@ export async function favoriteNode(
nodeNum: number,
): Promise<ResultType<number, Error>> {
try {
const id = await sendAdminMessage(client, { case: "setFavoriteNode", value: nodeNum });
const id = await sendAdminMessage(client, {
case: "setFavoriteNode",
value: nodeNum,
});
return Result.ok(id);
} catch (e) {
return Result.err(e instanceof Error ? e : new Error(String(e)));
@@ -20,7 +23,10 @@ export async function removeFavoriteNode(
nodeNum: number,
): Promise<ResultType<number, Error>> {
try {
const id = await sendAdminMessage(client, { case: "removeFavoriteNode", value: nodeNum });
const id = await sendAdminMessage(client, {
case: "removeFavoriteNode",
value: nodeNum,
});
return Result.ok(id);
} catch (e) {
return Result.err(e instanceof Error ? e : new Error(String(e)));
@@ -8,7 +8,10 @@ export async function ignoreNode(
nodeNum: number,
): Promise<ResultType<number, Error>> {
try {
const id = await sendAdminMessage(client, { case: "setIgnoredNode", value: nodeNum });
const id = await sendAdminMessage(client, {
case: "setIgnoredNode",
value: nodeNum,
});
return Result.ok(id);
} catch (e) {
return Result.err(e instanceof Error ? e : new Error(String(e)));
@@ -20,7 +23,10 @@ export async function removeIgnoredNode(
nodeNum: number,
): Promise<ResultType<number, Error>> {
try {
const id = await sendAdminMessage(client, { case: "removeIgnoredNode", value: nodeNum });
const id = await sendAdminMessage(client, {
case: "removeIgnoredNode",
value: nodeNum,
});
return Result.ok(id);
} catch (e) {
return Result.err(e instanceof Error ? e : new Error(String(e)));
@@ -8,16 +8,24 @@ export async function removeNodeByNum(
nodeNum: number,
): Promise<ResultType<number, Error>> {
try {
const id = await sendAdminMessage(client, { case: "removeByNodenum", value: nodeNum });
const id = await sendAdminMessage(client, {
case: "removeByNodenum",
value: nodeNum,
});
return Result.ok(id);
} catch (e) {
return Result.err(e instanceof Error ? e : new Error(String(e)));
}
}
export async function resetNodes(client: MeshClient): Promise<ResultType<number, Error>> {
export async function resetNodes(
client: MeshClient,
): Promise<ResultType<number, Error>> {
try {
const id = await sendAdminMessage(client, { case: "nodedbReset", value: true });
const id = await sendAdminMessage(client, {
case: "nodedbReset",
value: true,
});
return Result.ok(id);
} catch (e) {
return Result.err(e instanceof Error ? e : new Error(String(e)));
@@ -9,7 +9,10 @@ export async function setOwner(
owner: Protobuf.Mesh.User,
): Promise<ResultType<number, Error>> {
try {
const id = await sendAdminMessage(client, { case: "setOwner", value: owner });
const id = await sendAdminMessage(client, {
case: "setOwner",
value: owner,
});
return Result.ok(id);
} catch (e) {
return Result.err(e instanceof Error ? e : new Error(String(e)));
@@ -7,7 +7,10 @@ import type * as Protobuf from "@meshtastic/protobufs";
* stored public-key history. Routing errors come straight off the wire
* via `Routing_Error`.
*/
export type NodeErrorType = Protobuf.Mesh.Routing_Error | "MISMATCH_PKI" | "DUPLICATE_PKI";
export type NodeErrorType =
| Protobuf.Mesh.Routing_Error
| "MISMATCH_PKI"
| "DUPLICATE_PKI";
export interface NodeError {
readonly node: number;
+4 -1
View File
@@ -4,5 +4,8 @@ export type { Node } from "./domain/Node.ts";
export type { NodeError, NodeErrorType } from "./domain/NodeError.ts";
export type { NodesRepository } from "./domain/NodesRepository.ts";
export { NodeMapper } from "./infrastructure/NodeMapper.ts";
export { equalKey, validateIncomingNode } from "./infrastructure/nodeValidation.ts";
export {
equalKey,
validateIncomingNode,
} from "./infrastructure/nodeValidation.ts";
export { InMemoryNodesRepository } from "./infrastructure/repositories/InMemoryNodesRepository.ts";
@@ -6,7 +6,10 @@ import type { NodeErrorType } from "../domain/NodeError.ts";
* Byte-equal compare for two public keys. Empty / undefined keys never
* match each other.
*/
export function equalKey(a?: Uint8Array | null, b?: Uint8Array | null): boolean {
export function equalKey(
a?: Uint8Array | null,
b?: Uint8Array | null,
): boolean {
if (!a || !b) return false;
if (a === b) return true;
if (a.byteLength !== b.byteLength) return false;
@@ -31,7 +31,10 @@ export class PositionClient {
return this.store.get(nodeNum);
}
public setFixed(latitude: number, longitude: number): Promise<ResultType<number, Error>> {
public setFixed(
latitude: number,
longitude: number,
): Promise<ResultType<number, Error>> {
return setFixedPosition(this.client, latitude, longitude);
}
@@ -39,7 +42,9 @@ export class PositionClient {
return removeFixedPosition(this.client);
}
public set(position: Protobuf.Mesh.Position): Promise<ResultType<number, Error>> {
public set(
position: Protobuf.Mesh.Position,
): Promise<ResultType<number, Error>> {
return setPosition(this.client, position);
}
@@ -29,7 +29,9 @@ export async function setFixedPosition(
}
}
export async function removeFixedPosition(client: MeshClient): Promise<ResultType<number, Error>> {
export async function removeFixedPosition(
client: MeshClient,
): Promise<ResultType<number, Error>> {
try {
const id = await sendAdminMessage(
client,
@@ -6,7 +6,12 @@ import { createFakeTransport } from "../../core/testing/createFakeTransport.ts";
import { ChannelNumber } from "../../core/types.ts";
import { InMemoryTelemetryRepository } from "./infrastructure/repositories/InMemoryTelemetryRepository.ts";
const dispatch = (client: MeshClient, from: number, ms: number, battery = 80): void => {
const dispatch = (
client: MeshClient,
from: number,
ms: number,
battery = 80,
): void => {
client.events.onTelemetryPacket.dispatch({
id: ms,
from,
@@ -18,7 +23,9 @@ const dispatch = (client: MeshClient, from: number, ms: number, battery = 80): v
time: ms,
variant: {
case: "deviceMetrics",
value: create(Protobuf.Telemetry.DeviceMetricsSchema, { batteryLevel: battery }),
value: create(Protobuf.Telemetry.DeviceMetricsSchema, {
batteryLevel: battery,
}),
},
}),
});
@@ -46,7 +53,9 @@ describe("TelemetryClient persistence", () => {
nodeNum: 200,
time: new Date(500),
kind: "deviceMetrics",
value: create(Protobuf.Telemetry.DeviceMetricsSchema, { batteryLevel: 60 }),
value: create(Protobuf.Telemetry.DeviceMetricsSchema, {
batteryLevel: 60,
}),
});
const { transport } = createFakeTransport();
@@ -21,7 +21,9 @@ describe("TelemetryClient", () => {
time: 1000,
variant: {
case: "deviceMetrics",
value: create(Protobuf.Telemetry.DeviceMetricsSchema, { batteryLevel: 80 }),
value: create(Protobuf.Telemetry.DeviceMetricsSchema, {
batteryLevel: 80,
}),
},
}),
});
@@ -36,7 +38,9 @@ describe("TelemetryClient", () => {
time: 2000,
variant: {
case: "deviceMetrics",
value: create(Protobuf.Telemetry.DeviceMetricsSchema, { batteryLevel: 70 }),
value: create(Protobuf.Telemetry.DeviceMetricsSchema, {
batteryLevel: 70,
}),
},
}),
});
@@ -56,7 +56,11 @@ export class TelemetryClient {
* repository. Caller is responsible for merging with the in-memory store
* if it wants the result reflected in the `history(nodeNum)` signal.
*/
public loadBefore(nodeNum: number, cursor: Date, limit: number): Promise<TelemetryReading[]> {
public loadBefore(
nodeNum: number,
cursor: Date,
limit: number,
): Promise<TelemetryReading[]> {
return this.repository.loadBefore(nodeNum, cursor, limit);
}
@@ -17,7 +17,11 @@ export interface TelemetryRetentionPolicy {
*/
export interface TelemetryRepository {
loadRecent(nodeNum: number, limit: number): Promise<TelemetryReading[]>;
loadBefore(nodeNum: number, cursor: Date, limit: number): Promise<TelemetryReading[]>;
loadBefore(
nodeNum: number,
cursor: Date,
limit: number,
): Promise<TelemetryReading[]>;
append(reading: TelemetryReading): Promise<void>;
appendBatch(readings: ReadonlyArray<TelemetryReading>): Promise<void>;
prune(policy: TelemetryRetentionPolicy): Promise<void>;
+4 -1
View File
@@ -1,6 +1,9 @@
export { TelemetryClient } from "./TelemetryClient.ts";
export type { TelemetryClientOptions } from "./TelemetryClient.ts";
export type { TelemetryKind, TelemetryReading } from "./domain/TelemetryReading.ts";
export type {
TelemetryKind,
TelemetryReading,
} from "./domain/TelemetryReading.ts";
export type {
TelemetryRepository,
TelemetryRetentionPolicy,
@@ -3,7 +3,9 @@ import type * as Protobuf from "@meshtastic/protobufs";
import type { TelemetryReading } from "../domain/TelemetryReading.ts";
export const TelemetryMapper = {
fromPacket(packet: PacketMetadata<Protobuf.Telemetry.Telemetry>): TelemetryReading {
fromPacket(
packet: PacketMetadata<Protobuf.Telemetry.Telemetry>,
): TelemetryReading {
return {
nodeNum: packet.from,
time: packet.rxTime,
@@ -36,7 +36,10 @@ describe("InMemoryTelemetryRepository", () => {
it("prune drops readings older than olderThanMs", async () => {
const repo = new InMemoryTelemetryRepository();
await repo.appendBatch([reading(1, Date.now() - 10_000_000), reading(1, Date.now() - 1_000)]);
await repo.appendBatch([
reading(1, Date.now() - 10_000_000),
reading(1, Date.now() - 1_000),
]);
await repo.prune({ olderThanMs: 5_000_000 });
const remaining = await repo.loadRecent(1, 10);
expect(remaining).toHaveLength(1);
@@ -11,11 +11,18 @@ import type {
export class InMemoryTelemetryRepository implements TelemetryRepository {
private readonly buckets = new Map<number, TelemetryReading[]>();
async loadRecent(nodeNum: number, limit: number): Promise<TelemetryReading[]> {
async loadRecent(
nodeNum: number,
limit: number,
): Promise<TelemetryReading[]> {
return (this.buckets.get(nodeNum) ?? []).slice(-limit);
}
async loadBefore(nodeNum: number, cursor: Date, limit: number): Promise<TelemetryReading[]> {
async loadBefore(
nodeNum: number,
cursor: Date,
limit: number,
): Promise<TelemetryReading[]> {
const bucket = this.buckets.get(nodeNum) ?? [];
const idx = bucket.findIndex((r) => r.time >= cursor);
const end = idx === -1 ? bucket.length : idx;
@@ -37,7 +44,9 @@ export class InMemoryTelemetryRepository implements TelemetryRepository {
}
async prune(policy: TelemetryRetentionPolicy): Promise<void> {
const cutoff = policy.olderThanMs ? Date.now() - policy.olderThanMs : undefined;
const cutoff = policy.olderThanMs
? Date.now() - policy.olderThanMs
: undefined;
for (const [nodeNum, bucket] of this.buckets.entries()) {
let next = bucket;
if (cutoff !== undefined) {
@@ -1,14 +1,26 @@
import { type Signal, signal } from "@preact/signals-core";
import { type ReadonlySignal, toReadonly } from "../../../core/signals/createStore.ts";
import {
type ReadonlySignal,
toReadonly,
} from "../../../core/signals/createStore.ts";
import type { TelemetryReading } from "../domain/TelemetryReading.ts";
const MAX_HISTORY = 256;
export class TelemetryStore {
private readonly latest = new Map<number, Signal<TelemetryReading | undefined>>();
private readonly latestRead = new Map<number, ReadonlySignal<TelemetryReading | undefined>>();
private readonly latest = new Map<
number,
Signal<TelemetryReading | undefined>
>();
private readonly latestRead = new Map<
number,
ReadonlySignal<TelemetryReading | undefined>
>();
private readonly history = new Map<number, Signal<TelemetryReading[]>>();
private readonly historyRead = new Map<number, ReadonlySignal<TelemetryReading[]>>();
private readonly historyRead = new Map<
number,
ReadonlySignal<TelemetryReading[]>
>();
append(reading: TelemetryReading): void {
const latestSig = this.ensureLatest(reading.nodeNum);
@@ -9,7 +9,9 @@ export async function runTraceRoute(
destination: number,
): Promise<ResultType<number, Error>> {
try {
const routeDiscovery = create(Protobuf.Mesh.RouteDiscoverySchema, { route: [] });
const routeDiscovery = create(Protobuf.Mesh.RouteDiscoverySchema, {
route: [],
});
const id = await client.sendPacket(
toBinary(Protobuf.Mesh.RouteDiscoverySchema, routeDiscovery),
Protobuf.Portnums.PortNum.TRACEROUTE_APP,