Express için Azure Web PubSub CloudEvents işleyicileri

Azure Web PubSub hizmeti , geliştiricilerin gerçek zamanlı özellikler ve yayımlama-abone olma düzeniyle kolayca web uygulamaları oluşturmalarına yardımcı olan Azure tarafından yönetilen bir hizmettir. Sunucu ve istemciler arasında veya istemciler arasında gerçek zamanlı yayımlama-abone olma mesajlaşması gerektiren tüm senaryolar Azure Web PubSub hizmetini kullanabilir. Genellikle sunucudan yoklama veya HTTP istekleri gönderme gerektiren geleneksel gerçek zamanlı özellikler, Azure Web PubSub hizmetini de kullanabilir.

WebSocket bağlantısı bağlandığında, Web PubSub hizmeti bağlantı yaşam döngüsünü ve iletileri CloudEvents biçiminde olaylara dönüştürür. Bu kitaplık, aşağıdaki diyagramda gösterildiği gibi WebSocket bağlantısının yaşam döngüsünü ve iletilerini temsil eden olayları işlemek için hızlı bir ara yazılım sağlar:

bulut olayları

Burada kullanılan terimlerle ilgili detaylar Ana kavramlar bölümünde açıklanmıştır.

Kaynak kodu | Paket (NPM) | API başvuru belgeleri | Ürün belgeleri | Örnekleri

Başlangıç Yapmak

Şu anda desteklenen ortamlar

Prerequisites

1. Paketi yükleyin @azure/web-pubsub-express

npm install @azure/web-pubsub-express

2. Bir WebPubSubEventHandler oluşturun

import { WebPubSubEventHandler } from "@azure/web-pubsub-express";
import express from "express";

const handler = new WebPubSubEventHandler("chat");

const app = express();

app.use(handler.getMiddleware());

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

Temel kavramlar

Bağlantı

Bir bağlantı, istemci veya istemci bağlantısı olarak da bilinir ve Web PubSub hizmetine bağlı bireysel bir WebSocket bağlantısını temsil eder. Başarılı bağlandığında, Web PubSub servisi tarafından bu bağlantıya benzersiz bir bağlantı kimliği atanır.

Merkez

Hub, bir dizi istemci bağlantısı için mantıksal bir kavramdır. Genellikle bir hub'ı tek bir amaç için kullanırsınız, örneğin bir sohbet merkezi veya bir bildirim merkezi. İstemci bağlantısı oluşturulduğunda bir hub'a bağlanır ve kullanım ömrü boyunca bu hub'a aittir. Farklı uygulamalar, farklı hub adlarını kullanarak bir Azure Web PubSub hizmetini paylaşabilir.

Grup

Grup, hub'a yönelik bağlantıların bir alt kümesidir. Bir gruba istemci bağlantısı ekleyebilir veya istemci bağlantısını istediğiniz zaman gruptan kaldırabilirsiniz. Örneğin, bir istemci bir sohbet odasına katıldığında veya bir istemci sohbet odasından ayrıldığında, bu sohbet odası bir grup olarak kabul edilebilir. bir istemci birden çok gruba katılabilir ve bir grup birden çok istemci içerebilir.

User

Web PubSub bağlantıları tek bir kullanıcıya ait olabilir. Bir kullanıcının birden çok bağlantısı olabilir; örneğin, tek bir kullanıcı birden çok cihaza veya birden çok tarayıcı sekmesine bağlandığında.

İstemci Olayları

Olaylar, bir müşteri bağlantısının yaşam döngüsü boyunca oluşturulur. Örneğin, basit bir WebSocket istemci bağlantısı hizmete bağlanmaya çalıştığında bir connect olay, hizmete başarıyla bağlandığında bir connected olay, hizmete mesaj gönderdiğinde ve message hizmetten koptuğunda bir disconnected olay oluşturur.

Olay İşleyicisi

Olay işleyicisi, istemci olaylarını yönetmek için mantığı içerir. Olay işleyicisinin önceden portal veya Azure CLI üzerinden hizmette kayıtlı ve yapılandırılması gerekir. Olay işleyici mantığını barındırmak genellikle sunucu tarafı olarak kabul edilir.

Examples

connect isteğini işle ve <userId> atamasını yap

import { WebPubSubEventHandler } from "@azure/web-pubsub-express";
import express from "express";

const handler = new WebPubSubEventHandler("chat", {
  handleConnect: (req, res) => {
    // auth the connection and set the userId of the connection
    res.success({
      userId: "<userId>",
    });
  },
  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}`),
);

İsteği connect yönetin ve doğrulama başarısız olursa bağlantıyı reddedin

import { WebPubSubEventHandler } from "@azure/web-pubsub-express";
import express from "express";

const handler = new WebPubSubEventHandler("chat", {
  handleConnect: (req, res) => {
    // auth the connection and reject the connection if auth failed
    res.fail(401, "Unauthorized");
    // the following method is also a valid approach
    // res.failWith({ code: 401, detail: "Unauthorized" });
  },
  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}`),
);

İsteği connected ele alın

import { WebPubSubEventHandler } from "@azure/web-pubsub-express";
import express from "express";

const handler = new WebPubSubEventHandler("chat", {
  onConnected: (connectedRequest) => {
    // Your onConnected 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}`),
);

İsteği onGroupJoined ele alın

import { WebPubSubEventHandler } from "@azure/web-pubsub-express";
import express from "express";

const handler = new WebPubSubEventHandler("chat", {
  onGroupJoined: (groupJoinedRequest) => {
    console.log(
      `Connection ${groupJoinedRequest.context.connectionId} joined group ${groupJoinedRequest.group}`,
    );
  },
  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}`),
);

İsteği onGroupLeft ele alın

import { WebPubSubEventHandler } from "@azure/web-pubsub-express";
import express from "express";

const handler = new WebPubSubEventHandler("chat", {
  onGroupLeft: (groupLeftRequest) => {
    console.log(
      `Connection ${groupLeftRequest.context.connectionId} left group ${groupLeftRequest.group}`,
    );
  },
  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}`),
);

İsteği onDisconnected ele alın

import { WebPubSubEventHandler } from "@azure/web-pubsub-express";
import express from "express";

const handler = new WebPubSubEventHandler("chat", {
  onDisconnected: (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}`),
);

Mqtt talebini yönetin connect ve atama <userId> ile <mqtt> özellikleri

import { WebPubSubEventHandler, MqttConnectRequest } from "@azure/web-pubsub-express";
import express from "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" }] },
      });
    } else {
      res.success({
        userId: "user1",
      });
    }
  },
  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}`),
);

Mqtt talebini yönetin connect ve doğrulama başarısız olursa bağlantıyı reddedin

import { WebPubSubEventHandler, MqttConnectRequest } from "@azure/web-pubsub-express";
import express from "express";

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();
  },
  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}`),
);

For mqtt talebini yönetin onDisconnected

import { WebPubSubEventHandler, MqttDisconnectedRequest } from "@azure/web-pubsub-express";
import express from "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}`),
);

Yalnızca belirtilen uç noktalara izin ver

import { WebPubSubEventHandler } from "@azure/web-pubsub-express";
import express from "express";

const handler = new WebPubSubEventHandler("chat", {
  allowedEndpoints: [
    "https://<yourAllowedService1>.webpubsub.azure.com",
    "https://<yourAllowedService2>.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}`),
);

Özel olay işleyici yolunu ayarlama

import { WebPubSubEventHandler } from "@azure/web-pubsub-express";
import express from "express";

const handler = new WebPubSubEventHandler("chat", {
  path: "/customPath1",
});

const app = express();

app.use(handler.getMiddleware());

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

Bağlantı durumunu ayarlama ve okuma

import { WebPubSubEventHandler } from "@azure/web-pubsub-express";
import express from "express";

const handler = new WebPubSubEventHandler("chat", {
  handleConnect(req, res) {
    // You can set the state for the connection, it lasts throughout the lifetime of the connection
    res.setState("calledTime", 1);
    res.success();
  },
  handleUserEvent(req, res) {
    const calledTime = req.context.states.calledTime++;
    console.log(calledTime);
    // You can also set the state here
    res.setState("calledTime", calledTime);
    res.success();
  },
});

const app = express();

app.use(handler.getMiddleware());

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

Troubleshooting

Günlükleri etkinleştirme

Loglamayı etkinleştirmek, hatalarla ilgili yararlı bilgilerin ortaya çıkmasına yardımcı olabilir. HTTP isteklerinin ve yanıtlarının günlüğünü görmek için ortam değişkenini AZURE_LOG_LEVEL olarak infoayarlayın.

export AZURE_LOG_LEVEL=verbose

Alternatif olarak, çalışma zamanında setLogLevel@azure/logger çağrılarak günlük tutma etkinleştirilebilir.

import { setLogLevel } from "@azure/logger";

setLogLevel("info");

Günlükleri etkinleştirme hakkında daha ayrıntılı yönergeler için @azure/günlükçü paketi belgelerine bakabilirsiniz.

Canlı İzleme

Canlı trafiği görüntülemek için Web PubSub hizmet portalından Canlı İzleme'yi kullanın.

Sonraki Adımlar

Bu kütüphaneyi nasıl kullanacağınıza dair ayrıntılı örnekler için lütfen samples dizinine göz atın.

Contributing

Bu kütüphaneye katkıda bulunmak isterseniz, kodun nasıl oluşturulacağı ve test edileceği hakkında daha fazla bilgi edinmek için lütfen katkı rehberi adresini okuyun.