dispatch: typed handlers, respond/defer/error, automatic ErrorResponse, watchdog
src/dispatcher.ts routes a directive to capability.on(name | "*"), device.onDirective() or device.onReportState(), with the payload checked by the descriptor of the interface. The DirectiveContext answers with respond/report/defer/error; respond() and report() start from device.state(). A handler or 1.x listener that throws or rejects is answered with INTERNAL_ERROR (an AlexaError with itself) and reported through "error", never as an unhandled rejection. Undeclared interface, unknown directive, AdjustMode on an unordered mode and a missing handler get INVALID_DIRECTIVE, a bad payload INVALID_VALUE; a device with an "Event" or "ReportState" listener keeps the answer to itself. Every answer passes the dispatcher: the first one per correlationToken is published, a second is refused. No answer within answerWithinMs (6500, 0 = off, unref'd timer) sends INTERNAL_ERROR and emits "unanswered". A messageId that arrived in the last 60 s is dropped. New: "unknownEndpoint", options answerUnknownEndpoints, publisher, timers, and bridge.receive() to run a bridge without a broker. 168 tests pass (18 new). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
parent
e0fe9d2812
commit
feff828ec1
40 changed files with 2149 additions and 136 deletions
102
src/Alex2Node.ts
102
src/Alex2Node.ts
|
|
@ -7,8 +7,11 @@ import { checkEndpoint } from "./device/validate.js";
|
|||
import { EventEmitter } from "events";
|
||||
import { DisplayCategory } from "./compat/enums.js";
|
||||
import { DeclarationError } from "./registry/types.js";
|
||||
import { Dispatcher } from "./dispatcher.js";
|
||||
import type { Timers } from "./dispatcher.js";
|
||||
import * as topics from "./topics.js";
|
||||
import { MqttPublisher } from "./transport.js";
|
||||
import { asError, MqttPublisher } from "./transport.js";
|
||||
import type { Publisher } from "./transport.js";
|
||||
|
||||
/** Optional settings for the bridge (1.5.1). Everything has the 1.4.0 behaviour as its default. */
|
||||
export interface Alex2MQTTOptions {
|
||||
|
|
@ -23,6 +26,20 @@ export interface Alex2MQTTOptions {
|
|||
* { type: "AlexaInterface", interface: "Alexa", version: "3" }, which Amazon requires and 1.x left out.
|
||||
*/
|
||||
alexaInterface?: boolean;
|
||||
/**
|
||||
* How long a directive may wait for its answer, in milliseconds. After that the bridge answers INTERNAL_ERROR and
|
||||
* emits "unanswered". Default: 6500, before Alex2MQTT gives up at 7000. 0: the bridge never answers for a handler.
|
||||
*/
|
||||
answerWithinMs?: number;
|
||||
/**
|
||||
* true: a directive for an endpoint the bridge does not have is answered with NO_SUCH_ENDPOINT. Default: it is
|
||||
* left alone, because the endpoint may belong to another bridge on the same root topic.
|
||||
*/
|
||||
answerUnknownEndpoints?: boolean;
|
||||
/** Publish here and not to the broker: a MemoryPublisher and receive() run a bridge that never connects. */
|
||||
publisher?: Publisher;
|
||||
/** The timer of answerWithinMs, for a test that does not wait. Default: setTimeout, unref'd. */
|
||||
timers?: Timers;
|
||||
}
|
||||
|
||||
export const DEFAULT_HOST = "mqtt://Alex2MQTT.stormysdream.club:1883";
|
||||
|
|
@ -46,11 +63,15 @@ const DESCRIBED = [
|
|||
* unconditionally, and Node kills a process that has an unhandled "error" event)
|
||||
* "discover" (n) a discovery request was answered with n devices
|
||||
* "directive" (info) a directive was dispatched to a device: { endpointId, namespace, name }
|
||||
* "unknownEndpoint" (info) a directive came for an endpoint that is not registered: { endpointId, namespace, name }
|
||||
* "unanswered" (info) nothing answered a directive in time and the bridge answered INTERNAL_ERROR:
|
||||
* { endpointId, namespace, name, correlationToken }
|
||||
*/
|
||||
class Alex2MQTT extends EventEmitter {
|
||||
private client: MqttClient | null = null;
|
||||
// One for the life of the bridge: the devices keep it over disconnect() and connect()
|
||||
private readonly publisher = new MqttPublisher(() => this.client);
|
||||
private readonly publisher: Publisher;
|
||||
private readonly dispatcher: Dispatcher;
|
||||
private devices: Device[] = [];
|
||||
private MqttHost: string;
|
||||
private options: Alex2MQTTOptions;
|
||||
|
|
@ -71,6 +92,18 @@ class Alex2MQTT extends EventEmitter {
|
|||
super(); // Initialize EventEmitter
|
||||
this.options = options || {};
|
||||
this.MqttHost = this.options.host || DEFAULT_HOST;
|
||||
this.publisher = this.options.publisher ?? new MqttPublisher(() => this.client);
|
||||
this.dispatcher = new Dispatcher({
|
||||
rootTopic,
|
||||
publisher: this.publisher,
|
||||
getDevice: (endpointId) => this.getDevice(endpointId),
|
||||
log: (message, detail) => this.log(message, detail),
|
||||
fail: (err) => this.fail(err),
|
||||
emit: (event, ...args) => { this.emit(event, ...args); },
|
||||
answerWithinMs: this.options.answerWithinMs,
|
||||
answerUnknownEndpoints: this.options.answerUnknownEndpoints,
|
||||
timers: this.options.timers,
|
||||
});
|
||||
}
|
||||
|
||||
private log(message: string, detail?: unknown): void {
|
||||
|
|
@ -112,43 +145,41 @@ class Alex2MQTT extends EventEmitter {
|
|||
this.client.on("close", () => { this.connected = false; this.emit("close"); });
|
||||
this.client.on("error", (err: Error) => { this.connected = false; this.fail(err); });
|
||||
|
||||
this.client.on("message", (topic: string, message: Buffer) => {
|
||||
this.log(`MQTT Message Received`, { topic, payload: message.toString() });
|
||||
this.client.on("message", (topic: string, message: Buffer) => { void this.receive(topic, message); });
|
||||
}
|
||||
|
||||
/**
|
||||
* What the bridge does with a message of the broker: it answers a discovery request, and it hands a directive to
|
||||
* the handlers of its device. Resolves when they are done and never rejects. With the publisher option a test
|
||||
* calls it in place of the broker:
|
||||
*
|
||||
* await bridge.receive("root/lamp-1/alexaDirective", JSON.stringify(directive));
|
||||
*/
|
||||
async receive(topic: string, payload: Buffer | string): Promise<void> {
|
||||
const text = payload.toString();
|
||||
this.log(`MQTT Message Received`, { topic, payload: text });
|
||||
try {
|
||||
if (topic === topics.discover(this.rootTopic)) {
|
||||
this.log("Discovery request received, getting device json...");
|
||||
const deviceArray = this.describeDevices();
|
||||
this.lastDiscoveryAt = new Date().toISOString();
|
||||
void this.publisher.publish(topics.discoverReply(this.rootTopic), deviceArray).then((result) => {
|
||||
if (!result.ok) { this.fail(result.error); return; }
|
||||
this.log(`Discovery payloads published to ${result.topic}`, deviceArray);
|
||||
this.emit("discover", deviceArray.length);
|
||||
});
|
||||
await this.answerDiscovery();
|
||||
return;
|
||||
}
|
||||
// Another topic can still arrive: a broker may deliver what an earlier session of this client id subscribed to
|
||||
const endpointId = topics.directiveEndpoint(this.rootTopic, topic);
|
||||
if (endpointId === null) return;
|
||||
const device = this.devices.find((d) => d.endpointId === endpointId);
|
||||
if (!device) {
|
||||
this.log(`No device found for endpointId: ${endpointId}`);
|
||||
return;
|
||||
}
|
||||
let payload;
|
||||
try {
|
||||
payload = JSON.parse(message.toString());
|
||||
} catch (e) {
|
||||
this.log(`Failed to parse payload JSON`, e);
|
||||
return;
|
||||
}
|
||||
if (!payload || !payload.header) return;
|
||||
this.emit("directive", { endpointId, namespace: payload.header.namespace, name: payload.header.name });
|
||||
if (payload.header.namespace === "Alexa" && payload.header.name === "ReportState") {
|
||||
this.log(`ReportState directive for device ${endpointId}`);
|
||||
device.emit("ReportState", payload);
|
||||
} else {
|
||||
device.emit("Event", payload, payload.header.namespace);
|
||||
}
|
||||
});
|
||||
if (endpointId !== null) await this.dispatcher.dispatch(endpointId, text);
|
||||
} catch (err) {
|
||||
// A listener of "discover", "directive" or "unknownEndpoint" threw
|
||||
this.fail(asError(err));
|
||||
}
|
||||
}
|
||||
|
||||
private async answerDiscovery(): Promise<void> {
|
||||
this.log("Discovery request received, getting device json...");
|
||||
const deviceArray = this.describeDevices();
|
||||
this.lastDiscoveryAt = new Date().toISOString();
|
||||
const result = await this.publisher.publish(topics.discoverReply(this.rootTopic), deviceArray);
|
||||
if (!result.ok) { this.fail(result.error); return; }
|
||||
this.log(`Discovery payloads published to ${result.topic}`, deviceArray);
|
||||
this.emit("discover", deviceArray.length);
|
||||
}
|
||||
|
||||
// The endpoint objects of a discovery answer. What check() says about a device is logged, each line once. A device
|
||||
|
|
@ -229,7 +260,8 @@ class Alex2MQTT extends EventEmitter {
|
|||
device.alexaInterface = this.options.alexaInterface !== false;
|
||||
device.endpointHealth = endpointHealth;
|
||||
device.onPublishError = (err) => this.fail(err); // a failed publish is an "error" event (when listened to), never a rejected send()
|
||||
device.publisher = this.publisher;
|
||||
// Through the dispatcher, which lets one answer to a directive pass
|
||||
device.publisher = this.dispatcher.publisher;
|
||||
this.devices.push(device);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,7 @@
|
|||
import type { DirectiveHandler } from "../dispatcher.js";
|
||||
import { s } from "../registry/schema.js";
|
||||
import type { Infer } from "../registry/schema.js";
|
||||
import { DeclarationError } from "../registry/types.js";
|
||||
import type {
|
||||
Declared, Directives, InterfaceDescriptor, Label, Properties, Semantics,
|
||||
} from "../registry/types.js";
|
||||
|
|
@ -66,6 +69,7 @@ export class Capability<P extends Properties = Properties, D extends Directives
|
|||
options: O;
|
||||
/** What the bridge logs about the declaration, once, when it answers a discovery. */
|
||||
readonly notes: string[] = [];
|
||||
private readonly handlers = new Map<string, DirectiveHandler<any>>();
|
||||
|
||||
constructor(readonly descriptor: InterfaceDescriptor<P, D, O, boolean>, declared: CommonOptions & { options: O }) {
|
||||
this.instance = declared.instance ?? "";
|
||||
|
|
@ -80,6 +84,33 @@ export class Capability<P extends Properties = Properties, D extends Directives
|
|||
return this.descriptor.namespace;
|
||||
}
|
||||
|
||||
/**
|
||||
* What the device does on a directive of the interface:
|
||||
*
|
||||
* lift.on("SetRangeValue", async (ctx) => { await motor.moveTo(ctx.payload.rangeValue); return ctx.respond(); });
|
||||
*
|
||||
* "*" is the handler of every directive that has none of its own. A handler that throws answers the directive
|
||||
* with an ErrorResponse: the AlexaError it threw, INTERNAL_ERROR for anything else. Throws a DeclarationError
|
||||
* for a name that is not a directive of the interface.
|
||||
*/
|
||||
on<K extends keyof D & string>(name: K, handler: DirectiveHandler<Infer<D[K]["payload"]>>): this;
|
||||
on(name: "*", handler: DirectiveHandler): this;
|
||||
on(name: string, handler: DirectiveHandler<any>): this {
|
||||
const names = Object.keys(this.descriptor.directives);
|
||||
// An interface the library only names (tier 3) describes no directive: any name is taken
|
||||
if (name !== "*" && this.descriptor.tier !== 3 && !names.includes(name)) {
|
||||
throw new DeclarationError(this, `${name} is not a directive of the interface, which has ${names.join(", ") || "none"}`);
|
||||
}
|
||||
if (typeof handler !== "function") throw new DeclarationError(this, `the handler of ${name} is a function`);
|
||||
this.handlers.set(name, handler);
|
||||
return this;
|
||||
}
|
||||
|
||||
/** The handler on(name) registered, or the one of "*". */
|
||||
handlerFor(name: string): DirectiveHandler<any> | undefined {
|
||||
return this.handlers.get(name) ?? this.handlers.get("*");
|
||||
}
|
||||
|
||||
/** Mappings of "open", "close", "raise", "lower" and of states, when the declaration has any. */
|
||||
get semantics(): Semantics | undefined {
|
||||
const { semantics } = this.options as { semantics?: Semantics };
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ import { DisplayCategory } from "../compat/enums.js";
|
|||
import type { AlexaInterfaceType } from "../compat/enums.js";
|
||||
import { sceneEvent } from "../messages/build.js";
|
||||
import type { ChangeCause } from "../messages/types.js";
|
||||
import type { DirectiveHandler, Fill } from "../dispatcher.js";
|
||||
import type { DisplayCategoryName } from "../registry/catalog.js";
|
||||
import { Alexa } from "../registry/interfaces/Alexa.js";
|
||||
import { EndpointHealth } from "../registry/interfaces/EndpointHealth.js";
|
||||
|
|
@ -80,6 +81,12 @@ class Device extends EventEmitter {
|
|||
* is null every send() resolves "" and reports why.
|
||||
*/
|
||||
public publisher: Publisher | null = null;
|
||||
/** Set by state(). */
|
||||
public stateProvider?: Fill;
|
||||
/** Set by onReportState(). */
|
||||
public reportStateHandler?: DirectiveHandler<Record<string, never>>;
|
||||
/** Set by onDirective(). */
|
||||
public directiveHandler?: DirectiveHandler;
|
||||
|
||||
/** client is ignored: in 1.x it was the broker client, and a device could only be built after connect(). */
|
||||
constructor(
|
||||
|
|
@ -169,6 +176,32 @@ class Device extends EventEmitter {
|
|||
const build = () => sceneEvent({ endpointId: this.endpointId, correlationToken, activated, cause });
|
||||
return send(this.publisher, answer(this.rootTopic, this.endpointId), build, this.onPublishError);
|
||||
}
|
||||
/**
|
||||
* How the device reports its state, every retrievable property of it:
|
||||
*
|
||||
* blinds.state((s) => s.set(lift, "rangeValue", motor.position).health("OK"));
|
||||
*
|
||||
* ReportState is answered with it, and it is the context of every ctx.respond(), where the handler sets only what
|
||||
* the directive changed. Alexa wants the whole state in both (alexa-response.html, "Synchronous response").
|
||||
*/
|
||||
state(fill: Fill): this {
|
||||
this.stateProvider = fill;
|
||||
return this;
|
||||
}
|
||||
/** Answer ReportState in a handler of its own, for a state that has to be read from the device first. */
|
||||
onReportState(handler: DirectiveHandler<Record<string, never>>): this {
|
||||
this.reportStateHandler = handler;
|
||||
return this;
|
||||
}
|
||||
/** The handler for the directives of declared capabilities that have no handler of their own. */
|
||||
onDirective(handler: DirectiveHandler): this {
|
||||
this.directiveHandler = handler;
|
||||
return this;
|
||||
}
|
||||
/** The capability declared for the interface, under the instance for a generic controller. */
|
||||
capability(namespace: string, instance = ""): AnyCapability | undefined {
|
||||
return this.capabilities.find((capability) => capability.namespace === namespace && capability.instance === instance);
|
||||
}
|
||||
/** The capabilities the device declared, in the order it declared them. */
|
||||
getCapabilities(): AnyCapability[] {
|
||||
return this.capabilities.slice();
|
||||
|
|
|
|||
386
src/dispatcher.ts
Normal file
386
src/dispatcher.ts
Normal file
|
|
@ -0,0 +1,386 @@
|
|||
// From a message on <root>/<endpointId>/alexaDirective to the handlers of the device, and to the one answer
|
||||
// Alex2MQTT takes for it. Every answer of the bridge passes through here, those of the 1.x message classes too, so
|
||||
// the dispatcher knows which directive is still waiting and answers for a handler that failed or stayed silent.
|
||||
import type { AnyCapability } from "./device/Capability.js";
|
||||
import type Device from "./device/Device.js";
|
||||
import { deferredResponse, errorResponse, response, sameProperty, stateReport } from "./messages/build.js";
|
||||
import { AlexaError } from "./messages/errors.js";
|
||||
import { StateBuilder } from "./messages/StateBuilder.js";
|
||||
import type { Property } from "./messages/types.js";
|
||||
import { SchemaError } from "./registry/schema.js";
|
||||
import * as topics from "./topics.js";
|
||||
import { asError } from "./transport.js";
|
||||
import type { Publisher, PublishResult } from "./transport.js";
|
||||
|
||||
/** A directive as Alex2MQTT publishes it: the directive of Alexa without endpoint.scope, the token of the user. */
|
||||
export interface RawDirective {
|
||||
header: {
|
||||
namespace: string;
|
||||
name: string;
|
||||
instance?: string;
|
||||
messageId?: string;
|
||||
correlationToken?: string;
|
||||
payloadVersion?: string;
|
||||
};
|
||||
endpoint?: { endpointId?: string; cookie?: Record<string, string> };
|
||||
payload?: unknown;
|
||||
}
|
||||
|
||||
/** Sets the properties of a message. */
|
||||
export type Fill = (state: StateBuilder) => void;
|
||||
|
||||
/** One directive, and the ways to answer it. Each method resolves with what became of the publish, none rejects. */
|
||||
export interface DirectiveContext<T = unknown> {
|
||||
readonly endpointId: string;
|
||||
readonly namespace: string;
|
||||
readonly name: string;
|
||||
/** The instance of a generic controller, "" without one. */
|
||||
readonly instance: string;
|
||||
/** "" when the directive came without one; it can then not be answered. */
|
||||
readonly correlationToken: string;
|
||||
/** The payload, checked by the descriptor of the interface. As it arrived for an interface the library only names. */
|
||||
readonly payload: T;
|
||||
readonly raw: RawDirective;
|
||||
/** Date.now() when the directive arrived. */
|
||||
readonly receivedAt: number;
|
||||
/** A Response, a StateReport or an ErrorResponse was sent. */
|
||||
readonly answered: boolean;
|
||||
/** A DeferredResponse was sent: the answer goes to <root>/<endpointId>/deferredResponse. */
|
||||
readonly deferred: boolean;
|
||||
/**
|
||||
* Answer with a Response, or with the response the interface has of its own. The context is the state of
|
||||
* device.state(), and what fill sets replaces the same property of it.
|
||||
*/
|
||||
respond(fill?: Fill, options?: { payload?: Record<string, unknown> }): Promise<PublishResult>;
|
||||
/** Answer ReportState with a StateReport, its properties as for respond(). */
|
||||
report(fill?: Fill): Promise<PublishResult>;
|
||||
/** Send a DeferredResponse now, when the answer takes longer than the 7 s Alex2MQTT waits for it. */
|
||||
defer(estimatedDeferralInSeconds?: number): Promise<PublishResult>;
|
||||
/** Answer with an ErrorResponse. An error that is not an AlexaError is sent as INTERNAL_ERROR. */
|
||||
error(type: string, message: string, extra?: Record<string, unknown>): Promise<PublishResult>;
|
||||
error(err: Error): Promise<PublishResult>;
|
||||
}
|
||||
|
||||
/** What a handler returns is awaited and otherwise ignored; what it throws answers the directive. */
|
||||
export type DirectiveHandler<T = unknown> = (ctx: DirectiveContext<T>) => unknown;
|
||||
|
||||
/** The clock of the watchdog, replaced in tests. */
|
||||
export interface Timers {
|
||||
setTimeout(run: () => void, ms: number): unknown;
|
||||
clearTimeout(timer: unknown): void;
|
||||
}
|
||||
|
||||
// unref: a directive that waits for its answer does not keep a process alive that is otherwise done
|
||||
const processTimers: Timers = {
|
||||
setTimeout(run, ms) {
|
||||
const timer = setTimeout(run, ms);
|
||||
timer.unref();
|
||||
return timer;
|
||||
},
|
||||
clearTimeout(timer) {
|
||||
clearTimeout(timer as ReturnType<typeof setTimeout>);
|
||||
},
|
||||
};
|
||||
|
||||
/** What the dispatcher needs of its bridge. */
|
||||
export interface DispatcherOptions {
|
||||
rootTopic: string;
|
||||
/** Where the answers go. */
|
||||
publisher: Publisher;
|
||||
getDevice(endpointId: string): Device | undefined;
|
||||
log(message: string, detail?: unknown): void;
|
||||
/** Reports an error: the "error" event of the bridge. */
|
||||
fail(err: Error): void;
|
||||
emit(event: string, ...args: unknown[]): void;
|
||||
answerWithinMs?: number;
|
||||
answerUnknownEndpoints?: boolean;
|
||||
timers?: Timers;
|
||||
}
|
||||
|
||||
/** Alex2MQTT gives up on a directive after DIRECTIVE_BUDGET_MS: the answer of the watchdog has to be there before. */
|
||||
export const ANSWER_WITHIN_MS = topics.DIRECTIVE_BUDGET_MS - 500;
|
||||
|
||||
// How long a directive is remembered: its messageId, to drop the copy of a mirroring broker, and that it was
|
||||
// answered, to drop a second answer. A deferred answer may take this long and still find its directive.
|
||||
const REMEMBERED_MS = 60_000;
|
||||
|
||||
// A directive on its way to its answer
|
||||
interface Exchange {
|
||||
readonly endpointId: string;
|
||||
readonly namespace: string;
|
||||
readonly name: string;
|
||||
readonly correlationToken: string;
|
||||
readonly receivedAt: number;
|
||||
answered: boolean;
|
||||
deferred: boolean;
|
||||
/** Set while the watchdog waits for the first answer. */
|
||||
watchdog?: unknown;
|
||||
}
|
||||
|
||||
// A directive no handler can be called for. A device with a 1.x listener answers it by itself.
|
||||
class RoutingError extends AlexaError {}
|
||||
|
||||
const key = (endpointId: string, id: string): string => `${endpointId}\n${id}`;
|
||||
|
||||
class Context implements DirectiveContext<any> {
|
||||
payload: unknown;
|
||||
/** The capability the directive is for; none for ReportState. */
|
||||
capability?: AnyCapability;
|
||||
|
||||
constructor(
|
||||
private readonly dispatcher: Dispatcher,
|
||||
private readonly device: Device,
|
||||
private readonly exchange: Exchange,
|
||||
readonly raw: RawDirective
|
||||
) {
|
||||
this.payload = raw.payload ?? {};
|
||||
}
|
||||
|
||||
get endpointId(): string { return this.exchange.endpointId; }
|
||||
get namespace(): string { return this.exchange.namespace; }
|
||||
get name(): string { return this.exchange.name; }
|
||||
get instance(): string { return this.raw.header.instance ?? ""; }
|
||||
get correlationToken(): string { return this.exchange.correlationToken; }
|
||||
get receivedAt(): number { return this.exchange.receivedAt; }
|
||||
get answered(): boolean { return this.exchange.answered; }
|
||||
get deferred(): boolean { return this.exchange.deferred; }
|
||||
get reportState(): boolean { return this.namespace === "Alexa" && this.name === "ReportState"; }
|
||||
|
||||
async respond(fill?: Fill, options: { payload?: Record<string, unknown> } = {}): Promise<PublishResult> {
|
||||
const { endpointId, correlationToken } = this;
|
||||
const own = this.capability?.descriptor.responseFor?.(this.name);
|
||||
const payload = own?.payload ? own.payload.parse(options.payload ?? {}, "payload") : options.payload;
|
||||
const context = this.state(fill);
|
||||
return this.answer(response({ endpointId, correlationToken, namespace: own?.namespace, name: own?.name, payload, context }));
|
||||
}
|
||||
|
||||
async report(fill?: Fill): Promise<PublishResult> {
|
||||
if (!this.reportState) {
|
||||
throw new Error(`report() answers ReportState with a StateReport: answer ${this.namespace}.${this.name} with respond()`);
|
||||
}
|
||||
const { endpointId, correlationToken } = this;
|
||||
return this.answer(stateReport({ endpointId, correlationToken, context: this.state(fill) }));
|
||||
}
|
||||
|
||||
defer(estimatedDeferralInSeconds?: number): Promise<PublishResult> {
|
||||
const { endpointId, correlationToken } = this;
|
||||
if (this.capability && !this.capability.descriptor.deferrable) this.dispatcher.noteDeferral(this.namespace);
|
||||
// Always where the first answer goes: a second DeferredResponse is refused there
|
||||
const topic = topics.response(this.dispatcher.rootTopic, endpointId);
|
||||
return this.dispatcher.send(topic, deferredResponse({ endpointId, correlationToken, estimatedDeferralInSeconds }));
|
||||
}
|
||||
|
||||
error(typeOrError: string | Error, message = "", extra: Record<string, unknown> = {}): Promise<PublishResult> {
|
||||
const { endpointId, correlationToken } = this;
|
||||
let error: AlexaError;
|
||||
if (typeOrError instanceof AlexaError) error = typeOrError;
|
||||
else if (typeOrError instanceof Error) error = new AlexaError("INTERNAL_ERROR", typeOrError.message);
|
||||
else error = new AlexaError(typeOrError, message, extra);
|
||||
const { type, alexaMessage, namespace } = error;
|
||||
return this.answer(errorResponse({ endpointId, correlationToken, type, message: alexaMessage, extra: error.extra, namespace }));
|
||||
}
|
||||
|
||||
// The state of the device, and over it what the handler says about this directive
|
||||
private state(fill?: Fill): Property[] {
|
||||
const whole = new StateBuilder();
|
||||
this.device.stateProvider?.(whole);
|
||||
const own = new StateBuilder();
|
||||
fill?.(own);
|
||||
return [...whole.context.filter((property) => !own.context.some((other) => sameProperty(property, other))), ...own.context];
|
||||
}
|
||||
|
||||
private answer(message: object): Promise<PublishResult> {
|
||||
const topic = this.deferred ? topics.deferred : topics.response;
|
||||
return this.dispatcher.send(topic(this.dispatcher.rootTopic, this.endpointId), message);
|
||||
}
|
||||
}
|
||||
|
||||
export class Dispatcher {
|
||||
readonly rootTopic: string;
|
||||
/**
|
||||
* What the devices of the bridge publish through. An answer to a directive that waits is let through once, and a
|
||||
* DeferredResponse once before it; everything else passes.
|
||||
*/
|
||||
readonly publisher: Publisher = { publish: (topic, message) => this.publish(topic, message) };
|
||||
private readonly answerWithinMs: number;
|
||||
private readonly timers: Timers;
|
||||
// Both oldest first. The directives by endpoint and correlationToken, when they arrived by endpoint and messageId.
|
||||
private readonly exchanges = new Map<string, Exchange>();
|
||||
private readonly arrived = new Map<string, number>();
|
||||
private readonly deferralNoted = new Set<string>();
|
||||
|
||||
constructor(private readonly options: DispatcherOptions) {
|
||||
const { answerWithinMs = ANSWER_WITHIN_MS } = options;
|
||||
if (typeof answerWithinMs !== "number" || !(answerWithinMs >= 0)) {
|
||||
throw new Error(`answerWithinMs is ${String(answerWithinMs)}: pass the milliseconds a handler has to answer in, or 0 for no limit`);
|
||||
}
|
||||
this.rootTopic = options.rootTopic;
|
||||
this.answerWithinMs = answerWithinMs;
|
||||
this.timers = options.timers ?? processTimers;
|
||||
}
|
||||
|
||||
/** Publish an answer; one that is not published is reported to the bridge. */
|
||||
async send(topic: string, message: object): Promise<PublishResult> {
|
||||
const result = await this.publish(topic, message);
|
||||
if (!result.ok) this.options.fail(result.error);
|
||||
return result;
|
||||
}
|
||||
|
||||
/** defer() for an interface Amazon documents no DeferredResponse for: said once, the DeferredResponse is sent. */
|
||||
noteDeferral(namespace: string): void {
|
||||
if (this.deferralNoted.has(namespace)) return;
|
||||
this.deferralNoted.add(namespace);
|
||||
this.options.log(`warning: Amazon documents no DeferredResponse for ${namespace}, Alexa may not wait for the answer`);
|
||||
}
|
||||
|
||||
/** The text of a message on the directive topic of endpointId. Resolves when the handlers are done. */
|
||||
async dispatch(endpointId: string, text: string): Promise<void> {
|
||||
const { log, emit } = this.options;
|
||||
let raw: RawDirective;
|
||||
try {
|
||||
raw = JSON.parse(text);
|
||||
} catch (err) {
|
||||
// Without a correlationToken there is nothing to answer
|
||||
log(`the directive for ${endpointId} is dropped: it is not JSON`, err);
|
||||
return;
|
||||
}
|
||||
if (typeof raw !== "object" || raw === null || typeof raw.header !== "object" || raw.header === null) {
|
||||
log(`the directive for ${endpointId} is dropped: it has no header`);
|
||||
return;
|
||||
}
|
||||
const { namespace, name, messageId } = raw.header;
|
||||
const correlationToken = typeof raw.header.correlationToken === "string" ? raw.header.correlationToken : "";
|
||||
const receivedAt = Date.now();
|
||||
this.forget(receivedAt);
|
||||
if (typeof messageId === "string") {
|
||||
if (this.arrived.has(key(endpointId, messageId))) {
|
||||
log(`the directive ${messageId} for ${endpointId} is dropped: it arrived before`);
|
||||
return;
|
||||
}
|
||||
this.arrived.set(key(endpointId, messageId), receivedAt);
|
||||
}
|
||||
|
||||
const device = this.options.getDevice(endpointId);
|
||||
if (!device) {
|
||||
log(`No device found for endpointId: ${endpointId}`);
|
||||
emit("unknownEndpoint", { endpointId, namespace, name });
|
||||
// Off by default: the endpoint may belong to another bridge on the same root topic
|
||||
if (this.options.answerUnknownEndpoints) {
|
||||
const message = `${endpointId} is not an endpoint of this bridge`;
|
||||
await this.send(topics.response(this.rootTopic, endpointId), errorResponse({ endpointId, correlationToken, type: "NO_SUCH_ENDPOINT", message }));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const exchange: Exchange = { endpointId, namespace, name, correlationToken, receivedAt, answered: false, deferred: false };
|
||||
if (correlationToken) {
|
||||
this.exchanges.set(key(endpointId, correlationToken), exchange);
|
||||
this.watch(exchange);
|
||||
}
|
||||
const ctx = new Context(this, device, exchange, raw);
|
||||
emit("directive", { endpointId, namespace, name });
|
||||
|
||||
// The 1.x listeners first, called one by one: emit() would let what one of them throws out, and lose what an
|
||||
// async one rejects with
|
||||
const event = ctx.reportState ? "ReportState" : "Event";
|
||||
const listeners = device.rawListeners(event);
|
||||
const running = listeners.map((listener) => this.isolated(ctx, () => listener.call(device, raw, ...(ctx.reportState ? [] : [namespace]))));
|
||||
running.push(this.isolated(ctx, () => this.route(device, ctx)(ctx), listeners.length > 0));
|
||||
await Promise.all(running);
|
||||
}
|
||||
|
||||
// The handler for the directive, the payload of ctx checked for it
|
||||
private route(device: Device, ctx: Context): DirectiveHandler<any> {
|
||||
const { endpointId, namespace, name, instance } = ctx;
|
||||
const refused = (type: string, problem: string): RoutingError => new RoutingError(type, problem);
|
||||
if (ctx.reportState) {
|
||||
if (device.reportStateHandler) return device.reportStateHandler;
|
||||
if (device.stateProvider) return (context) => context.report();
|
||||
throw refused("INVALID_DIRECTIVE", `${endpointId} has no handler for ReportState: register one with onReportState() or state() of the device`);
|
||||
}
|
||||
const capability = device.capability(namespace, instance);
|
||||
const declared = `${namespace}${instance ? ` "${instance}"` : ""}`;
|
||||
if (!capability) throw refused("INVALID_DIRECTIVE", `${declared} is not declared on ${endpointId}`);
|
||||
ctx.capability = capability;
|
||||
const directive = capability.descriptor.directives[name];
|
||||
// An interface the library only names describes no directive: its handlers get the payload as it arrived
|
||||
if (!directive && capability.descriptor.tier !== 3) throw refused("INVALID_DIRECTIVE", `${name} is not a directive of ${namespace}`);
|
||||
if (directive?.when && !directive.when(capability)) {
|
||||
throw refused("INVALID_DIRECTIVE", `${declared} as ${endpointId} declares it does not take ${name}`);
|
||||
}
|
||||
const handler = capability.handlerFor(name) ?? device.directiveHandler;
|
||||
if (!handler) {
|
||||
throw refused("INVALID_DIRECTIVE", `${endpointId} has no handler for ${namespace}.${name}: register one with on("${name}", handler) of the capability`);
|
||||
}
|
||||
try {
|
||||
if (directive) ctx.payload = directive.payload.parse(ctx.payload, "payload");
|
||||
} catch (err) {
|
||||
throw err instanceof SchemaError ? refused("INVALID_VALUE", err.message) : err;
|
||||
}
|
||||
return handler;
|
||||
}
|
||||
|
||||
// Runs a listener or a handler. What it throws or rejects with answers the directive and goes no further.
|
||||
private async isolated(ctx: Context, run: () => unknown, answersItself = false): Promise<void> {
|
||||
try {
|
||||
await run();
|
||||
} catch (thrown) {
|
||||
if (thrown instanceof RoutingError && answersItself) return;
|
||||
const err = asError(thrown);
|
||||
// An AlexaError is the answer the handler chose. Anything else is a fault in it, and so is an answer too many.
|
||||
if (!(err instanceof AlexaError) || ctx.answered) this.options.fail(err);
|
||||
if (!ctx.answered) await ctx.error(err);
|
||||
}
|
||||
}
|
||||
|
||||
private watch(exchange: Exchange): void {
|
||||
const within = this.answerWithinMs;
|
||||
if (within === 0) return;
|
||||
exchange.watchdog = this.timers.setTimeout(() => {
|
||||
exchange.watchdog = undefined;
|
||||
const { endpointId, namespace, name, correlationToken } = exchange;
|
||||
const message = `no answer within ${within / 1000} s`;
|
||||
this.options.emit("unanswered", { endpointId, namespace, name, correlationToken });
|
||||
this.options.fail(new Error(
|
||||
`${endpointId}: ${namespace}.${name} got ${message} and is answered with INTERNAL_ERROR. `
|
||||
+ "Answer in the handler, or defer() first when the device takes longer"
|
||||
));
|
||||
void this.send(topics.response(this.rootTopic, endpointId), errorResponse({ endpointId, correlationToken, type: "INTERNAL_ERROR", message }));
|
||||
}, within);
|
||||
}
|
||||
|
||||
private publish(topic: string, message: object): Promise<PublishResult> {
|
||||
const { event } = message as { event?: { header?: { name?: string; correlationToken?: unknown }; endpoint?: { endpointId?: string } } };
|
||||
const token = event?.header?.correlationToken;
|
||||
const exchange = typeof token === "string" ? this.exchanges.get(key(event?.endpoint?.endpointId ?? "", token)) : undefined;
|
||||
if (exchange) {
|
||||
const deferral = event?.header?.name === "DeferredResponse";
|
||||
const { endpointId, namespace, name } = exchange;
|
||||
if (exchange.answered || (deferral && exchange.deferred)) {
|
||||
const was = exchange.answered ? "answered" : "deferred";
|
||||
const error = new Error(`nothing was published to ${topic}: ${namespace}.${name} for ${endpointId} was ${was} before, and Alex2MQTT takes one answer`);
|
||||
return Promise.resolve({ ok: false, topic, error });
|
||||
}
|
||||
if (deferral) exchange.deferred = true;
|
||||
else exchange.answered = true;
|
||||
if (exchange.watchdog !== undefined) {
|
||||
this.timers.clearTimeout(exchange.watchdog);
|
||||
exchange.watchdog = undefined;
|
||||
}
|
||||
}
|
||||
return this.options.publisher.publish(topic, message);
|
||||
}
|
||||
|
||||
// Drops what is older than REMEMBERED_MS. A directive the watchdog still waits for is kept.
|
||||
private forget(now: number): void {
|
||||
const old = (since: number): boolean => now - since > REMEMBERED_MS;
|
||||
for (const [id, since] of this.arrived) {
|
||||
if (!old(since)) break;
|
||||
this.arrived.delete(id);
|
||||
}
|
||||
for (const [id, exchange] of this.exchanges) {
|
||||
if (!old(exchange.receivedAt)) break;
|
||||
if (exchange.watchdog === undefined) this.exchanges.delete(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -39,6 +39,9 @@ export * as topics from "./topics.js";
|
|||
export { MemoryPublisher } from "./transport.js";
|
||||
export type { Publisher, PublishResult } from "./transport.js";
|
||||
|
||||
// Directives: what a handler is given
|
||||
export type { DirectiveContext, DirectiveHandler, Fill, RawDirective, Timers } from "./dispatcher.js";
|
||||
|
||||
// 1.x
|
||||
export { AlexaInterface } from "./compat/AlexaInterface.js";
|
||||
export type { SupportedMode } from "./compat/AlexaInterface.js";
|
||||
|
|
|
|||
|
|
@ -123,7 +123,8 @@ export interface ChangeReportFields extends Envelope {
|
|||
context?: readonly Property[];
|
||||
}
|
||||
|
||||
const sameProperty = (a: Property, b: Property): boolean =>
|
||||
/** The same property of the same instance, whatever its value. */
|
||||
export const sameProperty = (a: Property, b: Property): boolean =>
|
||||
a.namespace === b.namespace && a.name === b.name && (a.instance ?? "") === (b.instance ?? "");
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -28,5 +28,8 @@ export const response = (root: string, endpointId: string): string => `${root}/$
|
|||
/** Where the answer goes once a DeferredResponse was sent for the directive. */
|
||||
export const deferred = (root: string, endpointId: string): string => `${root}/${endpointId}/deferredResponse`;
|
||||
|
||||
/** How long Alex2MQTT waits for the answer to a directive before it tells Alexa that the endpoint did not answer. */
|
||||
export const DIRECTIVE_BUDGET_MS = 7000;
|
||||
|
||||
/** Where every ChangeReport of the root goes: the backend adds the user's token and posts it to Alexa. */
|
||||
export const changeReport = (root: string): string => `${root}/changeReport`;
|
||||
|
|
|
|||
|
|
@ -10,7 +10,8 @@ export interface Publisher {
|
|||
publish(topic: string, message: object): Promise<PublishResult>;
|
||||
}
|
||||
|
||||
const asError = (err: unknown): Error => (err instanceof Error ? err : new Error(String(err)));
|
||||
/** What was thrown, as an Error. */
|
||||
export const asError = (err: unknown): Error => (err instanceof Error ? err : new Error(String(err)));
|
||||
|
||||
/**
|
||||
* Publishes to the broker through the client the bridge has at the time: a new one after disconnect() and connect(),
|
||||
|
|
@ -41,7 +42,7 @@ export class MqttPublisher implements Publisher {
|
|||
* Keeps what it is asked to publish, for tests and dry runs without a broker:
|
||||
*
|
||||
* const sent = new MemoryPublisher();
|
||||
* device.publisher = sent;
|
||||
* device.publisher = sent; // or new Alex2MQTT(..., { publisher: sent }) and bridge.receive()
|
||||
* await device.getStatusMessage(token, true).addPowerControllerProp(PowerController.ON).send();
|
||||
* sent.published[0] // { topic: "<root>/<endpointId>/alexaResponce", message: { event, context } }
|
||||
*/
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue