Skip to content

Commit

Permalink
add disconnected request and samples
Browse files Browse the repository at this point in the history
  • Loading branch information
chuongnguyen committed Oct 1, 2024
1 parent ce5b57a commit 26e76f8
Show file tree
Hide file tree
Showing 6 changed files with 345 additions and 4 deletions.
41 changes: 41 additions & 0 deletions sdk/web-pubsub/web-pubsub-express/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,11 @@ const { WebPubSubEventHandler } = require("@azure/web-pubsub-express");
const handler = new WebPubSubEventHandler("chat", {
handleConnect: (req, res) => {
if (req.context.clientProtocol === "mqtt") { // return mqtt response when request is of MQTT kind
// get connect request as mqtt request and print it
const mqttRequest = req as MqttConnectRequest;
console.log(mqttRequest);

// auth the connection and return mqtt response
res.success({
userId: "user1",
mqtt: { userProperties: [{ name: "a", value: "b" }] },
Expand Down Expand Up @@ -209,7 +214,13 @@ const handler = new WebPubSubEventHandler("chat", {
handleConnect: (req, res) => {
// auth the connection and reject the connection if auth failed
if (req.context.clientProtocol === "mqtt") { // return mqtt error response when request is of MQTT kind
// get connect request as mqtt request and print it
const mqttRequest = req as MqttConnectRequest;
console.log(mqttRequest);

// auth the connection and return mqtt failure response
res.fail(401, "Not Authorized");

// Or use below method for more fine-grained control over the MQTT return code
// res.failWith({ mqtt: { code: MqttV500ConnectReasonCode.NotAuthorized } });
} else res.success();
Expand All @@ -226,6 +237,36 @@ app.listen(3000, () =>
);
```

### Handle the `onDisconnected` for mqtt request

```js
const express = require("express");

const { WebPubSubEventHandler } = require("@azure/web-pubsub-express");
const handler = new WebPubSubEventHandler("chat", {
onDisconnected: (disconnectedRequest) => {
if (disconnectedRequest.context.clientProtocol === "mqtt") {
// get disconnect request as mqtt request and print it
const mqttRequest = disconnectedRequest as MqttDisconnectedRequest;
console.log(mqttRequest.mqtt);
// Your onDisconnected logic goes here
} else {
console.log(disconnectedRequest);
// Your onDisconnected logic goes here
}
},
allowedEndpoints: ["https://<yourAllowedService>.webpubsub.azure.com"]
});

const app = express();

app.use(handler.getMiddleware());

app.listen(3000, () =>
console.log(`Azure WebPubSub Upstream ready at http://localhost:3000${handler.path}`)
);
```

### Only allow specified endpoints

```js
Expand Down
50 changes: 50 additions & 0 deletions sdk/web-pubsub/web-pubsub-express/review/web-pubsub-express.api.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,56 @@ export interface MqttConnectResponseProperties {
userProperties?: MqttUserProperty[];
}

// @public
export interface MqttDisconnectedProperties {
disconnectPacket: MqttDisconnectPacket;
initiatedByClient: boolean;
}

// @public
export interface MqttDisconnectedRequest extends DisconnectedRequest {
mqtt: MqttDisconnectedProperties;
}

// @public
export interface MqttDisconnectPacket {
code: MqttDisconnectReasonCode;
userProperties?: MqttUserProperty[];
}

// @public
export enum MqttDisconnectReasonCode {
AdministrativeAction = 152,
ConnectionRateExceeded = 159,
DisconnectWithWillMessage = 4,
ImplementationSpecificError = 131,
KeepAliveTimeout = 141,
MalformedPacket = 129,
MaximumConnectTime = 160,
MessageRateTooHigh = 150,
NormalDisconnection = 0,
NotAuthorized = 135,
PacketTooLarge = 149,
PayloadFormatInvalid = 153,
ProtocolError = 130,
QosNotSupported = 155,
QuotaExceeded = 151,
ReceiveMaximumExceeded = 147,
RetainNotSupported = 154,
ServerBusy = 137,
ServerMoved = 157,
ServerShuttingDown = 139,
SessionTakenOver = 142,
SharedSubscriptionsNotSupported = 158,
SubscriptionIdentifiersNotSupported = 161,
TopicAliasInvalid = 148,
TopicFilterInvalid = 143,
TopicNameInvalid = 144,
UnspecifiedError = 128,
UseAnotherServer = 156,
WildcardSubscriptionsNotSupported = 162
}

// @public
export interface MqttUserProperty {
name: string;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import type {
MqttConnectErrorResponse,
MqttConnectionContextProperties,
ConnectErrorResponse,
MqttDisconnectedRequest,
} from "./cloudEventsProtocols.js";
import { MqttV311ConnectReturnCode } from "./enum/MqttErrorCodes/mqttV311ConnectReturnCode.js";
import { MqttV500ConnectReasonCode } from "./enum/MqttErrorCodes/mqttV500ConnectReasonCode.js";
Expand Down Expand Up @@ -452,10 +453,9 @@ export class CloudEventsDispatcher {
case EventType.Disconnected: {
// for unblocking events, we responds to the service as early as possible
response.end();
const disconnectedRequest = await readSystemEventRequest<DisconnectedRequest>(
request,
origin,
);
const disconnectedRequest = isMqtt
? await readSystemEventRequest<MqttDisconnectedRequest>(request, origin)
: await readSystemEventRequest<DisconnectedRequest>(request, origin);
logger.verbose(disconnectedRequest);
this.eventHandler.onDisconnected!(disconnectedRequest);
return true;
Expand Down
39 changes: 39 additions & 0 deletions sdk/web-pubsub/web-pubsub-express/src/cloudEventsProtocols.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

import { MqttDisconnectReasonCode } from "./enum/MqttErrorCodes/mqttDisconnectReasonCode.js";
import { MqttV311ConnectReturnCode } from "./enum/MqttErrorCodes/mqttV311ConnectReturnCode.js";
import { MqttV500ConnectReasonCode } from "./enum/MqttErrorCodes/mqttV500ConnectReasonCode.js";

Expand Down Expand Up @@ -320,6 +321,44 @@ export interface DisconnectedRequest {
reason?: string;
}

/**
* Request for the disconnected event.
*/
export interface MqttDisconnectedRequest extends DisconnectedRequest {
/**
* The MQTT specific properties in the MQTT disconnected event request.
*/
mqtt: MqttDisconnectedProperties;
}

/**
* The properties of an MQTT disconnected event.
*/
export interface MqttDisconnectedProperties {
/**
* The MQTT disconnect packet.
*/
disconnectPacket: MqttDisconnectPacket;
/**
* Whether the disconnection is initiated by the client.
*/
initiatedByClient: boolean;
}

/**
* The properties of the MQTT DISCONNECT packet.
*/
export interface MqttDisconnectPacket {
/**
* The MQTT disconnect return code.
*/
code: MqttDisconnectReasonCode;
/**
* The user properties in the MQTT disconnect packet.
*/
userProperties?: MqttUserProperty[];
}

/**
* The handler to set connect event response
*/
Expand Down
Loading

0 comments on commit 26e76f8

Please sign in to comment.