Repository: soketi/pws Branch: 1.x Commit: 5d188786beaf Files: 116 Total size: 573.9 KB Directory structure: gitextract_uh224e27/ ├── .dockerignore ├── .editorconfig ├── .eslintrc.js ├── .gitattributes ├── .github/ │ ├── FUNDING.yml │ ├── ISSUE_TEMPLATE/ │ │ ├── bug-report---.md │ │ └── feature-request-🚀.md │ ├── dependabot.yml │ ├── stale.yml │ └── workflows/ │ ├── benchmark.yml │ ├── ci.yml │ ├── docker-commit.yml │ ├── docker-latest-tag.yml │ ├── docker-release-tag.yml │ └── release-npm.yml ├── .gitignore ├── .npmignore ├── CONTRIBUTING.md ├── Dockerfile ├── Dockerfile.awslocal ├── Dockerfile.debian ├── Dockerfile.distroless ├── LICENSE ├── README.md ├── SECURITY.md ├── babel.config.js ├── benchmark/ │ ├── ci-horizontal.js │ ├── ci-local.js │ ├── composer.json │ └── send ├── bin/ │ ├── pm2.js │ └── server.js ├── docker-compose.yml ├── jest.config.js ├── new-connection.sh ├── package.json ├── src/ │ ├── adapters/ │ │ ├── adapter-interface.ts │ │ ├── adapter.ts │ │ ├── cluster-adapter.ts │ │ ├── horizontal-adapter.ts │ │ ├── index.ts │ │ ├── local-adapter.ts │ │ ├── nats-adapter.ts │ │ └── redis-adapter.ts │ ├── app-managers/ │ │ ├── app-manager-interface.ts │ │ ├── app-manager.ts │ │ ├── array-app-manager.ts │ │ ├── base-app-manager.ts │ │ ├── dynamodb-app-manager.ts │ │ ├── index.ts │ │ ├── mysql-app-manager.ts │ │ ├── postgres-app-manager.ts │ │ └── sql-app-manager.ts │ ├── app.ts │ ├── cache-managers/ │ │ ├── cache-manager-interface.ts │ │ ├── cache-manager.ts │ │ ├── index.ts │ │ ├── memory-cache-manager.ts │ │ └── redis-cache-manager.ts │ ├── channels/ │ │ ├── encrypted-private-channel-manager.ts │ │ ├── index.ts │ │ ├── presence-channel-manager.ts │ │ ├── private-channel-manager.ts │ │ └── public-channel-manager.ts │ ├── cli/ │ │ ├── cli.ts │ │ └── index.ts │ ├── http-handler.ts │ ├── index.ts │ ├── job.ts │ ├── log.ts │ ├── message.ts │ ├── metrics/ │ │ ├── index.ts │ │ ├── metrics-interface.ts │ │ ├── metrics.ts │ │ └── prometheus-metrics-driver.ts │ ├── namespace.ts │ ├── node.ts │ ├── options.ts │ ├── queues/ │ │ ├── index.ts │ │ ├── queue-interface.ts │ │ ├── queue.ts │ │ ├── redis-queue-driver.ts │ │ ├── sqs-queue-driver.ts │ │ └── sync-queue-driver.ts │ ├── rate-limiters/ │ │ ├── cluster-rate-limiter.ts │ │ ├── index.ts │ │ ├── local-rate-limiter.ts │ │ ├── rate-limiter-interface.ts │ │ ├── rate-limiter.ts │ │ └── redis-rate-limiter.ts │ ├── server.ts │ ├── utils.ts │ ├── webhook-sender.ts │ └── ws-handler.ts ├── tests/ │ ├── encrypted-private.test.ts │ ├── fixtures/ │ │ ├── dynamodb_schema.js │ │ ├── mysql_schema.sql │ │ ├── postgres_schema.sql │ │ └── sqs.json │ ├── http-api.cluster-adapter.test.ts │ ├── http-api.nats-adapter.test.ts │ ├── http-api.redis-adapter.test.ts │ ├── http-api.test.ts │ ├── presence.cluster-adapter.test.ts │ ├── presence.nats-adapter.test.ts │ ├── presence.redis-adapter.test.ts │ ├── presence.test.ts │ ├── private.test.ts │ ├── public.test.ts │ ├── utils.ts │ ├── webhooks.test.ts │ ├── ws.cluster-adapter.test.ts │ ├── ws.nats-adapter.test.ts │ ├── ws.redis-adapter.test.ts │ └── ws.test.ts └── tsconfig.json ================================================ FILE CONTENTS ================================================ ================================================ FILE: .dockerignore ================================================ .git/**/* assets/**/* benchmark/**/* build/**/* coverage/**/* dist/**/* node_modules/**/* tests/**/* .env npm-debug.log yarn.lock *.db ================================================ FILE: .editorconfig ================================================ root = true [*] charset = utf-8 end_of_line = lf insert_final_newline = true indent_style = space indent_size = 4 trim_trailing_whitespace = true [*.md] trim_trailing_whitespace = false [*.{yml,yaml,json}] indent_size = 2 ================================================ FILE: .eslintrc.js ================================================ module.exports = { root: true, env: { browser: true, jest: true, node: true, }, parser: "@typescript-eslint/parser", plugins: ["@typescript-eslint"], extends: ["eslint:recommended", "plugin:@typescript-eslint/recommended"], rules: { "@typescript-eslint/ban-ts-comment": "off", "@typescript-eslint/ban-types": "off", "@typescript-eslint/explicit-module-boundary-types": "off", "@typescript-eslint/no-explicit-any": "off", "@typescript-eslint/no-unused-vars": "off", "@typescript-eslint/no-var-requires": "off", "prefer-const": "off", }, }; ================================================ FILE: .gitattributes ================================================ * text=auto /.github export-ignore /tests export-ignore .editorconfig export-ignore .gitattributes export-ignore .gitignore export-ignore .npmignore export-ignore .styleci.yml export-ignore CHANGELOG.md export-ignore ================================================ FILE: .github/FUNDING.yml ================================================ github: rennokki ================================================ FILE: .github/ISSUE_TEMPLATE/bug-report---.md ================================================ --- name: "Bug Report \U0001F41E" about: Report a bug. This is NOT for other versions of Soketi. Use the Discussions board for Cloudflare Serverless. title: "[BUG] " labels: - status:triage assignees: - rennokki --- **Description** A clear and concise description of what the bug is. **Reproduction steps** Steps to reproduce the behavior: 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' 4. See error **Expected behavior** A clear and concise description of what you expected to happen. **Screenshots** If applicable, add screenshots to help explain your problem. **Environment** - Soketi version (i.e. 1.3.0): - Adapter (local, redis): local - App Manager (array, mysql, postgres, dynamodb) : array - Queue (sqs, redis, sync): sync - Cache Managers (memory, redis): memory **Configuration** Run the server with `SOKETI_DEBUG=1` and paste the nested object configuration that outputs: ```js { // } ``` **Additional context** Add any other context about the problem here. ================================================ FILE: .github/ISSUE_TEMPLATE/feature-request-🚀.md ================================================ --- name: "Feature request \U0001F680" about: Suggest an idea for this project title: "[REQUEST]" labels: '' assignees: rennokki --- **Is your feature request related to a problem? Please describe.** A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] **Describe the solution you'd like** A clear and concise description of what you want to happen. **Describe alternatives you've considered** A clear and concise description of any alternative solutions or features you've considered. **Additional context** Add any other context or screenshots about the feature request here. ================================================ FILE: .github/dependabot.yml ================================================ version: 2 registries: quay: type: docker-registry url: quay.io username: ${{ secrets.DOCKER_REGISTRY_USERNAME }} password: ${{ secrets.DOCKER_REGISTRY_TOKEN }} updates: - package-ecosystem: github-actions directory: "/" groups: all: patterns: ["*"] schedule: interval: weekly open-pull-requests-limit: 100 rebase-strategy: auto reviewers: - rennokki labels: - dependabot:actions - auto:dependabot - dependencies - package-ecosystem: npm directory: "/" groups: typescript: patterns: - "@babel/*" - "@types/*" - "eslint" - typescript - "@typescript*" - "ts*" - "*ts" - "jest" - "jest*" - "*jest" exclude-patterns: - "@types/pusher*" dev-utils: patterns: - "body-parser" - "express" - "tcp-port-used" databases: patterns: - "knex" - "ioredis" - "mysql*" - "pg" utils: patterns: - "arraybuffer-to-string" - "async" - "boolean" - "colors" - "dot*" - "query-string" - "uuid" ws: patterns: - "uWebSockets.js" - "pusher*" schedule: interval: weekly open-pull-requests-limit: 100 rebase-strategy: auto reviewers: - rennokki labels: - dependabot:npm - auto:dependabot - dependencies versioning-strategy: auto - package-ecosystem: docker directory: "/" registries: - quay schedule: interval: weekly open-pull-requests-limit: 100 rebase-strategy: auto reviewers: - rennokki labels: - dependabot:docker - auto:dependabot - dependencies ================================================ FILE: .github/stale.yml ================================================ # Number of days of inactivity before an issue becomes stale daysUntilStale: 29 # Number of days of inactivity before a stale issue is closed daysUntilClose: 1 # Issues with these labels will never be considered stale exemptLabels: - pinned - security # Label to use when marking an issue as stale staleLabel: wontfix # Comment to post when marking an issue as stale. Set to `false` to disable markComment: false # Comment to post when closing a stale issue. Set to `false` to disable closeComment: > This issue has been automatically closed because it has not had any recent activity. 😨 ================================================ FILE: .github/workflows/benchmark.yml ================================================ name: Benchmark on: workflow_run: workflows: - "CI" types: - completed jobs: build: if: "!contains(github.event.head_commit.message, 'skip ci')" runs-on: ubuntu-latest strategy: fail-fast: false matrix: node: - 16.x adapter: - local - redis - cluster - nats app_manager: - array - mysql - postgres - dynamodb include: - adapter: local rate_limiter: local queue_driver: sync cache_driver: memory - adapter: local rate_limiter: local queue_driver: sqs cache_driver: memory - adapter: cluster rate_limiter: cluster queue_driver: sync cache_driver: redis - adapter: redis rate_limiter: redis queue_driver: redis cache_driver: redis - adapter: nats rate_limiter: redis queue_driver: sync cache_driver: redis name: Node.js ${{ matrix.node }} (adapter:${{ matrix.adapter }} manager:${{ matrix.app_manager }} ratelimiter:${{ matrix.rate_limiter }} queue:${{ matrix.queue_driver }}) steps: - uses: actions/checkout@v4.1.0 - uses: actions/setup-node@v3.8.1 name: Installing Node.js v${{ matrix.node }} with: node-version: ${{ matrix.node }} - uses: actions/cache@v3.3.2 name: Cache npm dependencies with: path: node_modules key: npm-${{ hashFiles('package-lock.json') }} - name: Install dependencies run: npm ci - name: Execute lint & build run: | npm run lint npm run build - name: Setup PHP uses: shivammathur/setup-php@2.26.0 with: php-version: "8.0" extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv, yaml coverage: pcov - uses: actions/cache@v3.3.2 name: Cache Composer dependencies with: path: ~/.composer/cache/files key: composer-php-${{ hashFiles('benchmark/composer.json') }} - name: Setup message sender run: | cd benchmark/ composer install --no-interaction --no-progress --prefer-dist --optimize-autoloader - name: Setup k6 run: | sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys C5AD17C747E3415A3642D57D77C6C491D6AC1D69 echo "deb https://dl.k6.io/deb stable main" | sudo tee /etc/apt/sources.list.d/k6.list sudo apt-get update sudo apt-get install k6 - name: Setup Redis if: "matrix.adapter == 'redis' || matrix.adapter == 'cluster' || matrix.adapter == 'nats'" run: docker run -p 6379:6379 redis:6-alpine & # Setup MySQL with user `root`, password `root` and database `testing` - name: Setup MySQL if: "matrix.app_manager == 'mysql'" run: | sudo systemctl start mysql.service mysql -e 'CREATE DATABASE testing;' -u root -proot mysql -u root -proot --database=testing < tests/fixtures/mysql_schema.sql # Setup PostgreSQL with user `testing`, password `testing` and database `testing` - name: Setup PostgreSQL if: "matrix.app_manager == 'postgres'" run: | sudo systemctl start postgresql.service pg_isready sudo -u postgres psql --command="CREATE USER testing PASSWORD 'testing'" sudo -u postgres createdb --owner=postgres testing psql --host=127.0.0.1 --username=testing testing < tests/fixtures/postgres_schema.sql env: PGPASSWORD: testing - name: Setup DynamoDB if: "matrix.app_manager == 'dynamodb'" run: | docker run -p 8000:8000 amazon/dynamodb-local:1.22.0 & node tests/fixtures/dynamodb_schema.js env: AWS_ACCESS_KEY_ID: fake-id AWS_SECRET_ACCESS_KEY: fake-secret - name: Setup Localstack if: "matrix.queue_driver == 'sqs'" run: | docker-compose up -d localstack docker-compose run initialize_sqs - name: Setup NATS if: "matrix.adapter == 'nats'" run: | docker run -d \ -p 4222:4222 \ -p 6222:6222 \ -p 8222:8222 \ nats --jetstream --user="" --pass="" - name: Run Soketi (port 6001) run: | node bin/server.js start & timeout 30 bash -c 'while [[ "$(curl -s -o /dev/null -w ''%{http_code}'' http://127.0.0.1:6001/ready)" != "200" ]]; do echo "Waiting for server to be ready..."; sleep 5; done' || false env: SOKETI_PORT: 6001 SOKETI_ADAPTER_DRIVER: ${{ matrix.adapter }} SOKETI_CACHE_DRIVER: ${{ matrix.cache_driver }} SOKETI_APP_MANAGER_DRIVER: ${{ matrix.app_manager }} SOKETI_APP_MANAGER_DYNAMODB_ENDPOINT: http://127.0.0.1:8000 SOKETI_APP_MANAGER_MYSQL_USE_V2: true SOKETI_METRICS_ENABLED: true SOKETI_QUEUE_DRIVER: ${{ matrix.queue_driver }} SOKETI_QUEUE_SQS_URL: http://localhost:4566/000000000000/test.fifo SOKETI_RATE_LIMITER_DRIVER: ${{ matrix.rate_limiter }} AWS_ACCESS_KEY_ID: fake-id AWS_SECRET_ACCESS_KEY: fake-secret SOKETI_DB_MYSQL_USERNAME: root SOKETI_DB_MYSQL_PASSWORD: root - name: Run Soketi (port 6002) if: "matrix.adapter == 'redis' || matrix.adapter == 'cluster' || matrix.adapter == 'nats'" run: | node bin/server.js start & timeout 30 bash -c 'while [[ "$(curl -s -o /dev/null -w ''%{http_code}'' http://127.0.0.1:6002/ready)" != "200" ]]; do echo "Waiting for server to be ready..."; sleep 5; done' || false env: SOKETI_PORT: 6002 SOKETI_ADAPTER_DRIVER: ${{ matrix.adapter }} SOKETI_CACHE_DRIVER: ${{ matrix.cache_driver }} SOKETI_APP_MANAGER_DRIVER: ${{ matrix.app_manager }} SOKETI_APP_MANAGER_DYNAMODB_ENDPOINT: http://127.0.0.1:8000 SOKETI_APP_MANAGER_MYSQL_USE_V2: true SOKETI_METRICS_ENABLED: true SOKETI_QUEUE_DRIVER: ${{ matrix.queue_driver }} SOKETI_QUEUE_SQS_URL: http://localhost:4566/000000000000/test.fifo SOKETI_RATE_LIMITER_DRIVER: ${{ matrix.rate_limiter }} AWS_ACCESS_KEY_ID: fake-id AWS_SECRET_ACCESS_KEY: fake-secret SOKETI_DB_MYSQL_USERNAME: root SOKETI_DB_MYSQL_PASSWORD: root - name: Run message sender (port 6001) run: ./benchmark/send --interval 1 --port 6001 & - name: Run message sender (port 6002) if: "matrix.adapter == 'redis' || matrix.adapter == 'cluster' || matrix.adapter == 'nats'" run: ./benchmark/send --interval 1 --port 6002 & - name: Execute benchmarks (single nodes) if: "matrix.adapter == 'local'" run: k6 run benchmark/ci-local.js env: ADAPTER_DRIVER: ${{ matrix.adapter }} CACHE_DRIVER: ${{ matrix.cache_driver }} APP_MANAGER_DRIVER: ${{ matrix.app_manager }} QUEUE_DRIVER: ${{ matrix.queue_driver }} RATE_LIMITER_DRIVER: ${{ matrix.rate_limiter }} - name: Execute benchmarks (multiple nodes) if: "matrix.adapter == 'redis' || matrix.adapter == 'cluster' || matrix.adapter == 'nats'" run: k6 run benchmark/ci-horizontal.js env: ADAPTER_DRIVER: ${{ matrix.adapter }} CACHE_DRIVER: ${{ matrix.cache_driver }} APP_MANAGER_DRIVER: ${{ matrix.app_manager }} QUEUE_DRIVER: ${{ matrix.queue_driver }} RATE_LIMITER_DRIVER: ${{ matrix.rate_limiter }} ================================================ FILE: .github/workflows/ci.yml ================================================ name: CI on: push: branches: - '*' tags: - '*' paths-ignore: - "**.md" pull_request: branches: - '*' jobs: build: if: "!contains(github.event.head_commit.message, 'skip ci')" runs-on: ubuntu-latest strategy: fail-fast: false matrix: node: - 16.x adapter: - local - redis - cluster - nats app_manager: - array - mysql - postgres - dynamodb include: - adapter: local rate_limiter: local queue_driver: sync cache_driver: memory - adapter: local rate_limiter: local queue_driver: sqs cache_driver: memory - adapter: cluster rate_limiter: cluster queue_driver: sync cache_driver: redis - adapter: redis rate_limiter: redis queue_driver: redis cache_driver: redis - adapter: nats rate_limiter: redis queue_driver: sync cache_driver: redis name: Node.js ${{ matrix.node }} (adapter:${{ matrix.adapter }} manager:${{ matrix.app_manager }} ratelimiter:${{ matrix.rate_limiter }} queue:${{ matrix.queue_driver }}) steps: - uses: actions/checkout@v4.1.0 - uses: actions/setup-node@v3.8.1 name: Setup Node.js v${{ matrix.node }} with: node-version: ${{ matrix.node }} - name: Install dependencies run: npm install - name: Execute lint & build run: | npm run lint npm run build - name: Setup Redis if: "matrix.adapter == 'redis' || matrix.adapter == 'cluster' || matrix.adapter == 'nats'" run: docker run -p 6379:6379 redis:6-alpine & # Setup MySQL with user `root`, password `root` and database `testing` - name: Setup MySQL if: "matrix.app_manager == 'mysql'" run: | sudo systemctl start mysql.service mysql -e 'CREATE DATABASE testing;' -u root -proot mysql -u root -proot --database=testing < tests/fixtures/mysql_schema.sql # Setup PostgreSQL with user `testing`, password `testing` and database `testing` - name: Setup PostgreSQL if: "matrix.app_manager == 'postgres'" run: | sudo systemctl start postgresql.service pg_isready sudo -u postgres psql --command="CREATE USER testing PASSWORD 'testing'" sudo -u postgres createdb --owner=postgres testing psql --host=127.0.0.1 --username=testing testing < tests/fixtures/postgres_schema.sql env: PGPASSWORD: testing - name: Setup DynamoDB if: "matrix.app_manager == 'dynamodb'" run: | docker run -p 8000:8000 amazon/dynamodb-local:1.22.0 & node tests/fixtures/dynamodb_schema.js env: AWS_ACCESS_KEY_ID: fake-id AWS_SECRET_ACCESS_KEY: fake-secret - name: Setup Localstack if: "matrix.queue_driver == 'sqs'" run: | docker-compose up -d localstack docker-compose run initialize_sqs - name: Setup NATS if: "matrix.adapter == 'nats'" run: | docker run -d \ -p 4222:4222 \ -p 6222:6222 \ -p 8222:8222 \ nats --jetstream --user="" --pass="" - name: Execute tests run: npm run test env: RETRY_TIMES: 2 TEST_ADAPTER: ${{ matrix.adapter }} TEST_APP_MANAGER: ${{ matrix.app_manager }} TEST_CACHE_DRIVER: ${{ matrix.cache_driver }} TEST_QUEUE_DRIVER: ${{ matrix.queue_driver }} TEST_RATE_LIMITER: ${{ matrix.rate_limiter }} TEST_MYSQL_USER: root TEST_MYSQL_PASSWORD: root TEST_SQS_URL: http://localhost:4566/000000000000/test.fifo AWS_ACCESS_KEY_ID: fake-id AWS_SECRET_ACCESS_KEY: fake-secret - uses: codecov/codecov-action@v3.1.4 with: token: ${{ secrets.CODECOV_TOKEN }} fail_ci_if_error: false ================================================ FILE: .github/workflows/docker-commit.yml ================================================ name: Docker Commit on: push: branches: - "*" pull_request: branches: - "*" tags-ignore: - "*" jobs: # Alpine build. # WARNING: Deprecated, will be removed as it is not recommended # for uWebSockets.js alpine: if: "!contains(github.event.head_commit.message, 'skip ci')" runs-on: ubuntu-latest strategy: fail-fast: false matrix: node: - '16' name: Tag Alpine Commit (node:${{ matrix.node }}) steps: - uses: actions/checkout@v4.1.0 - name: Docker meta id: docker_meta uses: docker/metadata-action@v5.0.0 with: images: quay.io/soketi/soketi tags: | type=ref,event=pr,suffix=-${{ matrix.node }}-alpine type=raw,value=${{ github.sha }}-${{ matrix.node }}-alpine labels: | quay.expires-after=7d - name: Set up QEMU uses: docker/setup-qemu-action@v3 - name: Set up Docker Buildx uses: docker/setup-buildx-action@v3 with: driver-opts: network=host - name: Login to Quay uses: docker/login-action@v3 with: registry: quay.io username: ${{ secrets.DOCKER_REGISTRY_USERNAME }} password: ${{ secrets.DOCKER_REGISTRY_TOKEN }} - name: Build and Push uses: docker/build-push-action@v5 with: push: true context: . tags: ${{ steps.docker_meta.outputs.tags }} labels: ${{ steps.docker_meta.outputs.labels }} build-args: | VERSION=${{ matrix.node }} cache-from: | type=gha,scope=alpine cache-to: | type=gha,scope=alpine platforms: | linux/amd64 linux/arm64 linux/arm/v7 # Distroless build. distroless: if: "!contains(github.event.head_commit.message, 'skip ci')" runs-on: ubuntu-latest strategy: fail-fast: false matrix: node: - '16' name: Tag Distroless Commit (node:${{ matrix.node }}) steps: - uses: actions/checkout@v4.1.0 - name: Docker meta id: docker_meta uses: docker/metadata-action@v5.0.0 with: images: quay.io/soketi/soketi tags: | type=ref,event=pr,suffix=-${{ matrix.node }}-distroless type=raw,value=${{ github.sha }}-${{ matrix.node }}-distroless labels: | quay.expires-after=7d - name: Set up QEMU uses: docker/setup-qemu-action@v3 - name: Set up Docker Buildx uses: docker/setup-buildx-action@v3 with: driver-opts: network=host - name: Login to Quay uses: docker/login-action@v3 with: registry: quay.io username: ${{ secrets.DOCKER_REGISTRY_USERNAME }} password: ${{ secrets.DOCKER_REGISTRY_TOKEN }} - name: Build and Push uses: docker/build-push-action@v5 with: push: true context: . tags: ${{ steps.docker_meta.outputs.tags }} labels: ${{ steps.docker_meta.outputs.labels }} file: Dockerfile.distroless build-args: | VERSION=${{ matrix.node }} cache-from: | type=gha,scope=distroless cache-to: | type=gha,scope=distroless platforms: | linux/amd64 linux/arm64 # Stable Debian build. debian: if: "!contains(github.event.head_commit.message, 'skip ci')" runs-on: ubuntu-latest strategy: fail-fast: false matrix: node: - '16' name: Tag Debian Commit (node:${{ matrix.node }}) steps: - uses: actions/checkout@v4.1.0 - name: Docker meta id: docker_meta uses: docker/metadata-action@v5.0.0 with: images: quay.io/soketi/soketi tags: | type=ref,event=pr,suffix=-${{ matrix.node }}-debian type=raw,value=${{ github.sha }}-${{ matrix.node }}-debian labels: | quay.expires-after=7d - name: Set up QEMU uses: docker/setup-qemu-action@v3 - name: Set up Docker Buildx uses: docker/setup-buildx-action@v3 with: driver-opts: network=host - name: Login to Quay uses: docker/login-action@v3 with: registry: quay.io username: ${{ secrets.DOCKER_REGISTRY_USERNAME }} password: ${{ secrets.DOCKER_REGISTRY_TOKEN }} - name: Build and Push uses: docker/build-push-action@v5 with: push: true context: . tags: ${{ steps.docker_meta.outputs.tags }} labels: ${{ steps.docker_meta.outputs.labels }} file: Dockerfile.debian build-args: | VERSION=${{ matrix.node }} cache-from: | type=gha,scope=debian cache-to: | type=gha,scope=debian platforms: | linux/amd64 linux/arm64 linux/arm/v7 ================================================ FILE: .github/workflows/docker-latest-tag.yml ================================================ name: Docker Latest - Standard on: push: branches: - master tags-ignore: - "*" pull_request: tags-ignore: - "*" branches-ignore: - "*" jobs: # Alpine build. # WARNING: Deprecated, will be removed as it is not recommended # for uWebSockets.js alpine: if: "!contains(github.event.head_commit.message, 'skip ci')" runs-on: ubuntu-latest strategy: matrix: node: - '16' name: Tag Latest Alpine (node:${{ matrix.node }}) steps: - uses: actions/checkout@v4.1.0 - name: Docker meta id: docker_meta uses: docker/metadata-action@v5.0.0 with: images: quay.io/soketi/soketi tags: | type=raw,value=latest-${{ matrix.node }}-alpine - name: Set up QEMU uses: docker/setup-qemu-action@v3 - name: Set up Docker Buildx uses: docker/setup-buildx-action@v3 with: driver-opts: network=host - name: Login to Quay uses: docker/login-action@v3 with: registry: quay.io username: ${{ secrets.DOCKER_REGISTRY_USERNAME }} password: ${{ secrets.DOCKER_REGISTRY_TOKEN }} - name: Build and Push uses: docker/build-push-action@v5 with: push: true context: . tags: ${{ steps.docker_meta.outputs.tags }} labels: ${{ steps.docker_meta.outputs.labels }} build-args: | VERSION=${{ matrix.node }} cache-from: | type=gha,scope=alpine cache-to: | type=gha,scope=alpine platforms: | linux/amd64 linux/arm64 linux/arm/v7 # Distroless build. distroless: if: "!contains(github.event.head_commit.message, 'skip ci')" runs-on: ubuntu-latest strategy: matrix: node: - '16' name: Tag Latest Distroless (node:${{ matrix.node }}) steps: - uses: actions/checkout@v4.1.0 - name: Docker meta id: docker_meta uses: docker/metadata-action@v5.0.0 with: images: quay.io/soketi/soketi tags: | type=raw,value=latest-${{ matrix.node }}-distroless - name: Set up QEMU uses: docker/setup-qemu-action@v3 - name: Set up Docker Buildx uses: docker/setup-buildx-action@v3 with: driver-opts: network=host - name: Login to Quay uses: docker/login-action@v3 with: registry: quay.io username: ${{ secrets.DOCKER_REGISTRY_USERNAME }} password: ${{ secrets.DOCKER_REGISTRY_TOKEN }} - name: Build and Push uses: docker/build-push-action@v5 with: push: true context: . tags: ${{ steps.docker_meta.outputs.tags }} labels: ${{ steps.docker_meta.outputs.labels }} file: Dockerfile.distroless build-args: | VERSION=${{ matrix.node }} cache-from: | type=gha,scope=distroless cache-to: | type=gha,scope=distroless platforms: | linux/amd64 linux/arm64 # Debian build. debian: if: "!contains(github.event.head_commit.message, 'skip ci')" runs-on: ubuntu-latest strategy: matrix: node: - '16' name: Tag Latest Debian (node:${{ matrix.node }}) steps: - uses: actions/checkout@v4.1.0 - name: Docker meta id: docker_meta uses: docker/metadata-action@v5.0.0 with: images: quay.io/soketi/soketi tags: | type=raw,value=latest-${{ matrix.node }}-debian - name: Set up QEMU uses: docker/setup-qemu-action@v3 - name: Set up Docker Buildx uses: docker/setup-buildx-action@v3 with: driver-opts: network=host - name: Login to Quay uses: docker/login-action@v3 with: registry: quay.io username: ${{ secrets.DOCKER_REGISTRY_USERNAME }} password: ${{ secrets.DOCKER_REGISTRY_TOKEN }} - name: Build and Push uses: docker/build-push-action@v5 with: push: true context: . tags: ${{ steps.docker_meta.outputs.tags }} labels: ${{ steps.docker_meta.outputs.labels }} file: Dockerfile.debian build-args: | VERSION=${{ matrix.node }} cache-from: | type=gha,scope=debian cache-to: | type=gha,scope=debian platforms: | linux/amd64 linux/arm64 linux/arm/v7 ================================================ FILE: .github/workflows/docker-release-tag.yml ================================================ name: Docker Release - Standard on: push: tags: - "*" jobs: # Alpine build. # WARNING: Deprecated, will be removed as it is not recommended # for uWebSockets.js alpine: if: "!contains(github.event.head_commit.message, 'skip ci')" runs-on: ubuntu-latest strategy: matrix: node: - '16' name: Tag Alpine Release (node:${{ matrix.node }}) steps: - uses: actions/checkout@v4.1.0 - name: Docker meta id: docker_meta uses: docker/metadata-action@v5.0.0 with: images: quay.io/soketi/soketi tags: | type=semver,pattern={{version}}-${{ matrix.node }}-alpine type=semver,pattern={{major}}.{{minor}}-${{ matrix.node }}-alpine - name: Set up QEMU uses: docker/setup-qemu-action@v3 - name: Set up Docker Buildx uses: docker/setup-buildx-action@v3 - name: Compute GitHub tag id: tag uses: dawidd6/action-get-tag@v1.1.0 - name: Login to Quay uses: docker/login-action@v3 with: registry: quay.io username: ${{ secrets.DOCKER_REGISTRY_USERNAME }} password: ${{ secrets.DOCKER_REGISTRY_TOKEN }} - name: Build and push (node:${{ matrix.node }}) uses: docker/build-push-action@v5 with: push: true context: . tags: ${{ steps.docker_meta.outputs.tags }} labels: ${{ steps.docker_meta.outputs.labels }} build-args: | VERSION=${{ matrix.node }} cache-from: | type=gha,scope=alpine cache-to: | type=gha,scope=alpine platforms: | linux/amd64 linux/arm64 linux/arm/v7 # Distroless build. distroless: if: "!contains(github.event.head_commit.message, 'skip ci')" runs-on: ubuntu-latest strategy: matrix: node: - '16' name: Tag Distroless Release (node:${{ matrix.node }}) steps: - uses: actions/checkout@v4.1.0 - name: Docker meta id: docker_meta uses: docker/metadata-action@v5.0.0 with: images: quay.io/soketi/soketi tags: | type=semver,pattern={{version}}-${{ matrix.node }}-distroless type=semver,pattern={{major}}.{{minor}}-${{ matrix.node }}-distroless - name: Set up QEMU uses: docker/setup-qemu-action@v3 - name: Set up Docker Buildx uses: docker/setup-buildx-action@v3 - name: Compute GitHub tag id: tag uses: dawidd6/action-get-tag@v1.1.0 - name: Login to Quay uses: docker/login-action@v3 with: registry: quay.io username: ${{ secrets.DOCKER_REGISTRY_USERNAME }} password: ${{ secrets.DOCKER_REGISTRY_TOKEN }} - name: Build and push (node:${{ matrix.node }}) uses: docker/build-push-action@v5 with: push: true context: . tags: ${{ steps.docker_meta.outputs.tags }} labels: ${{ steps.docker_meta.outputs.labels }} file: Dockerfile.distroless build-args: | VERSION=${{ matrix.node }} cache-from: | type=gha,scope=distroless cache-to: | type=gha,scope=distroless platforms: | linux/amd64 linux/arm64 # Debian build. debian: if: "!contains(github.event.head_commit.message, 'skip ci')" runs-on: ubuntu-latest strategy: matrix: node: - '16' name: Tag Debian Release (node:${{ matrix.node }}) steps: - uses: actions/checkout@v4.1.0 - name: Docker meta id: docker_meta uses: docker/metadata-action@v5.0.0 with: images: quay.io/soketi/soketi tags: | type=semver,pattern={{version}}-${{ matrix.node }}-debian type=semver,pattern={{major}}.{{minor}}-${{ matrix.node }}-debian - name: Set up QEMU uses: docker/setup-qemu-action@v3 - name: Set up Docker Buildx uses: docker/setup-buildx-action@v3 - name: Compute GitHub tag id: tag uses: dawidd6/action-get-tag@v1.1.0 - name: Login to Quay uses: docker/login-action@v3 with: registry: quay.io username: ${{ secrets.DOCKER_REGISTRY_USERNAME }} password: ${{ secrets.DOCKER_REGISTRY_TOKEN }} - name: Build and push (node:${{ matrix.node }}) uses: docker/build-push-action@v5 with: push: true context: . tags: ${{ steps.docker_meta.outputs.tags }} labels: ${{ steps.docker_meta.outputs.labels }} file: Dockerfile.debian build-args: | VERSION=${{ matrix.node }} cache-from: | type=gha,scope=debian cache-to: | type=gha,scope=debian platforms: | linux/amd64 linux/arm64 linux/arm/v7 ================================================ FILE: .github/workflows/release-npm.yml ================================================ name: NPM Release on: push: tags: - "*" jobs: build: if: "!contains(github.event.head_commit.message, 'skip ci')" runs-on: ubuntu-latest name: Publish to NPM steps: - uses: actions/checkout@v4.1.0 - uses: actions/setup-node@v3.8.1 name: Installing Node.js v16.x with: node-version: 16.x - uses: actions/cache@v3.3.2 name: Cache npm dependencies with: path: node_modules key: npm-${{ hashFiles('package-lock.json') }} - name: Installing dependencies run: | npm ci - name: Lint & Compile run: | npm run lint npm run build - name: Cleanup run: | npm prune --production rm -rf node_modules/*/test/ node_modules/*/tests/ - name: Compute GitHub tag id: tag uses: dawidd6/action-get-tag@v1.1.0 - name: Publish run: | git config --local user.email "41898282+github-actions[bot]@users.noreply.github.com" git config --local user.name "github-actions[bot]" npm set //registry.npmjs.org/:_authToken $NPM_TOKEN npm version ${{ steps.tag.outputs.tag }} npm publish --access=public env: NPM_TOKEN: ${{ secrets.NPM_TOKEN }} NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} ================================================ FILE: .gitignore ================================================ benchmark/vendor/ build/ coverage/ dist/ node_modules/ .env benchmark/composer.lock config.json npm-debug.log yarn.lock *.db ================================================ FILE: .npmignore ================================================ src/ tests/ ================================================ FILE: CONTRIBUTING.md ================================================ # Contributing Contributions are **welcome** and will be fully **credited**. Please read and understand the contribution guide before creating an issue or pull request. ## Etiquette This project is open source, and as such, the maintainers give their free time to build and maintain the source code held within. They make the code freely available in the hope that it will be of use to other developers. It would be extremely unfair for them to suffer abuse or anger for their hard work. Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the world that developers are civilized and selfless people. It's the duty of the maintainer to ensure that all submissions to the project are of sufficient quality to benefit the project. Many developers have different skillsets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used. ## Viability When requesting or submitting new features, first consider whether it might be useful to others. Open source projects are used by many developers, who may have entirely different needs to your own. Think about whether or not your feature is likely to be used by other users of the project. ## Procedure Before filing an issue: - Attempt to replicate the problem, to ensure that it wasn't a coincidental incident. - Check to make sure your feature suggestion isn't already present within the project. - Check the pull requests tab to ensure that the bug doesn't have a fix in progress. - Check the pull requests tab to ensure that the feature isn't already in progress. Before submitting a pull request: - Check the codebase to ensure that your feature doesn't already exist. - Check the pull requests to ensure that another person hasn't already submitted the feature or fix. ## Requirements If the project maintainer has any additional requirements, you will find them listed here. - **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](https://pear.php.net/package/PHP_CodeSniffer). - **Add tests!** - Your patch won't be accepted if it doesn't have tests. - **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. - **Consider our release cycle** - We try to follow [SemVer v2.0.0](https://semver.org/). Randomly breaking public APIs is not an option. - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. - **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](https://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. **Happy coding**! ================================================ FILE: Dockerfile ================================================ ARG VERSION=lts FROM --platform=$BUILDPLATFORM node:$VERSION-alpine as build ENV PYTHONUNBUFFERED=1 COPY . /tmp/build WORKDIR /tmp/build RUN apk add --no-cache --update git python3 gcompat ; \ apk add --virtual build-dependencies build-base gcc wget ; \ ln -sf python3 /usr/bin/python ; \ python3 -m ensurepip ; \ pip3 install --no-cache --upgrade pip setuptools ; \ npm ci ; \ npm run build ; \ npm ci --omit=dev --ignore-scripts ; \ npm prune --production ; \ rm -rf node_modules/*/test/ node_modules/*/tests/ ; \ npm install -g modclean ; \ modclean -n default:safe --run ; \ mkdir -p /app ; \ cp -r bin/ dist/ node_modules/ LICENSE package.json package-lock.json README.md /app/ FROM --platform=$TARGETPLATFORM node:$VERSION-alpine LABEL org.opencontainers.image.authors="Soketi " LABEL org.opencontainers.image.source="https://github.com/soketi/soketi" LABEL org.opencontainers.image.url="https://soketi.app" LABEL org.opencontainers.image.documentation="https://docs.soketi.app" LABEL org.opencontainers.image.vendor="Soketi" LABEL org.opencontainers.image.licenses="AGPL-3.0" RUN apk add --no-cache libc6-compat ; \ ln -s /lib/libc.musl-x86_64.so.1 /lib/ld-linux-x86-64.so.2 COPY --from=build /app /app WORKDIR /app EXPOSE 6001 ENTRYPOINT ["node", "/app/bin/server.js", "start"] ================================================ FILE: Dockerfile.awslocal ================================================ FROM python:3-alpine RUN pip install awscli-local awscli && \ mkdir -p ~/.aws && \ touch ~/.aws/credentials && \ echo "[default]" >> ~/.aws/credentials && \ echo "aws_access_key_id = fake-id" >> ~/.aws/credentials && \ echo "aws_secret_access_key = fake-secret" >> ~/.aws/credentials ENTRYPOINT ["awslocal"] ================================================ FILE: Dockerfile.debian ================================================ ARG VERSION=lts FROM --platform=$BUILDPLATFORM node:$VERSION-bullseye as build ENV PYTHONUNBUFFERED=1 COPY . /tmp/build WORKDIR /tmp/build RUN apt-get update -y ; \ apt-get upgrade -y ; \ apt-get install -y git python3 gcc wget ; \ npm ci ; \ npm run build ; \ npm ci --omit=dev --ignore-scripts ; \ npm prune --production ; \ rm -rf node_modules/*/test/ node_modules/*/tests/ ; \ npm install -g modclean ; \ modclean -n default:safe --run ; \ mkdir -p /app ; \ cp -r bin/ dist/ node_modules/ LICENSE package.json package-lock.json README.md /app/ FROM --platform=$TARGETPLATFORM node:$VERSION-bullseye-slim LABEL org.opencontainers.image.authors="Soketi " LABEL org.opencontainers.image.source="https://github.com/soketi/soketi" LABEL org.opencontainers.image.url="https://soketi.app" LABEL org.opencontainers.image.documentation="https://docs.soketi.app" LABEL org.opencontainers.image.vendor="Soketi" LABEL org.opencontainers.image.licenses="AGPL-3.0" COPY --from=build /app /app WORKDIR /app EXPOSE 6001 ENTRYPOINT ["node", "/app/bin/server.js", "start"] ================================================ FILE: Dockerfile.distroless ================================================ ARG VERSION=16 FROM --platform=$BUILDPLATFORM node:$VERSION-alpine as base ENV PYTHONUNBUFFERED=1 COPY . /tmp/build WORKDIR /tmp/build RUN apk add --no-cache --update git python3 gcompat ; \ apk add --virtual build-dependencies build-base gcc wget ; \ ln -sf python3 /usr/bin/python ; \ python3 -m ensurepip ; \ pip3 install --no-cache --upgrade pip setuptools ; \ npm ci ; \ npm run build ; \ npm ci --omit=dev --ignore-scripts ; \ npm prune --production ; \ rm -rf node_modules/*/test/ node_modules/*/tests/ ; \ npm install -g modclean ; \ modclean -n default:safe --run ; \ mkdir -p /app ; \ cp -r bin/ dist/ node_modules/ LICENSE package.json package-lock.json README.md /app/ ; \ chgrp -R 0 /app/ ; \ chmod -R g+rx /app/ FROM --platform=$TARGETPLATFORM gcr.io/distroless/nodejs:$VERSION LABEL org.opencontainers.image.authors="Soketi " LABEL org.opencontainers.image.source="https://github.com/soketi/soketi" LABEL org.opencontainers.image.url="https://soketi.app" LABEL org.opencontainers.image.documentation="https://docs.soketi.app" LABEL org.opencontainers.image.vendor="Soketi" LABEL org.opencontainers.image.licenses="AGPL-3.0" COPY --from=base /app /app WORKDIR /app USER 65534 EXPOSE 6001 CMD ["/app/bin/server.js", "start"] ================================================ FILE: LICENSE ================================================ GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU Affero General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Remote Network Interaction; Use with the GNU General Public License. Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see . ================================================ FILE: README.md ================================================ # soketi ![CI](https://github.com/soketi/soketi/workflows/CI/badge.svg?branch=master) [![codecov](https://codecov.io/gh/soketi/soketi/branch/master/graph/badge.svg)](https://codecov.io/gh/soketi/soketi/branch/master) [![Latest Stable Version](https://img.shields.io/github/v/release/soketi/soketi)](https://www.npmjs.com/package/@soketi/soketi) [![Total Downloads](https://img.shields.io/npm/dt/@soketi/soketi)](https://www.npmjs.com/package/@soketi/soketi) [![License](https://img.shields.io/npm/l/@soketi/soketi)](https://www.npmjs.com/package/@soketi/soketi) [![Artifact Hub](https://img.shields.io/endpoint?url=https://artifacthub.io/badge/repository/soketi)](https://artifacthub.io/packages/search?repo=soketi) [![Discord](https://img.shields.io/discord/957380329985958038?color=%235865F2&label=Discord&logo=discord&logoColor=%23fff)](https://discord.gg/VgfKCQydjb) Next-gen, Pusher-compatible, open-source WebSockets server. Simple, fast, and resilient. 📣 ## 🤝 Supporting Soketi is meant to be open source, forever and ever. It solves issues that many developers face - the one of wanting to be limitless while testing locally or performing benchmarks. More than that, itt is also suited for production usage, either it is public for your frontend applications or internal to your team. The frequency of releases and maintenance is based on the available time, which is tight as hell. Recently, there were issues with the maintenance and this caused infrequent updates, as well as infrequent support. To cover some of the expenses of handling new features or having to maintain the project, we would be more than happy if you can donate towards the goal. This will ensure that Soketi will be taken care of at its full extent. **[💰 Sponsor the development via Github Sponsors](https://github.com/sponsors/rennokki)**

Logos from Sponsors

## Soketi ### Blazing fast speed ⚡ The server is built on top of [uWebSockets.js](https://github.com/uNetworking/uWebSockets.js) - a C application ported to Node.js. uWebSockets.js is demonstrated to perform at levels [_8.5x that of Fastify_](https://alexhultman.medium.com/serving-100k-requests-second-from-a-fanless-raspberry-pi-4-over-ethernet-fdd2c2e05a1e) and at least [_10x that of Socket.IO_](https://medium.com/swlh/100k-secure-websockets-with-raspberry-pi-4-1ba5d2127a23). ([_source_](https://github.com/uNetworking/uWebSockets.js)) ### Cheaper than most competitors 🤑 For a $49 plan on Pusher, you get a limited amount of connections (500) and messages (30M). With Soketi, for the price of an instance on Vultr or DigitalOcean ($5-$10), you get virtually unlimited connections, messages, and some more! Soketi is capable to hold thousands of active connections with high traffic on less than **1 GB and 1 CPU** in the cloud. You can also [get free $100 on Vultr to try out soketi →](https://www.vultr.com/?ref=9032189-8H) ### Easy to use 👶 Whether you run your infrastructure in containers or monoliths, soketi is portable. There are multiple ways to [install](https://docs.soketi.app/getting-started/installation) and [configure](https://docs.soketi.app/getting-started/environment-variables) soketi, from single instances for development, to tens of active instances at scale with hundreds or thousands of active users. ### Pusher Protocol 📡 soketi implements the [Pusher Protocol v7](https://pusher.com/docs/channels/library\_auth\_reference/pusher-websockets-protocol#version-7-2017-11). Your existing projects that connect to Pusher requires minimal code change to make it work with Soketi - you just add the host and port and swap the credentials. ### App-based access 🔐 Just like Pusher, you can access the API and WebSockets through the [apps you define](https://docs.soketi.app/app-management/introduction). Store the data with the built-in support for static arrays, DynamoDB and SQL-based servers like Postgres. ### Production-ready! 🤖 In addition to being a good companion during local development, soketi comes with the resiliency and speed required for demanding production applications. At scale with Redis, you get the breeze of scaling as you grow. ### Built-in monitoring 📈 You just have to scrape the Prometheus metrics. Soketi offers a lot of metrics to monitor the deployment and ## See it in action - [Laravel chat app](https://github.com/soketi/laravel-chat-app) - [ETH History chart](https://github.com/soketi/laravel-eth-history) ### Deployments - [Deploy with Railway](https://github.com/soketi/soketi-railway-deploy-example) - [Deploy with Cleavr](https://cleavr.io/cleavr-slice/how-to-install-soketi) ## Community projects - [Soketi UI](https://github.com/Daynnnnn/soketi-ui) - manage Soketi apps via UI - [Soketi App Manager for Filament](https://github.com/rahulhaque/soketi-app-manager-filament) - manage Soketi apps via Filament - [Basement Chat](https://github.com/basement-chat/basement-chat) - add chat to your Laravel application - [Simple Chat](https://github.com/kitar/simplechat) - showcased chat app built with Soketi and DynamoDB ## 📃 Documentation [The entire documentation is available on Gitbook 🌍](https://rennokki.gitbook.io/soketi-docs/) ## 🌟 Stargazers We really appreciate how this project turned to be such a great success. It will always remain open-source, free, and maintained. This is the real-time as it should be. [![Stargazers over time](https://starchart.cc/soketi/soketi.svg)](https://starchart.cc/soketi/soketi) ## 🤝 Contributing Please see [CONTRIBUTING](CONTRIBUTING.md) for details. ## ⁉ Ideas or Discussions? Have any ideas that can make into the project? Perhaps you have questions? [Jump into the discussions board](https://github.com/soketi/soketi/discussions) or [join the Discord channel](https://discord.gg/VgfKCQydjb) ## 🔒 Security If you discover any security related issues, please email alex@renoki.org instead of using the issue tracker. ## 🎉 Credits - [Alex Renoki](https://github.com/rennokki) - [Pusher Protocol](https://pusher.com/docs/channels/library_auth_reference/pusher-websockets-protocol) - [All Contributors](../../contributors) - Thank you to Bunny! 🌸 ================================================ FILE: SECURITY.md ================================================ # Security Policy ## Supported Versions | Version | Supported | | - | - | | <0.26.1 | :x: | | >=0.26.1 < 1.0.0 | :x: | | >= 1.6.0 | :white_check_mark: | ## Reporting a Vulnerability If you discover any security-related issues, please email alex@renoki.org instead of using the issue tracker. ================================================ FILE: babel.config.js ================================================ module.exports = { presets: [ '@babel/preset-typescript', ], }; ================================================ FILE: benchmark/ci-horizontal.js ================================================ import { Trend } from 'k6/metrics'; import ws from 'k6/ws'; /** * You need to run 4 terminals for this. * * 1. Run the servers: * * SOKETI_PORT=6001 SOKETI_ADAPTER_DRIVER=cluster SOKETI_RATE_LIMITER_DRIVER=cluster bin/server.js start * SOKETI_PORT=6002 SOKETI_ADAPTER_DRIVER=cluster SOKETI_RATE_LIMITER_DRIVER=cluster bin/server.js start * * 2. Run the PHP senders based on the amount of messages per second you want to receive. * The sending rate influences the final benchmark. * * Low, 1 message per second: * php send --interval 1 --port 6001 * php send --interval 1 --port 6002 * * Mild, 2 messages per second: * php send --interval 0.5 --port 6001 * php send --interval 0.5 --port 6002 * * Overkill, 10 messages per second: * php send --interval 0.1 --port 6001 * php send --interval 0.1 --port 6002 */ const delayTrend = new Trend('message_delay_ms'); let maxP95 = 100; let maxAvg = 100; // External DBs are really slow for benchmarks. if (['mysql', 'postgres', 'dynamodb'].includes(__ENV.APP_MANAGER_DRIVER)) { maxP95 += 500; maxAvg += 100; } // Horizontal drivers take additional time to communicate with other nodes. if (['redis', 'cluster', 'nats'].includes(__ENV.ADAPTER_DRIVER)) { maxP95 += 100; maxAvg += 100; } export const options = { thresholds: { message_delay_ms: [ { threshold: `p(95)<${maxP95}`, abortOnFail: false }, { threshold: `avg<${maxAvg}`, abortOnFail: false }, ], }, scenarios: { // Keep connected many users users at the same time. soakTraffic1: { executor: 'ramping-vus', startVUs: 0, startTime: '0s', stages: [ { duration: '50s', target: 125 }, { duration: '110s', target: 125 }, ], gracefulRampDown: '40s', env: { SLEEP_FOR: '160', WS_HOST: 'ws://127.0.0.1:6001/app/app-key', }, }, soakTraffic2: { executor: 'ramping-vus', startVUs: 0, startTime: '0s', stages: [ { duration: '50s', target: 125 }, { duration: '110s', target: 125 }, ], gracefulRampDown: '40s', env: { SLEEP_FOR: '160', WS_HOST: 'ws://127.0.0.1:6002/app/app-key', }, }, // Having high amount of connections and disconnections // representing active traffic that starts after 5 seconds // from the soakTraffic scenario. highTraffic1: { executor: 'ramping-vus', startVUs: 0, startTime: '50s', stages: [ { duration: '50s', target: 125 }, { duration: '30s', target: 125 }, { duration: '10s', target: 50 }, { duration: '10s', target: 25 }, { duration: '10s', target: 50 }, ], gracefulRampDown: '25s', env: { SLEEP_FOR: '160', WS_HOST: 'ws://127.0.0.1:6001/app/app-key', }, }, highTraffic2: { executor: 'ramping-vus', startVUs: 0, startTime: '50s', stages: [ { duration: '50s', target: 125 }, { duration: '30s', target: 125 }, { duration: '10s', target: 50 }, { duration: '10s', target: 25 }, { duration: '10s', target: 50 }, ], gracefulRampDown: '25s', env: { SLEEP_FOR: '160', WS_HOST: 'ws://127.0.0.1:6002/app/app-key', }, }, }, }; export default () => { ws.connect(__ENV.WS_HOST, null, (socket) => { socket.setTimeout(() => { socket.close(); }, __ENV.SLEEP_FOR * 1000); socket.on('open', () => { // Keep connection alive with pusher:ping socket.setInterval(() => { socket.send(JSON.stringify({ event: 'pusher:ping', data: JSON.stringify({}), })); }, 30000); socket.on('message', message => { let receivedTime = Date.now(); message = JSON.parse(message); if (message.event === 'pusher:connection_established') { socket.send(JSON.stringify({ event: 'pusher:subscribe', data: { channel: 'benchmark' }, })); } if (message.event === 'timed-message') { let data = JSON.parse(message.data); delayTrend.add(receivedTime - data.time); } }); }); }); } ================================================ FILE: benchmark/ci-local.js ================================================ import { Trend } from 'k6/metrics'; import ws from 'k6/ws'; /** * You need to run 4 terminals for this. * * 1. Run the servers: * * SOKETI_PORT=6001 SOKETI_ADAPTER_DRIVER=local SOKETI_RATE_LIMITER_DRIVER=local bin/server.js start * * 2. Run the PHP senders based on the amount of messages per second you want to receive. * The sending rate influences the final benchmark. * * Low, 1 message per second: * php send --interval 1 --port 6001 * * Mild, 2 messages per second: * php send --interval 0.5 --port 6001 * * Overkill, 10 messages per second: * php send --interval 0.1 --port 6001 */ const delayTrend = new Trend('message_delay_ms'); let maxP95 = 100; let maxAvg = 100; // External DBs are really slow for benchmarks. if (['mysql', 'postgres', 'dynamodb'].includes(__ENV.APP_MANAGER_DRIVER)) { maxP95 += 500; maxAvg += 100; } // Horizontal drivers take additional time to communicate with other nodes. if (['redis', 'cluster', 'nats'].includes(__ENV.ADAPTER_DRIVER)) { maxP95 += 100; maxAvg += 100; } if (['redis'].includes(__ENV.CACHE_DRIVER)) { maxP95 += 20; maxAvg += 20; } export const options = { thresholds: { message_delay_ms: [ { threshold: `p(95)<${maxP95}`, abortOnFail: false }, { threshold: `avg<${maxAvg}`, abortOnFail: false }, ], }, scenarios: { // Keep connected many users users at the same time. soakTraffic: { executor: 'ramping-vus', startVUs: 0, startTime: '0s', stages: [ { duration: '50s', target: 250 }, { duration: '110s', target: 250 }, ], gracefulRampDown: '40s', env: { SLEEP_FOR: '160', WS_HOST: __ENV.WS_HOST || 'ws://127.0.0.1:6001/app/app-key', }, }, // Having high amount of connections and disconnections // representing active traffic that starts after 5 seconds // from the soakTraffic scenario. highTraffic: { executor: 'ramping-vus', startVUs: 0, startTime: '50s', stages: [ { duration: '50s', target: 250 }, { duration: '30s', target: 250 }, { duration: '10s', target: 100 }, { duration: '10s', target: 50 }, { duration: '10s', target: 100 }, ], gracefulRampDown: '20s', env: { SLEEP_FOR: '110', WS_HOST: __ENV.WS_HOST || 'ws://127.0.0.1:6001/app/app-key', }, }, }, }; export default () => { ws.connect(__ENV.WS_HOST, null, (socket) => { socket.setTimeout(() => { socket.close(); }, __ENV.SLEEP_FOR * 1000); socket.on('open', () => { // Keep connection alive with pusher:ping socket.setInterval(() => { socket.send(JSON.stringify({ event: 'pusher:ping', data: JSON.stringify({}), })); }, 30000); socket.on('message', message => { let receivedTime = Date.now(); message = JSON.parse(message); if (message.event === 'pusher:connection_established') { socket.send(JSON.stringify({ event: 'pusher:subscribe', data: { channel: 'benchmark' }, })); } if (message.event === 'timed-message') { let data = JSON.parse(message.data); delayTrend.add(receivedTime - data.time); } }); }); }); } ================================================ FILE: benchmark/composer.json ================================================ { "name": "soketi/soketi-benchmark", "type": "package", "license": "MIT", "minimum-stability": "dev", "require": { "pusher/pusher-php-server": "^7.0", "nesbot/carbon": "^2.0", "ratchet/pawl": "dev-master", "toolkit/pflag": "dev-main" } } ================================================ FILE: benchmark/send ================================================ #!/usr/bin/env php setScriptFile($flags); $fs->addOpt('interval', 'i', 'Specify at which interval to send each message.', FlagType::FLOAT, false, 0.1); $fs->addOpt('messages', 'm', 'Specify the number of messages to send.', FlagType::INT, false); $fs->addOpt('host', 'h', 'Specify the host to connect to.', FlagType::STRING, false, '127.0.0.1'); $fs->addOpt('app-id', 'app-id', 'Specify the ID to use.', FlagType::STRING, false, 'app-id'); $fs->addOpt('app-key', 'app-key', 'Specify the key to use.', FlagType::STRING, false, 'app-key'); $fs->addOpt('app-secret', 'app-secret', 'Specify the secret to use.', FlagType::STRING, false, 'app-secret'); $fs->addOpt('port', 'p', 'Specify the port to connect to.', FlagType::INT, false, 6001); $fs->addOpt('ssl', 's', 'Securely connect to the server.', FlagType::BOOL, false, false); $fs->addOpt('verbose', 'v', 'Enable verbosity.', FlagType::BOOL, false, false); if (! $fs->parse($argv)) { return; } $options = $fs->getOpts(); $args = $fs->getArgs(); $pusher = new Pusher( $options['app-key'] ?? 'app-key', $options['app-secret'] ?? 'app-secret', $options['app-id'] ?? 'app-id', [ 'host' => $options['host'], 'port' => $options['port'], 'scheme' => $options['ssl'] ? 'https' : 'http', 'encrypted' => true, 'useTLS' => $options['ssl'], ] ); $interval = $options['interval'] ?? null; $messagesBeforeStop = $options['messages'] ?? null; $totalMessages = 0; $loop->addPeriodicTimer($interval, function () use ($pusher, &$totalMessages, $messagesBeforeStop, $loop) { if ($messagesBeforeStop && $totalMessages >= $messagesBeforeStop) { echo "Sent: {$totalMessages} messages"; return $loop->stop(); } $pusher->trigger('benchmark', 'timed-message', [ 'time' => $time = Carbon::now()->getPreciseTimestamp(3), ]); $totalMessages++; if ($options['verbose'] ?? false) { echo 'Sent message with time: '.$time.PHP_EOL; } }); ================================================ FILE: bin/pm2.js ================================================ #! /usr/bin/env node const { Cli } = require('./../dist/cli/cli'); process.title = 'soketi-server'; Cli.startWithPm2(); ================================================ FILE: bin/server.js ================================================ #! /usr/bin/env node require('./../dist/cli'); process.title = 'soketi-server'; ================================================ FILE: docker-compose.yml ================================================ version: "3" networks: soketi: driver: bridge services: localstack: container_name: localstack image: localstack/localstack ports: - "4510-4530:4510-4530" - "4566:4566" - "4571:4571" environment: - SERVICES=sqs,s3 - DEBUG=1 - HOST_TMP_FOLDER=/tmp/localstack - DOCKER_HOST=unix:///var/run/docker.sock volumes: - "${TMPDIR:-/tmp}/localstack:/tmp/localstack" - "/var/run/docker.sock:/var/run/docker.sock" networks: - soketi healthcheck: test: ["CMD", "curl", "-f", "http://localhost:4566/health"] retries: 3 timeout: 5s initialize_sqs: container_name: initialize_sqs build: context: . dockerfile: Dockerfile.awslocal volumes: - ./tests/fixtures/sqs.json:/tmp/sqs.json networks: - soketi command: - sqs - create-queue - --endpoint-url=http://localstack:4566 - --queue-name=test.fifo - --region=us-east-1 - --attributes=file:///tmp/sqs.json depends_on: localstack: condition: service_healthy dynamodb: container_name: dynamodb image: amazon/dynamodb-local:1.22.0 ports: - "8000:8000" command: "-jar DynamoDBLocal.jar -sharedDb" networks: - soketi environment: AWS_ACCESS_KEY_ID: fake-id AWS_SECRET_ACCESS_KEY: fake-secret initialize_dynamodb: container_name: initialize_dynamodb image: node:18-alpine volumes: - .:/app/ networks: - soketi environment: - DYNAMODB_URL="dynamodb:8000" entrypoint: - node - /app/tests/fixtures/dynamodb_schema.js ================================================ FILE: jest.config.js ================================================ module.exports = { transform: { '^.+\\.tsx?$': 'ts-jest', }, moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'], testTimeout: 20 * 1000, collectCoverage: true, maxWorkers: 1, testRunner: 'jest-circus/runner', globals: { 'ts-jest': { isolatedModules: true, }, Uint8Array: Uint8Array, }, }; ================================================ FILE: new-connection.sh ================================================ #!/bin/bash websocat -t - autoreconnect:ws://127.0.0.1:$1/app/app-key -v --ping-interval=15 # Send this event for testing: # {"event": "pusher:subscribe", "data": { "channel": "public" } } ================================================ FILE: package.json ================================================ { "name": "@soketi/soketi", "version": "0.0.0-dev", "description": "Just another simple, fast, and resilient open-source WebSockets server.", "repository": { "type": "git", "url": "https://github.com/soketi/soketi.git" }, "main": "dist/index.js", "keywords": [ "laravel", "socket.io", "broadcasting", "events", "redis", "socket", "pusher" ], "author": "Alex Renoki", "license": "AGPL-3.0", "jshintConfig": { "esversion": 9 }, "dependencies": { "arraybuffer-to-string": "^1.0.2", "async": "^3.2.4", "aws-sdk": "^2.1426.0", "axios": "^0.27.2", "boolean": "^3.1.4", "bullmq": "^1.80.3", "colors": "1.4.0", "dot-wild": "^3.0.1", "dotenv": "^16.0.1", "ioredis": "^5.0.4", "knex": "^3.0.1", "mysql": "^2.18.1", "mysql2": "^3.5.2", "nats": "^2.7.1", "node-discover": "^1.2.1", "pg": "^8.7.1", "pm2": "^5.3.0", "prom-client": "^14.0.1", "prometheus-query": "^3.2.5", "pusher": "^5.1.0-beta", "query-string": "^7.1.0", "rate-limiter-flexible": "^2.3.8", "sqs-consumer": "^5.7.0", "uuid": "^8.3.2", "uWebSockets.js": "https://github.com/uNetworking/uWebSockets.js.git#v20.10.0", "yargs": "^17.5.1" }, "devDependencies": { "@babel/plugin-proposal-decorators": "^7.18.10", "@babel/plugin-proposal-export-namespace-from": "^7.16.7", "@babel/plugin-proposal-function-sent": "^7.18.6", "@babel/plugin-proposal-numeric-separator": "^7.16.7", "@babel/plugin-proposal-throw-expressions": "^7.16.7", "@babel/plugin-transform-object-assign": "^7.16.7", "@babel/preset-env": "^7.18.2", "@types/bull": "^3.15.9", "@types/express": "^4.17.13", "@types/jest": "^28.1.6", "@types/node": "^18.7.6", "@types/pusher-js": "^5.1.0", "@typescript-eslint/eslint-plugin": "^5.33.1", "@typescript-eslint/parser": "^5.33.1", "body-parser": "^1.20.0", "eslint": "^8.6.0", "express": "^4.18.1", "jest": "^26.6.3", "jest-circus": "^26.6.3", "pusher-js": "^7.1.1-beta", "tcp-port-used": "^1.0.2", "ts-jest": "^26.5.6", "tslib": "^2.3.1", "typescript": "^4.5.4" }, "scripts": { "build": "node node_modules/typescript/bin/tsc", "build:watch": "npm run build -- -W", "lint": "eslint --ext .js,.ts ./src", "prepublish": "npm run build", "test": "jest --detectOpenHandles --forceExit --silent", "test:local": "jest --detectOpenHandles --forceExit --verbose", "test:watch": "npm test -- --watch" }, "bin": { "soketi": "bin/server.js", "soketi-pm2": "bin/pm2.js" }, "peerDependencies": { "@pm2/agent": "^2.0.3" } } ================================================ FILE: src/adapters/adapter-interface.ts ================================================ import { Namespace } from '../namespace'; import { PresenceMemberInfo } from '../channels/presence-channel-manager'; import { WebSocket } from 'uWebSockets.js'; const Discover = require('node-discover'); export interface AdapterInterface { /** * The app connections storage class to manage connections. */ namespaces?: Map; /** * The list of nodes in the current private network. */ driver?: AdapterInterface; /** * Initialize the adapter. */ init(): Promise; /** * Get the app namespace. */ getNamespace(appId: string): Namespace; /** * Get all namespaces. */ getNamespaces(): Map; /** * Add a new socket to the namespace. */ addSocket(appId: string, ws: WebSocket): Promise; /** * Remove a socket from the namespace. */ removeSocket(appId: string, wsId: string): Promise; /** * Add a socket ID to the channel identifier. * Return the total number of connections after the connection. */ addToChannel(appId: string, channel: string, ws: WebSocket): Promise; /** * Remove a socket ID from the channel identifier. * Return the total number of connections remaining to the channel. */ removeFromChannel(appId: string, channel: string|string[], wsId: string): Promise; /** * Send a message to a namespace and channel. */ send(appId: string, channel: string, data: string, exceptingId?: string|null): any; /** * Terminate an User ID's connections. */ terminateUserConnections(appId: string, userId: number|string): void; /** * Clear the connection for the adapter. */ disconnect(): Promise; /** * Clear the namespace from the local adapter. */ clearNamespace(namespaceId: string): Promise; /** * Clear all namespaces from the local adapter. */ clearNamespaces(): Promise; /** * Get all sockets from the namespace. */ getSockets(appId: string, onlyLocal?: boolean): Promise>; /** * Get total sockets count. */ getSocketsCount(appId: string, onlyLocal?: boolean): Promise; /** * Get the list of channels with the websocket IDs. */ getChannels(appId: string, onlyLocal?: boolean): Promise>>; /** * Get the list of channels with the websockets count. */ getChannelsWithSocketsCount(appId: string, onlyLocal?: boolean): Promise>; /** * Get all the channel sockets associated with a namespace. */ getChannelSockets(appId: string, channel: string, onlyLocal?: boolean): Promise>; /** * Get a given channel's total sockets count. */ getChannelSocketsCount(appId: string, channel: string, onlyLocal?: boolean): Promise; /** * Get a given presence channel's members. */ getChannelMembers(appId: string, channel: string, onlyLocal?: boolean): Promise>; /** * Get a given presence channel's members count */ getChannelMembersCount(appId: string, channel: string, onlyLocal?: boolean): Promise; /** * Check if a given connection ID exists in a channel. */ isInChannel(appId: string, channel: string, wsId: string, onlyLocal?: boolean): Promise; /** * Add to the users list the associated socket connection ID. */ addUser(ws: WebSocket): Promise; /** * Remove the user associated with the connection ID. */ removeUser(ws: WebSocket): Promise; /** * Get the sockets associated with an user. */ getUserSockets(appId: string, userId: string|number): Promise>; } ================================================ FILE: src/adapters/adapter.ts ================================================ import { AdapterInterface } from './adapter-interface'; import { ClusterAdapter } from './cluster-adapter'; import { LocalAdapter } from './local-adapter'; import { Log } from '../log'; import { Namespace } from '../namespace'; import { NatsAdapter } from './nats-adapter'; import { PresenceMemberInfo } from '../channels/presence-channel-manager'; import { RedisAdapter } from './redis-adapter'; import { Server } from '../server'; import { WebSocket } from 'uWebSockets.js'; export class Adapter implements AdapterInterface { /** * The adapter driver. */ public driver: AdapterInterface; /** * Initialize adapter scaling. */ constructor(server: Server) { if (server.options.adapter.driver === 'local') { this.driver = new LocalAdapter(server); } else if (server.options.adapter.driver === 'redis') { this.driver = new RedisAdapter(server); } else if (server.options.adapter.driver === 'nats') { this.driver = new NatsAdapter(server); } else if (server.options.adapter.driver === 'cluster') { this.driver = new ClusterAdapter(server); } else { Log.error('Adapter driver not set.'); } } /** * Initialize the adapter. */ async init(): Promise { return await this.driver.init(); } /** * Get the app namespace. */ getNamespace(appId: string): Namespace { return this.driver.getNamespace(appId); } /** * Get all namespaces. */ getNamespaces(): Map { return this.driver.getNamespaces(); } /** * Add a new socket to the namespace. */ async addSocket(appId: string, ws: WebSocket): Promise { return this.driver.addSocket(appId, ws); } /** * Remove a socket from the namespace. */ async removeSocket(appId: string, wsId: string): Promise { return this.driver.removeSocket(appId, wsId); } /** * Add a socket ID to the channel identifier. * Return the total number of connections after the connection. */ async addToChannel(appId: string, channel: string, ws: WebSocket): Promise { return this.driver.addToChannel(appId, channel, ws); } /** * Remove a socket ID from the channel identifier. * Return the total number of connections remaining to the channel. */ async removeFromChannel(appId: string, channel: string|string[], wsId: string): Promise { return this.driver.removeFromChannel(appId, channel, wsId); } /** * Get all sockets from the namespace. */ async getSockets(appId: string, onlyLocal = false): Promise> { return this.driver.getSockets(appId, onlyLocal); } /** * Get total sockets count. */ async getSocketsCount(appId: string, onlyLocal?: boolean): Promise { return this.driver.getSocketsCount(appId, onlyLocal); } /** * Get the list of channels with the websocket IDs. */ async getChannels(appId: string, onlyLocal = false): Promise>> { return this.driver.getChannels(appId, onlyLocal); } /** * Get the list of channels with the websockets count. */ async getChannelsWithSocketsCount(appId: string, onlyLocal = false): Promise> { return this.driver.getChannelsWithSocketsCount(appId, onlyLocal); } /** * Get all the channel sockets associated with a namespace. */ async getChannelSockets(appId: string, channel: string, onlyLocal = false): Promise> { return this.driver.getChannelSockets(appId, channel, onlyLocal); } /** * Get a given channel's total sockets count. */ async getChannelSocketsCount(appId: string, channel: string, onlyLocal?: boolean): Promise { return this.driver.getChannelSocketsCount(appId, channel, onlyLocal); } /** * Get a given presence channel's members. */ async getChannelMembers(appId: string, channel: string, onlyLocal = false): Promise> { return this.driver.getChannelMembers(appId, channel, onlyLocal); } /** * Get a given presence channel's members count */ async getChannelMembersCount(appId: string, channel: string, onlyLocal?: boolean): Promise { return this.driver.getChannelMembersCount(appId, channel, onlyLocal); } /** * Check if a given connection ID exists in a channel. */ async isInChannel(appId: string, channel: string, wsId: string, onlyLocal?: boolean): Promise { return this.driver.isInChannel(appId, channel, wsId, onlyLocal); } /** * Send a message to a namespace and channel. */ send(appId: string, channel: string, data: string, exceptingId: string|null = null): void { return this.driver.send(appId, channel, data, exceptingId); } /** * Terminate an User ID's connections. */ terminateUserConnections(appId: string, userId: number|string): void { return this.driver.terminateUserConnections(appId, userId); } /** * Add to the users list the associated socket connection ID. */ addUser(ws: WebSocket): Promise { return this.driver.addUser(ws); } /** * Remove the user associated with the connection ID. */ removeUser(ws: WebSocket): Promise { return this.driver.removeUser(ws); } /** * Get the sockets associated with an user. */ getUserSockets(appId: string, userId: string|number): Promise> { return this.driver.getUserSockets(appId, userId); } /** * Clear the namespace from the local adapter. */ clearNamespace(namespaceId: string): Promise { return this.driver.clearNamespace(namespaceId); } /** * Clear all namespaces from the local adapter. */ clearNamespaces(): Promise { return this.driver.clearNamespaces(); } /** * Clear the connections. */ disconnect(): Promise { return this.driver.disconnect(); } } ================================================ FILE: src/adapters/cluster-adapter.ts ================================================ import { AdapterInterface } from './adapter-interface'; import { HorizontalAdapter, PubsubBroadcastedMessage } from './horizontal-adapter'; import { Server } from '../server'; export class ClusterAdapter extends HorizontalAdapter { /** * The channel to broadcast the information. */ protected channel = 'cluster-adapter'; /** * Initialize the adapter. */ constructor(server: Server) { super(server); this.channel = server.clusterPrefix(this.channel); this.requestChannel = `${this.channel}#comms#req`; this.responseChannel = `${this.channel}#comms#res`; this.requestsTimeout = server.options.adapter.cluster.requestsTimeout; } /** * Initialize the adapter. */ async init(): Promise { this.server.discover.join(this.requestChannel, this.onRequest.bind(this)); this.server.discover.join(this.responseChannel, this.onResponse.bind(this)); this.server.discover.join(this.channel, this.onMessage.bind(this)); return this; } /** * Listen for requests coming from other nodes. */ protected onRequest(msg: any): void { if (typeof msg === 'object') { msg = JSON.stringify(msg); } super.onRequest(this.requestChannel, msg); } /** * Handle a response from another node. */ protected onResponse(msg: any): void { if (typeof msg === 'object') { msg = JSON.stringify(msg); } super.onResponse(this.responseChannel, msg); } /** * Listen for message coming from other nodes to broadcast * a specific message to the local sockets. */ protected onMessage(msg: any): void { if (typeof msg === 'string') { msg = JSON.parse(msg); } let message: PubsubBroadcastedMessage = msg; const { uuid, appId, channel, data, exceptingId } = message; if (uuid === this.uuid || !appId || !channel || !data) { return; } super.sendLocally(appId, channel, data, exceptingId); } /** * Broadcast data to a given channel. */ protected broadcastToChannel(channel: string, data: string): void { this.server.discover.send(channel, data); } /** * Get the number of Discover nodes. */ protected getNumSub(): Promise { return Promise.resolve(this.server.nodes.size); } } ================================================ FILE: src/adapters/horizontal-adapter.ts ================================================ import { LocalAdapter } from './local-adapter'; import { Log } from '../log'; import { PresenceMemberInfo } from '../channels/presence-channel-manager'; import { v4 as uuidv4 } from 'uuid'; import { WebSocket } from 'uWebSockets.js'; /** * |-----> NODE1 ----> SEEKS DATA (ONREQUEST) ----> SEND TO THE NODE0 ---> NODE0 (ONRESPONSE) APPENDS DATA TO REQUEST OBJECT * | * NODE0 ---> PUBLISH TO PUBLISHER ------> |-----> NODE2 ----> SEEKS DATA (ONREQUEST) ----> SEND TO THE NODE0 ---> NODE0 (ONRESPONSE) APPENDS DATA TO REQUEST OBJECT * (IN ADAPTER METHOD) | * |-----> NODE3 ----> SEEKS DATA (ONREQUEST) ----> SEND TO THE NODE0 ---> NODE0 (ONRESPONSE) APPENDS DATA TO REQUEST OBJECT */ export enum RequestType { SOCKETS = 0, CHANNELS = 1, CHANNEL_SOCKETS = 2, CHANNEL_MEMBERS = 3, SOCKETS_COUNT = 4, CHANNEL_MEMBERS_COUNT = 5, CHANNEL_SOCKETS_COUNT = 6, SOCKET_EXISTS_IN_CHANNEL = 7, CHANNELS_WITH_SOCKETS_COUNT = 8, TERMINATE_USER_CONNECTIONS = 9, } export interface RequestExtra { numSub?: number; msgCount?: number; sockets?: Map; members?: Map; channels?: Map>; channelsWithSocketsCount?: Map; totalCount?: number; } export interface Request extends RequestExtra { appId: string; type: RequestType; time: number; resolve: Function; reject: Function; timeout: any; [other: string]: any; } export interface RequestOptions { opts?: { [key: string]: any }; } export interface RequestBody extends RequestOptions { type: RequestType; requestId: string; appId: string; } export interface Response { requestId: string; sockets?: Map; members?: [string, PresenceMemberInfo][]; channels?: [string, string[]][]; channelsWithSocketsCount?: [string, number][]; totalCount?: number; exists?: boolean; } export interface PubsubBroadcastedMessage { uuid: string; appId: string; channel: string; data: any; exceptingId?: string|null; } export abstract class HorizontalAdapter extends LocalAdapter { /** * The time (in ms) for the request to be fulfilled. */ public requestsTimeout = 5_000; /** * The channel to listen for new requests. */ protected requestChannel; /** * The channel to emit back based on the requests. */ protected responseChannel; /** * The list of current request made by this instance. */ protected requests: Map = new Map(); /** * The channel to broadcast the information. */ protected channel = 'horizontal-adapter'; /** * The UUID assigned for the current instance. */ protected uuid: string = uuidv4(); /** * The list of resolvers for each response type. */ protected resolvers = { [RequestType.SOCKETS]: { computeResponse: (request: Request, response: Response) => { if (response.sockets) { response.sockets.forEach(ws => request.sockets.set(ws.id, ws)); } }, resolveValue: (request: Request, response: Response) => { return request.sockets; }, }, [RequestType.CHANNEL_SOCKETS]: { computeResponse: (request: Request, response: Response) => { if (response.sockets) { response.sockets.forEach(ws => request.sockets.set(ws.id, ws)); } }, resolveValue: (request: Request, response: Response) => { return request.sockets; }, }, [RequestType.CHANNELS]: { computeResponse: (request: Request, response: Response) => { if (response.channels) { response.channels.forEach(([channel, connections]) => { if (request.channels.has(channel)) { connections.forEach(connection => { request.channels.set(channel, request.channels.get(channel).add(connection)); }); } else { request.channels.set(channel, new Set(connections)); } }); } }, resolveValue: (request: Request, response: Response) => { return request.channels; }, }, [RequestType.CHANNELS_WITH_SOCKETS_COUNT]: { computeResponse: (request: Request, response: Response) => { if (response.channelsWithSocketsCount) { response.channelsWithSocketsCount.forEach(([channel, connectionsCount]) => { if (request.channelsWithSocketsCount.has(channel)) { request.channelsWithSocketsCount.set( channel, request.channelsWithSocketsCount.get(channel) + connectionsCount, ); } else { request.channelsWithSocketsCount.set(channel, connectionsCount); } }); } }, resolveValue: (request: Request, response: Response) => { return request.channelsWithSocketsCount; }, }, [RequestType.CHANNEL_MEMBERS]: { computeResponse: (request: Request, response: Response) => { if (response.members) { response.members.forEach(([id, member]) => request.members.set(id, member)); } }, resolveValue: (request: Request, response: Response) => { return request.members; }, }, [RequestType.SOCKETS_COUNT]: { computeResponse: (request: Request, response: Response) => { if (typeof response.totalCount !== 'undefined') { request.totalCount += response.totalCount; } }, resolveValue: (request: Request, response: Response) => { return request.totalCount; }, }, [RequestType.CHANNEL_MEMBERS_COUNT]: { computeResponse: (request: Request, response: Response) => { if (typeof response.totalCount !== 'undefined') { request.totalCount += response.totalCount; } }, resolveValue: (request: Request, response: Response) => { return request.totalCount; }, }, [RequestType.CHANNEL_SOCKETS_COUNT]: { computeResponse: (request: Request, response: Response) => { if (typeof response.totalCount !== 'undefined') { request.totalCount += response.totalCount; } }, resolveValue: (request: Request, response: Response) => { return request.totalCount; }, }, [RequestType.SOCKET_EXISTS_IN_CHANNEL]: { computeResponse: (request: Request, response: Response) => { if (typeof response.exists !== 'undefined' && response.exists === true) { request.exists = true; } }, resolveValue: (request: Request, response: Response) => { return request.exists || false; }, }, [RequestType.TERMINATE_USER_CONNECTIONS]: { computeResponse: (request: Request, response: Response) => { // Don't need to compute any response as we won't be sending one. }, resolveValue: (request: Request, response: Response) => { return true; }, }, }; /** * Broadcast data to a given channel. */ protected abstract broadcastToChannel(channel: string, data: string): void; /** * Get the number of total subscribers subscribers. */ protected abstract getNumSub(): Promise; /** * Send a response through the response channel. */ protected sendToResponseChannel(data: string): void { this.broadcastToChannel(this.responseChannel, data); } /** * Send a request through the request channel. */ protected sendToRequestChannel(data: string): void { this.broadcastToChannel(this.requestChannel, data); } /** * Send a message to a namespace and channel. */ send(appId: string, channel: string, data: string, exceptingId: string|null = null): any { this.broadcastToChannel(this.channel, JSON.stringify({ uuid: this.uuid, appId, channel, data, exceptingId, })); this.sendLocally(appId, channel, data, exceptingId); } /** * Force local sending only for the Horizontal adapter. */ sendLocally(appId: string, channel: string, data: string, exceptingId: string|null = null): any { super.send(appId, channel, data, exceptingId); } /** * Terminate an User ID's connections. */ terminateUserConnections(appId: string, userId: number|string): void { new Promise((resolve, reject) => { this.getNumSub().then(numSub => { if (numSub <= 1) { this.terminateLocalUserConnections(appId, userId); return; } this.sendRequest( appId, RequestType.TERMINATE_USER_CONNECTIONS, resolve, reject, { numSub }, { opts: { userId } }, ); }); }); this.terminateLocalUserConnections(appId, userId); } /** * Terminate an User ID's local connections. */ terminateLocalUserConnections(appId: string, userId: number|string): void { super.terminateUserConnections(appId, userId); } /** * Get all sockets from the namespace. */ async getSockets(appId: string, onlyLocal = false): Promise> { return new Promise((resolve, reject) => { super.getSockets(appId, true).then(localSockets => { if (onlyLocal) { return resolve(localSockets); } this.getNumSub().then(numSub => { if (numSub <= 1) { return resolve(localSockets); } this.sendRequest( appId, RequestType.SOCKETS, resolve, reject, { numSub, sockets: localSockets }, ); }); }); }); } /** * Get total sockets count. */ async getSocketsCount(appId: string, onlyLocal?: boolean): Promise { return new Promise((resolve, reject) => { super.getSocketsCount(appId).then(wsCount => { if (onlyLocal) { return resolve(wsCount); } this.getNumSub().then(numSub => { if (numSub <= 1) { return resolve(wsCount); } this.sendRequest( appId, RequestType.SOCKETS_COUNT, resolve, reject, { numSub, totalCount: wsCount }, ); }); }); }); } /** * Get all sockets from the namespace. */ async getChannels(appId: string, onlyLocal = false): Promise>> { return new Promise((resolve, reject) => { super.getChannels(appId).then(localChannels => { if (onlyLocal) { resolve(localChannels); } this.getNumSub().then(numSub => { if (numSub <= 1) { return resolve(localChannels); } this.sendRequest( appId, RequestType.CHANNELS, resolve, reject, { numSub, channels: localChannels }, ); }); }); }); } /** * Get total sockets count. */ async getChannelsWithSocketsCount(appId: string, onlyLocal?: boolean): Promise> { return new Promise((resolve, reject) => { super.getChannelsWithSocketsCount(appId).then(list => { if (onlyLocal) { return resolve(list); } this.getNumSub().then(numSub => { if (numSub <= 1) { return resolve(list); } this.sendRequest( appId, RequestType.CHANNELS_WITH_SOCKETS_COUNT, resolve, reject, { numSub, channelsWithSocketsCount: list }, ); }); }); }); } /** * Get all the channel sockets associated with a namespace. */ async getChannelSockets(appId: string, channel: string, onlyLocal = false): Promise> { return new Promise((resolve, reject) => { super.getChannelSockets(appId, channel).then(localSockets => { if (onlyLocal) { return resolve(localSockets); } this.getNumSub().then(numSub => { if (numSub <= 1) { return resolve(localSockets); } this.sendRequest( appId, RequestType.CHANNEL_SOCKETS, resolve, reject, { numSub, sockets: localSockets }, { opts: { channel } }, ); }); }); }); } /** * Get a given channel's total sockets count. */ async getChannelSocketsCount(appId: string, channel: string, onlyLocal?: boolean): Promise { return new Promise((resolve, reject) => { super.getChannelSocketsCount(appId, channel).then(wsCount => { if (onlyLocal) { return resolve(wsCount); } this.getNumSub().then(numSub => { if (numSub <= 1) { return resolve(wsCount); } this.sendRequest( appId, RequestType.CHANNEL_SOCKETS_COUNT, resolve, reject, { numSub, totalCount: wsCount }, { opts: { channel } }, ); }); }); }); } /** * Get all the channel sockets associated with a namespace. */ async getChannelMembers(appId: string, channel: string, onlyLocal = false): Promise> { return new Promise((resolve, reject) => { super.getChannelMembers(appId, channel).then(localMembers => { if (onlyLocal) { return resolve(localMembers); } this.getNumSub().then(numSub => { if (numSub <= 1) { return resolve(localMembers); } return this.sendRequest( appId, RequestType.CHANNEL_MEMBERS, resolve, reject, { numSub, members: localMembers }, { opts: { channel } }, ); }); }); }); } /** * Get a given presence channel's members count */ async getChannelMembersCount(appId: string, channel: string, onlyLocal?: boolean): Promise { return new Promise((resolve, reject) => { super.getChannelMembersCount(appId, channel).then(localMembersCount => { if (onlyLocal) { return resolve(localMembersCount); } this.getNumSub().then(numSub => { if (numSub <= 1) { return resolve(localMembersCount); } this.sendRequest( appId, RequestType.CHANNEL_MEMBERS_COUNT, resolve, reject, { numSub, totalCount: localMembersCount }, { opts: { channel } }, ); }); }); }); } /** * Check if a given connection ID exists in a channel. */ async isInChannel(appId: string, channel: string, wsId: string, onlyLocal?: boolean): Promise { return new Promise((resolve, reject) => { super.isInChannel(appId, channel, wsId).then(existsLocally => { if (onlyLocal || existsLocally) { return resolve(existsLocally); } this.getNumSub().then(numSub => { if (numSub <= 1) { return resolve(existsLocally); } return this.sendRequest( appId, RequestType.SOCKET_EXISTS_IN_CHANNEL, resolve, reject, { numSub }, { opts: { channel, wsId } }, ); }); }); }); } /** * Listen for requests coming from other nodes. */ protected onRequest(channel: string, msg: string): void { let request: RequestBody; try { request = JSON.parse(msg); } catch (err) { // } let { appId } = request; if (this.server.options.debug) { Log.clusterTitle('🧠 Received request from another node'); Log.cluster({ request, channel }); } switch (request.type) { case RequestType.SOCKETS: this.processRequestFromAnotherInstance(request, () => super.getSockets(appId, true).then(sockets => { let localSockets: WebSocket[] = Array.from(sockets.values()); return { sockets: localSockets.map(ws => ({ id: ws.id, subscribedChannels: ws.subscribedChannels, presence: ws.presence, ip: ws.ip, ip2: ws.ip2, })), }; })); break; case RequestType.CHANNEL_SOCKETS: this.processRequestFromAnotherInstance(request, () => super.getChannelSockets(appId, request.opts.channel).then(sockets => { let localSockets: WebSocket[] = Array.from(sockets.values()); return { sockets: localSockets.map(ws => ({ id: ws.id, subscribedChannels: ws.subscribedChannels, presence: ws.presence, })), }; })); break; case RequestType.CHANNELS: this.processRequestFromAnotherInstance(request, () => { return super.getChannels(appId).then(localChannels => { return { channels: [...localChannels].map(([channel, connections]) => [channel, [...connections]]), }; }); }); break; case RequestType.CHANNELS_WITH_SOCKETS_COUNT: this.processRequestFromAnotherInstance(request, () => { return super.getChannelsWithSocketsCount(appId).then(channelsWithSocketsCount => { return { channelsWithSocketsCount: [...channelsWithSocketsCount] }; }); }); break; case RequestType.CHANNEL_MEMBERS: this.processRequestFromAnotherInstance(request, () => { return super.getChannelMembers(appId, request.opts.channel).then(localMembers => { return { members: [...localMembers] }; }); }); break; case RequestType.SOCKETS_COUNT: this.processRequestFromAnotherInstance(request, () => { return super.getSocketsCount(appId).then(localCount => { return { totalCount: localCount }; }); }); break; case RequestType.CHANNEL_MEMBERS_COUNT: this.processRequestFromAnotherInstance(request, () => { return super.getChannelMembersCount(appId, request.opts.channel).then(localCount => { return { totalCount: localCount }; }); }); break; case RequestType.CHANNEL_SOCKETS_COUNT: this.processRequestFromAnotherInstance(request, () => { return super.getChannelSocketsCount(appId, request.opts.channel).then(localCount => { return { totalCount: localCount }; }); }); break; case RequestType.SOCKET_EXISTS_IN_CHANNEL: this.processRequestFromAnotherInstance(request, () => { return super.isInChannel(appId, request.opts.channel, request.opts.wsId).then(existsLocally => { return { exists: existsLocally }; }); }); break; case RequestType.TERMINATE_USER_CONNECTIONS: this.processRequestFromAnotherInstance(request, () => { this.terminateLocalUserConnections(appId, request.opts.userId); return Promise.resolve(); }); break; } } /** * Handle a response from another node. */ protected onResponse(channel: string, msg: string): void { let response: Response; try { response = JSON.parse(msg); } catch (err) { // } const requestId = response.requestId; if (!requestId || !this.requests.has(requestId)) { return; } const request = this.requests.get(requestId); if (this.server.options.debug) { Log.clusterTitle('🧠 Received response from another node to our request'); Log.cluster(msg); } this.processReceivedResponse( response, this.resolvers[request.type].computeResponse.bind(this), this.resolvers[request.type].resolveValue.bind(this), ); } /** * Send a request to find more about what other subscribers * are storing in their memory. */ protected sendRequest( appId: string, type: RequestType, resolve: CallableFunction, reject: CallableFunction, requestExtra: RequestExtra = {}, requestOptions: RequestOptions = {}, ) { const requestId = uuidv4(); const timeout = setTimeout(() => { if (this.requests.has(requestId)) { if (this.server.options.debug) { Log.error(`Timeout reached while waiting for response in type ${type}. Forcing resolve with the current values.`); } this.processReceivedResponse( { requestId }, this.resolvers[type].computeResponse.bind(this), this.resolvers[type].resolveValue.bind(this), true ); } }, this.requestsTimeout); // Add the request to the local memory. this.requests.set(requestId, { appId, type, time: Date.now(), timeout, msgCount: 1, resolve, reject, ...requestExtra, }); // The message to send to other nodes. const requestToSend = JSON.stringify({ requestId, appId, type, ...requestOptions, }); this.sendToRequestChannel(requestToSend); if (this.server.options.debug) { Log.clusterTitle('✈ Sent message to other instances'); Log.cluster({ request: this.requests.get(requestId) }); } this.server.metricsManager.markHorizontalAdapterRequestSent(appId); } /** * Process the incoming request from other subscriber. */ protected processRequestFromAnotherInstance(request: RequestBody, callbackResolver: Function): void { let { requestId, appId } = request; // Do not process requests for the same node that created the request. if (this.requests.has(requestId)) { return; } callbackResolver().then(extra => { let response = JSON.stringify({ requestId, ...extra }); this.sendToResponseChannel(response); if (this.server.options.debug) { Log.clusterTitle('✈ Sent response to the instance'); Log.cluster({ response }); } this.server.metricsManager.markHorizontalAdapterRequestReceived(appId); }); } /** * Process the incoming response to a request we made. */ protected processReceivedResponse( response: Response, responseComputer: CallableFunction, promiseResolver: CallableFunction, forceResolve = false ) { const request = this.requests.get(response.requestId); request.msgCount++; responseComputer(request, response); this.server.metricsManager.markHorizontalAdapterResponseReceived(request.appId); if (forceResolve || request.msgCount === request.numSub) { clearTimeout(request.timeout); if (request.resolve) { request.resolve(promiseResolver(request, response)); this.requests.delete(response.requestId); // If the resolve was forced, it means not all nodes fulfilled the request, thus leading to timeout. this.server.metricsManager.trackHorizontalAdapterResolvedPromises(request.appId, !forceResolve); this.server.metricsManager.trackHorizontalAdapterResolveTime(request.appId, Date.now() - request.time); } } } } ================================================ FILE: src/adapters/index.ts ================================================ export * from './adapter'; export * from './adapter-interface'; export * from './cluster-adapter'; export * from './horizontal-adapter'; export * from './local-adapter'; export * from './nats-adapter'; export * from './redis-adapter'; ================================================ FILE: src/adapters/local-adapter.ts ================================================ import { AdapterInterface } from './adapter-interface'; import { Namespace } from '../namespace'; import { PresenceMemberInfo } from '../channels/presence-channel-manager'; import { Server } from '../server'; import { WebSocket } from 'uWebSockets.js'; export class LocalAdapter implements AdapterInterface { // TODO: Force disconnect a specific socket // TODO: Force disconnect all sockets from an app. /** * The app connections storage class to manage connections. */ public namespaces: Map = new Map(); /** * Initialize the adapter. */ constructor(protected server: Server) { // } /** * Initialize the adapter. */ async init(): Promise { return Promise.resolve(this); } /** * Get the app namespace. */ getNamespace(appId: string): Namespace { if (!this.namespaces.has(appId)) { this.namespaces.set(appId, new Namespace(appId)); } return this.namespaces.get(appId); } /** * Get all namespaces. */ getNamespaces(): Map { return this.namespaces; } /** * Add a new socket to the namespace. */ async addSocket(appId: string, ws: WebSocket): Promise { return this.getNamespace(appId).addSocket(ws); } /** * Remove a socket from the namespace. */ async removeSocket(appId: string, wsId: string): Promise { return this.getNamespace(appId).removeSocket(wsId); } /** * Add a socket ID to the channel identifier. * Return the total number of connections after the connection. */ async addToChannel(appId: string, channel: string, ws: WebSocket): Promise { return this.getNamespace(appId).addToChannel(ws, channel).then(() => { return this.getChannelSocketsCount(appId, channel); }); } /** * Remove a socket ID from the channel identifier. * Return the total number of connections remaining to the channel. */ async removeFromChannel(appId: string, channel: string|string[], wsId: string): Promise { return this.getNamespace(appId).removeFromChannel(wsId, channel).then((remainingConnections) => { if (!Array.isArray(channel)) { return this.getChannelSocketsCount(appId, channel); } return; }); } /** * Get all sockets from the namespace. */ async getSockets(appId: string, onlyLocal = false): Promise> { return this.getNamespace(appId).getSockets(); } /** * Get total sockets count. */ async getSocketsCount(appId: string, onlyLocal?: boolean): Promise { return this.getNamespace(appId).getSockets().then(sockets => { return sockets.size; }); } /** * Get all sockets from the namespace. */ async getChannels(appId: string, onlyLocal = false): Promise>> { return this.getNamespace(appId).getChannels(); } /** * Get channels with total sockets count. */ async getChannelsWithSocketsCount(appId: string, onlyLocal?: boolean): Promise> { return this.getNamespace(appId).getChannelsWithSocketsCount(); } /** * Get all the channel sockets associated with a namespace. */ async getChannelSockets(appId: string, channel: string, onlyLocal = false): Promise> { return this.getNamespace(appId).getChannelSockets(channel); } /** * Get a given channel's total sockets count. */ async getChannelSocketsCount(appId: string, channel: string, onlyLocal?: boolean): Promise { return this.getNamespace(appId).getChannelSockets(channel).then(sockets => { return sockets.size; }); } /** * Get a given presence channel's members. */ async getChannelMembers(appId: string, channel: string, onlyLocal = false): Promise> { return this.getNamespace(appId).getChannelMembers(channel); } /** * Get a given presence channel's members count */ async getChannelMembersCount(appId: string, channel: string, onlyLocal?: boolean): Promise { return this.getNamespace(appId).getChannelMembers(channel).then(members => { return members.size; }); } /** * Check if a given connection ID exists in a channel. */ async isInChannel(appId: string, channel: string, wsId: string, onlyLocal?: boolean): Promise { return this.getNamespace(appId).isInChannel(wsId, channel); } /** * Send a message to a namespace and channel. */ send(appId: string, channel: string, data: string, exceptingId: string|null = null): any { // For user-dedicated channels, intercept the .send() call and use custom logic. if (channel.indexOf('#server-to-user-') === 0) { let userId = channel.split('#server-to-user-').pop(); this.getUserSockets(appId, userId).then(sockets => { sockets.forEach(ws => { if (ws.sendJson) { ws.sendJson(JSON.parse(data)); } }); }); return; } this.getNamespace(appId).getChannelSockets(channel).then(sockets => { sockets.forEach((ws) => { if (exceptingId && exceptingId === ws.id) { return; } // Fix race conditions. if (ws.sendJson) { ws.sendJson(JSON.parse(data)); } }); }); } /** * Terminate an User ID's connections. */ terminateUserConnections(appId: string, userId: number|string): void { this.getNamespace(appId).terminateUserConnections(userId); } /** * Add to the users list the associated socket connection ID. */ addUser(ws: WebSocket): Promise { return this.getNamespace(ws.app.id).addUser(ws); } /** * Remove the user associated with the connection ID. */ removeUser(ws: WebSocket): Promise { return this.getNamespace(ws.app.id).removeUser(ws); } /** * Get the sockets associated with an user. */ getUserSockets(appId: string, userId: number|string): Promise> { return this.getNamespace(appId).getUserSockets(userId); } /** * Clear the connections. */ disconnect(): Promise { return Promise.resolve(); } /** * Clear the namespace from the local adapter. */ clearNamespace(namespaceId: string): Promise { this.namespaces.set(namespaceId, new Namespace(namespaceId)); return Promise.resolve(); } /** * Clear all namespaces from the local adapter. */ clearNamespaces(): Promise { this.namespaces = new Map(); return Promise.resolve(); } } ================================================ FILE: src/adapters/nats-adapter.ts ================================================ import { AdapterInterface } from './adapter-interface'; import { connect, JSONCodec, Msg, NatsConnection, StringCodec } from 'nats'; import { HorizontalAdapter, PubsubBroadcastedMessage } from './horizontal-adapter'; import { Server } from '../server'; import { timeout } from 'nats/lib/nats-base-client/util'; export class NatsAdapter extends HorizontalAdapter { /** * The channel to broadcast the information. */ protected channel = 'nats-adapter'; /** * The NATS connection. */ protected connection: NatsConnection; /** * The JSON codec. */ protected jc: any; /** * The String codec. */ protected sc: any; /** * Initialize the adapter. */ constructor(server: Server) { super(server); if (server.options.adapter.nats.prefix) { this.channel = server.options.adapter.nats.prefix + '#' + this.channel; } this.requestChannel = `${this.channel}#comms#req`; this.responseChannel = `${this.channel}#comms#res`; this.jc = JSONCodec(); this.sc = StringCodec(); this.requestsTimeout = server.options.adapter.nats.requestsTimeout; } /** * Initialize the adapter. */ async init(): Promise { return new Promise(resolve => { connect({ servers: this.server.options.adapter.nats.servers, user: this.server.options.adapter.nats.user, pass: this.server.options.adapter.nats.pass, token: this.server.options.adapter.nats.token, pingInterval: 30_000, timeout: this.server.options.adapter.nats.timeout, reconnect: false, }).then((connection) => { this.connection = connection; this.connection.subscribe(this.requestChannel, { callback: (_err, msg) => this.onRequest(msg) }); this.connection.subscribe(this.responseChannel, { callback: (_err, msg) => this.onResponse(msg) }); this.connection.subscribe(this.channel, { callback: (_err, msg) => this.onMessage(msg) }); resolve(this); }); }); } /** * Listen for requests coming from other nodes. */ protected onRequest(msg: any): void { super.onRequest(this.requestChannel, JSON.stringify(this.jc.decode(msg.data))); } /** * Handle a response from another node. */ protected onResponse(msg: any): void { super.onResponse(this.responseChannel, JSON.stringify(this.jc.decode(msg.data))); } /** * Listen for message coming from other nodes to broadcast * a specific message to the local sockets. */ protected onMessage(msg: any): void { let message: PubsubBroadcastedMessage = this.jc.decode(msg.data); const { uuid, appId, channel, data, exceptingId } = message; if (uuid === this.uuid || !appId || !channel || !data) { return; } super.sendLocally(appId, channel, data, exceptingId); } /** * Broadcast data to a given channel. */ protected broadcastToChannel(channel: string, data: string): void { this.connection.publish(channel, this.jc.encode(JSON.parse(data))); } /** * Get the number of Discover nodes. */ protected async getNumSub(): Promise { let nodesNumber = this.server.options.adapter.nats.nodesNumber; if (nodesNumber && nodesNumber > 0) { return Promise.resolve(nodesNumber); } return new Promise(resolve => { let responses: Msg[] = []; let calculateResponses = () => responses.reduce((total, response) => { let { data } = JSON.parse(this.sc.decode(response.data)) as any; return total += data.total; }, 0); let waiter = timeout(1000); waiter.finally(() => resolve(calculateResponses())); this.connection.request('$SYS.REQ.SERVER.PING.CONNZ').then(response => { responses.push(response); waiter.cancel(); waiter = timeout(200); waiter.catch(() => resolve(calculateResponses())); }); }); } /** * Clear the connections. */ disconnect(): Promise { return this.connection.close(); } } ================================================ FILE: src/adapters/redis-adapter.ts ================================================ import { AdapterInterface } from './adapter-interface'; import { HorizontalAdapter, PubsubBroadcastedMessage } from './horizontal-adapter'; import { Log } from '../log'; import Redis, { Cluster, ClusterOptions, RedisOptions } from 'ioredis'; import { Server } from '../server'; export class RedisAdapter extends HorizontalAdapter { /** * The channel to broadcast the information. */ protected channel = 'redis-adapter'; /** * The subscription client. */ protected subClient: Redis|Cluster; /** * The publishing client. */ protected pubClient: Redis|Cluster; /** * Initialize the adapter. */ constructor(server: Server) { super(server); if (server.options.adapter.redis.prefix) { this.channel = server.options.adapter.redis.prefix + '#' + this.channel; } this.requestChannel = `${this.channel}#comms#req`; this.responseChannel = `${this.channel}#comms#res`; this.requestsTimeout = server.options.adapter.redis.requestsTimeout; } /** * Initialize the adapter. */ async init(): Promise { let redisOptions: RedisOptions|ClusterOptions = { maxRetriesPerRequest: 2, retryStrategy: times => times * 2, ...this.server.options.database.redis, }; this.subClient = this.server.options.adapter.redis.clusterMode ? new Cluster(this.server.options.database.redis.clusterNodes, { ...redisOptions, ...this.server.options.adapter.redis.redisSubOptions }) : new Redis({ ...redisOptions, ...this.server.options.adapter.redis.redisSubOptions }); this.pubClient = this.server.options.adapter.redis.clusterMode ? new Cluster(this.server.options.database.redis.clusterNodes, { ...redisOptions, ...this.server.options.adapter.redis.redisPubOptions }) : new Redis({ ...redisOptions, ...this.server.options.adapter.redis.redisPubOptions }); const onError = err => { if (err) { Log.warning(err); } }; this.subClient.psubscribe(`${this.channel}*`, onError); this.subClient.on('pmessageBuffer', this.onMessage.bind(this)); this.subClient.on('messageBuffer', this.processMessage.bind(this)); this.subClient.subscribe(this.requestChannel, this.responseChannel, onError); this.pubClient.on('error', onError); this.subClient.on('error', onError); return this; } /** * Broadcast data to a given channel. */ protected broadcastToChannel(channel: string, data: string): void { this.pubClient.publish(channel, data); } /** * Process the incoming message and redirect it to the right processor. */ protected processMessage(redisChannel: string, msg: Buffer|string): void { redisChannel = redisChannel.toString(); msg = msg.toString(); if (redisChannel.startsWith(this.responseChannel)) { this.onResponse(redisChannel, msg); } else if (redisChannel.startsWith(this.requestChannel)) { this.onRequest(redisChannel, msg); } } /** * Listen for message coming from other nodes to broadcast * a specific message to the local sockets. */ protected onMessage(pattern: string, redisChannel: string, msg: Buffer|string): void { redisChannel = redisChannel.toString(); msg = msg.toString(); // This channel is just for the en-masse broadcasting, not for processing // the request-response cycle to gather info across multiple nodes. if (!redisChannel.startsWith(this.channel)) { return; } let decodedMessage: PubsubBroadcastedMessage = JSON.parse(msg); if (typeof decodedMessage !== 'object') { return; } const { uuid, appId, channel, data, exceptingId } = decodedMessage; if (uuid === this.uuid || !appId || !channel || !data) { return; } super.sendLocally(appId, channel, data, exceptingId); } /** * Get the number of Redis subscribers. */ protected getNumSub(): Promise { if (this.server.options.adapter.redis.clusterMode) { const nodes = (this.pubClient as Cluster).nodes(); return Promise.all( nodes.map((node) => node.pubsub('NUMSUB', this.requestChannel) ) ).then((values: any[]) => { let number = values.reduce((numSub, value) => { return numSub += parseInt(value[1], 10); }, 0); if (this.server.options.debug) { Log.info(`Found ${number} subscribers in the Redis cluster.`); } return number; }); } else { // RedisClient or Redis return new Promise((resolve, reject) => { this.pubClient.pubsub( 'NUMSUB', this.requestChannel, (err, numSub: [any, string]) => { if (err) { return reject(err); } let number = parseInt(numSub[1], 10); if (this.server.options.debug) { Log.info(`Found ${number} subscribers in the Redis cluster.`); } resolve(number); } ); }); } } /** * Clear the connections. */ disconnect(): Promise { return Promise.all([ this.subClient.quit(), this.pubClient.quit(), ]).then(() => { // }); } } ================================================ FILE: src/app-managers/app-manager-interface.ts ================================================ import { App } from '../app'; export interface AppManagerInterface { /** * The application manager driver. */ driver?: AppManagerInterface; /** * Find an app by given ID. */ findById(id: string): Promise; /** * Find an app by given key. */ findByKey(key: string): Promise; /** * Get the app secret by ID. */ getAppSecret(id: string): Promise; } ================================================ FILE: src/app-managers/app-manager.ts ================================================ import { App } from './../app'; import { AppManagerInterface } from './app-manager-interface'; import { ArrayAppManager } from './array-app-manager'; import { DynamoDbAppManager } from './dynamodb-app-manager'; import { Log } from '../log'; import { MysqlAppManager } from './mysql-app-manager'; import { PostgresAppManager } from './postgres-app-manager'; import { Server } from '../server'; /** * Class that controls the key/value data store. */ export class AppManager implements AppManagerInterface { /** * The application manager driver. */ public driver: AppManagerInterface; /** * Create a new database instance. */ constructor(protected server: Server) { if (server.options.appManager.driver === 'array') { this.driver = new ArrayAppManager(server); } else if (server.options.appManager.driver === 'mysql') { this.driver = new MysqlAppManager(server); } else if (server.options.appManager.driver === 'postgres') { this.driver = new PostgresAppManager(server); } else if (server.options.appManager.driver === 'dynamodb') { this.driver = new DynamoDbAppManager(server); } else { Log.error('Clients driver not set.'); } } /** * Find an app by given ID. */ findById(id: string): Promise { if (!this.server.options.appManager.cache.enabled) { return this.driver.findById(id); } return this.server.cacheManager.get(`app:${id}`).then(appFromCache => { if (appFromCache) { return new App(JSON.parse(appFromCache), this.server); } return this.driver.findById(id).then(app => { this.server.cacheManager.set(`app:${id}`, app ? app.toJson() : app, this.server.options.appManager.cache.ttl); return app; }); }); } /** * Find an app by given key. */ findByKey(key: string): Promise { if (!this.server.options.appManager.cache.enabled) { return this.driver.findByKey(key); } return this.server.cacheManager.get(`app:${key}`).then(appFromCache => { if (appFromCache) { return new App(JSON.parse(appFromCache), this.server); } return this.driver.findByKey(key).then(app => { this.server.cacheManager.set(`app:${key}`, app ? app.toJson() : app, this.server.options.appManager.cache.ttl); return app; }); }); } /** * Get the app secret by ID. */ getAppSecret(id: string): Promise { return this.driver.getAppSecret(id); } } ================================================ FILE: src/app-managers/array-app-manager.ts ================================================ import { App } from '../app'; import { BaseAppManager } from './base-app-manager'; import { Log } from '../log'; import { Server } from '../server'; export class ArrayAppManager extends BaseAppManager { /** * Create a new app manager instance. */ constructor(protected server: Server) { super(); } /** * Find an app by given ID. */ findById(id: string): Promise { return new Promise(resolve => { let app = this.server.options.appManager.array.apps.find(app => app.id == id); if (typeof app !== 'undefined') { resolve(new App(app, this.server)); } else { if (this.server.options.debug) { Log.error(`App ID not found: ${id}`); } resolve(null); } }); } /** * Find an app by given key. */ findByKey(key: string): Promise { return new Promise(resolve => { let app = this.server.options.appManager.array.apps.find(app => app.key == key); if (typeof app !== 'undefined') { resolve(new App(app, this.server)); } else { if (this.server.options.debug) { Log.error(`App key not found: ${key}`); } resolve(null); } }); } } ================================================ FILE: src/app-managers/base-app-manager.ts ================================================ import { App } from '../app'; import { AppManagerInterface } from './app-manager-interface'; export class BaseAppManager implements AppManagerInterface { /** * Find an app by given ID. */ findById(id: string): Promise { return Promise.resolve(null); } /** * Find an app by given key. */ findByKey(key: string): Promise { return Promise.resolve(null); } /** * Get the app secret by ID. */ getAppSecret(id: string): Promise { return this.findById(id).then(app => { return app ? app.secret : null; }); } } ================================================ FILE: src/app-managers/dynamodb-app-manager.ts ================================================ import { App } from '../app'; import { AttributeMap } from 'aws-sdk/clients/dynamodb'; import { BaseAppManager } from './base-app-manager'; import { boolean } from 'boolean'; import { DynamoDB } from 'aws-sdk'; import { Log } from '../log'; import { Server } from '../server'; export class DynamoDbAppManager extends BaseAppManager { /** * The DynamoDB client. */ protected dynamodb: DynamoDB; /** * Create a new app manager instance. */ constructor(protected server: Server) { super(); this.dynamodb = new DynamoDB({ apiVersion: '2012-08-10', region: server.options.appManager.dynamodb.region, endpoint: server.options.appManager.dynamodb.endpoint, }); } /** * Find an app by given ID. */ findById(id: string): Promise { return this.dynamodb.getItem({ TableName: this.server.options.appManager.dynamodb.table, Key: { AppId: { S: id }, }, }).promise().then((response) => { let item = response.Item; if (!item) { if (this.server.options.debug) { Log.error(`App ID not found: ${id}`); } return null; } return new App(this.unmarshallItem(item), this.server); }).catch(err => { if (this.server.options.debug) { Log.error('Error loading app config from dynamodb'); Log.error(err); } return null; }); } /** * Find an app by given key. */ findByKey(key: string): Promise { return this.dynamodb.query({ TableName: this.server.options.appManager.dynamodb.table, IndexName: 'AppKeyIndex', ScanIndexForward: false, Limit: 1, KeyConditionExpression: 'AppKey = :app_key', ExpressionAttributeValues: { ':app_key': { S: key }, }, }).promise().then((response) => { let item = response.Items[0] || null; if (!item) { if (this.server.options.debug) { Log.error(`App key not found: ${key}`); } return null; } return new App(this.unmarshallItem(item), this.server); }).catch(err => { if (this.server.options.debug) { Log.error('Error loading app config from dynamodb'); Log.error(err); } return null; }); } /** * Transform the marshalled item to a key-value pair. */ protected unmarshallItem(item: AttributeMap): { [key: string]: any; } { let appObject = DynamoDB.Converter.unmarshall(item); // Making sure EnableClientMessages is boolean. if (appObject.EnableClientMessages instanceof Buffer) { appObject.EnableClientMessages = boolean(appObject.EnableClientMessages.toString()); } // JSON-decoding the Webhooks field. if (typeof appObject.Webhooks === 'string') { try { appObject.Webhooks = JSON.parse(appObject.Webhooks); } catch (e) { appObject.Webhooks = []; } } return appObject; } } ================================================ FILE: src/app-managers/index.ts ================================================ export * from './app-manager'; export * from './app-manager-interface'; export * from './array-app-manager'; export * from './base-app-manager'; export * from './dynamodb-app-manager'; export * from './mysql-app-manager'; export * from './postgres-app-manager'; export * from './sql-app-manager'; ================================================ FILE: src/app-managers/mysql-app-manager.ts ================================================ import { SqlAppManager } from './sql-app-manager'; export class MysqlAppManager extends SqlAppManager { /** * Get the client name to be used by Knex. */ protected knexClientName(): string { return this.server.options.appManager.mysql.useMysql2 ? 'mysql2' : 'mysql'; } /** * Get the object connection details for Knex. */ protected knexConnectionDetails(): { [key: string]: any; } { return { ...this.server.options.database.mysql, }; } /** * Get the connection version for Knex. * For MySQL can be 5.7 or 8.0, etc. */ protected knexVersion(): string { return this.server.options.appManager.mysql.version as string; } /** * Wether the manager supports pooling. This introduces * additional settings for connection pooling. */ protected supportsPooling(): boolean { return true; } /** * Get the table name where the apps are stored. */ protected appsTableName(): string { return this.server.options.appManager.mysql.table; } } ================================================ FILE: src/app-managers/postgres-app-manager.ts ================================================ import { SqlAppManager } from './sql-app-manager'; export class PostgresAppManager extends SqlAppManager { /** * Get the client name to be used by Knex. */ protected knexClientName(): string { return 'pg'; } /** * Get the object connection details for Knex. */ protected knexConnectionDetails(): { [key: string]: any; } { return { ...this.server.options.database.postgres, }; } /** * Get the connection version for Knex. * For MySQL can be 5.7 or 8.0, etc. */ protected knexVersion(): string { return this.server.options.appManager.postgres.version as string; } /** * Wether the manager supports pooling. This introduces * additional settings for connection pooling. */ protected supportsPooling(): boolean { return true; } /** * Get the table name where the apps are stored. */ protected appsTableName(): string { return this.server.options.appManager.postgres.table; } } ================================================ FILE: src/app-managers/sql-app-manager.ts ================================================ import { App } from './../app'; import { BaseAppManager } from './base-app-manager'; import { Log } from '../log'; import { Knex, knex } from 'knex'; import { Server } from './../server'; export abstract class SqlAppManager extends BaseAppManager { /** * The Knex connection. * * @type {Knex} */ protected connection: Knex; /** * Create a new app manager instance. */ constructor(protected server: Server) { super(); let knexConfig = { client: this.knexClientName(), connection: this.knexConnectionDetails(), version: this.knexVersion(), }; if (this.supportsPooling() && server.options.databasePooling.enabled) { knexConfig = { ...knexConfig, ...{ pool: { min: server.options.databasePooling.min, max: server.options.databasePooling.max, }, }, }; } this.connection = knex(knexConfig); } /** * Find an app by given ID. */ findById(id: string): Promise { return this.selectById(id).then(apps => { if (apps.length === 0) { if (this.server.options.debug) { Log.error(`App ID not found: ${id}`); } return null; } return new App(apps[0] || apps, this.server); }); } /** * Find an app by given key. */ findByKey(key: string): Promise { return this.selectByKey(key).then(apps => { if (apps.length === 0) { if (this.server.options.debug) { Log.error(`App key not found: ${key}`); } return null; } return new App(apps[0] || apps, this.server); }); } /** * Make a Knex selection for the app ID. */ protected selectById(id: string): Promise { return this.connection(this.appsTableName()) .where('id', id) .select('*'); } /** * Make a Knex selection for the app key. */ protected selectByKey(key: string): Promise { return this.connection(this.appsTableName()) .where('key', key) .select('*'); } /** * Get the client name to be used by Knex. */ protected abstract knexClientName(): string; /** * Get the object connection details for Knex. */ protected abstract knexConnectionDetails(): { [key: string]: any; }; /** * Get the connection version for Knex. * For MySQL can be 5.7 or 8.0, etc. */ protected abstract knexVersion(): string; /** * Wether the manager supports pooling. This introduces * additional settings for connection pooling. */ protected abstract supportsPooling(): boolean; /** * Get the table name where the apps are stored. */ protected abstract appsTableName(): string; } ================================================ FILE: src/app.ts ================================================ import { HttpResponse } from 'uWebSockets.js'; import { Lambda } from 'aws-sdk'; import { Server } from './server'; const Pusher = require('pusher'); const pusherUtil = require('pusher/lib/util'); export interface AppInterface { id: string; key: string; secret: string; maxConnections: string|number; enableClientMessages: boolean; enabled: boolean; maxBackendEventsPerSecond?: string|number; maxClientEventsPerSecond: string|number; maxReadRequestsPerSecond?: string|number; webhooks?: WebhookInterface[]; maxPresenceMembersPerChannel?: string|number; maxPresenceMemberSizeInKb?: string|number; maxChannelNameLength?: number; maxEventChannelsAtOnce?: string|number; maxEventNameLength?: string|number; maxEventPayloadInKb?: string|number; maxEventBatchSize?: string|number; enableUserAuthentication?: boolean; hasClientEventWebhooks?: boolean; hasChannelOccupiedWebhooks?: boolean; hasChannelVacatedWebhooks?: boolean; hasMemberAddedWebhooks?: boolean; hasMemberRemovedWebhooks?: boolean; } export interface WebhookInterface { url?: string; headers?: { [key: string]: string; }; lambda_function?: string; event_types: string[]; filter?: { channel_name_starts_with?: string; channel_name_ends_with?: string; }; lambda: { async?: boolean; region?: string; client_options?: Lambda.Types.ClientConfiguration, }; } export class App implements AppInterface { /** * @type {string|number} */ public id: string; /** * @type {string|number} */ public key: string; /** * @type {string} */ public secret: string; /** * @type {number} */ public maxConnections: string|number; /** * @type {boolean} */ public enableClientMessages: boolean; /** * @type {boolean} */ public enabled: boolean; /** * @type {number} */ public maxBackendEventsPerSecond: string|number; /** * @type {number} */ public maxClientEventsPerSecond: string|number; /** * @type {number} */ public maxReadRequestsPerSecond: string|number; /** * @type {WebhookInterface[]} */ public webhooks: WebhookInterface[]; /** * @type {string|number} */ public maxPresenceMembersPerChannel: string|number; /** * @type {string|number} */ public maxPresenceMemberSizeInKb: string|number; /** * @type {number} */ public maxChannelNameLength: number; /** * @type {string|number} */ public maxEventChannelsAtOnce: string|number; /** * @type {string|number} */ public maxEventNameLength: string|number; /** * @type {string|number} */ public maxEventPayloadInKb: string|number; /** * @type {string|number} */ public maxEventBatchSize: string|number; /** * @type {boolean} */ public enableUserAuthentication = false; /** * @type {boolean} */ public hasClientEventWebhooks = false; /** * @type {boolean} */ public hasChannelOccupiedWebhooks = false; /** * @type {boolean} */ public hasChannelVacatedWebhooks = false; /** * @type {boolean} */ public hasMemberAddedWebhooks = false; /** * @type {boolean} */ public hasMemberRemovedWebhooks = false; /** * @type {boolean} */ public hasCacheMissedWebhooks = false; static readonly CLIENT_EVENT_WEBHOOK = 'client_event'; static readonly CHANNEL_OCCUPIED_WEBHOOK = 'channel_occupied'; static readonly CHANNEL_VACATED_WEBHOOK = 'channel_vacated'; static readonly MEMBER_ADDED_WEBHOOK = 'member_added'; static readonly MEMBER_REMOVED_WEBHOOK = 'member_removed'; static readonly CACHE_MISSED_WEBHOOK = 'cache_miss'; /** * Create a new app from object. */ constructor(public initialApp: { [key: string]: any; }, protected server: Server) { this.id = this.extractFromPassedKeys(initialApp, ['id', 'AppId'], 'app-id'); this.key = this.extractFromPassedKeys(initialApp, ['key', 'AppKey'], 'app-key'); this.secret = this.extractFromPassedKeys(initialApp, ['secret', 'AppSecret'], 'app-secret'); this.maxConnections = this.extractFromPassedKeys(initialApp, ['maxConnections', 'MaxConnections', 'max_connections'], -1); this.enableClientMessages = this.extractFromPassedKeys(initialApp, ['enableClientMessages', 'EnableClientMessages', 'enable_client_messages'], false); this.enabled = this.extractFromPassedKeys(initialApp, ['enabled', 'Enabled'], true); this.maxBackendEventsPerSecond = parseInt(this.extractFromPassedKeys(initialApp, ['maxBackendEventsPerSecond', 'MaxBackendEventsPerSecond', 'max_backend_events_per_sec'], -1)); this.maxClientEventsPerSecond = parseInt(this.extractFromPassedKeys(initialApp, ['maxClientEventsPerSecond', 'MaxClientEventsPerSecond', 'max_client_events_per_sec'], -1)); this.maxReadRequestsPerSecond = parseInt(this.extractFromPassedKeys(initialApp, ['maxReadRequestsPerSecond', 'MaxReadRequestsPerSecond', 'max_read_req_per_sec'], -1)); this.webhooks = this.transformPotentialJsonToArray(this.extractFromPassedKeys(initialApp, ['webhooks', 'Webhooks'], '[]')); this.maxPresenceMembersPerChannel = parseInt(this.extractFromPassedKeys(initialApp, ['maxPresenceMembersPerChannel', 'MaxPresenceMembersPerChannel', 'max_presence_members_per_channel'], server.options.presence.maxMembersPerChannel)); this.maxPresenceMemberSizeInKb = parseFloat(this.extractFromPassedKeys(initialApp, ['maxPresenceMemberSizeInKb', 'MaxPresenceMemberSizeInKb', 'max_presence_member_size_in_kb'], server.options.presence.maxMemberSizeInKb)); this.maxChannelNameLength = parseInt(this.extractFromPassedKeys(initialApp, ['maxChannelNameLength', 'MaxChannelNameLength', 'max_channel_name_length'], server.options.channelLimits.maxNameLength)); this.maxEventChannelsAtOnce = parseInt(this.extractFromPassedKeys(initialApp, ['maxEventChannelsAtOnce', 'MaxEventChannelsAtOnce', 'max_event_channels_at_once'], server.options.eventLimits.maxChannelsAtOnce)); this.maxEventNameLength = parseInt(this.extractFromPassedKeys(initialApp, ['maxEventNameLength', 'MaxEventNameLength', 'max_event_name_length'], server.options.eventLimits.maxNameLength)); this.maxEventPayloadInKb = parseFloat(this.extractFromPassedKeys(initialApp, ['maxEventPayloadInKb', 'MaxEventPayloadInKb', 'max_event_payload_in_kb'], server.options.eventLimits.maxPayloadInKb)); this.maxEventBatchSize = parseInt(this.extractFromPassedKeys(initialApp, ['maxEventBatchSize', 'MaxEventBatchSize', 'max_event_batch_size'], server.options.eventLimits.maxBatchSize)); this.enableUserAuthentication = this.extractFromPassedKeys(initialApp, ['enableUserAuthentication', 'EnableUserAuthentication', 'enable_user_authentication'], false); this.hasClientEventWebhooks = this.webhooks.filter(webhook => webhook.event_types.includes(App.CLIENT_EVENT_WEBHOOK)).length > 0; this.hasChannelOccupiedWebhooks = this.webhooks.filter(webhook => webhook.event_types.includes(App.CHANNEL_OCCUPIED_WEBHOOK)).length > 0; this.hasChannelVacatedWebhooks = this.webhooks.filter(webhook => webhook.event_types.includes(App.CHANNEL_VACATED_WEBHOOK)).length > 0; this.hasMemberAddedWebhooks = this.webhooks.filter(webhook => webhook.event_types.includes(App.MEMBER_ADDED_WEBHOOK)).length > 0; this.hasMemberRemovedWebhooks = this.webhooks.filter(webhook => webhook.event_types.includes(App.MEMBER_REMOVED_WEBHOOK)).length > 0; this.hasCacheMissedWebhooks = this.webhooks.filter(webhook => webhook.event_types.includes(App.CACHE_MISSED_WEBHOOK)).length > 0; } /** * Get the app represented as object. */ toObject(): AppInterface { return { id: this.id, key: this.key, secret: this.secret, maxConnections: this.maxConnections, enableClientMessages: this.enableClientMessages, enabled: this.enabled, maxBackendEventsPerSecond: this.maxBackendEventsPerSecond, maxClientEventsPerSecond: this.maxClientEventsPerSecond, maxReadRequestsPerSecond: this.maxReadRequestsPerSecond, webhooks: this.webhooks, maxPresenceMembersPerChannel: this.maxPresenceMembersPerChannel, maxPresenceMemberSizeInKb: this.maxPresenceMemberSizeInKb, maxChannelNameLength: this.maxChannelNameLength, maxEventChannelsAtOnce: this.maxEventChannelsAtOnce, maxEventNameLength: this.maxEventNameLength, maxEventPayloadInKb: this.maxEventPayloadInKb, maxEventBatchSize: this.maxEventBatchSize, enableUserAuthentication: this.enableUserAuthentication, } } /** * Get the app represented as JSON. */ toJson(): string { return JSON.stringify(this.toObject()); } /** * Strip data off the app, usually the one that's not needed from the WS's perspective. * Usually used when attached to WS connections, as they don't need these details. */ forWebSocket(): App { let app = new App(this.initialApp, this.server); // delete app.secret; delete app.maxBackendEventsPerSecond; delete app.maxReadRequestsPerSecond; delete app.webhooks; return app; } /** * Get the signing token from the request. */ signingTokenFromRequest(res: HttpResponse): string { const params = { auth_key: this.key, auth_timestamp: res.query.auth_timestamp, auth_version: res.query.auth_version, ...res.query, }; delete params['auth_signature']; delete params['body_md5'] delete params['appId']; delete params['appKey']; delete params['channelName']; if (res.rawBody || res.query['body_md5']) { params['body_md5'] = pusherUtil.getMD5(res.rawBody || ''); } return this.signingToken( res.method, res.url, pusherUtil.toOrderedArray(params).join('&'), ); } /** * Get the signing token for the given parameters. */ protected signingToken(method: string, path: string, params: string): string { let token = new Pusher.Token(this.key, this.secret); return token.sign([method, path, params].join("\n")); } /** * Due to cross-database schema, it's worth to search multiple fields in the app in order to assign it * to the local App object. For example, the local `enableClientMessages` attribute can exist as * enableClientMessages, enable_client_messages, or EnableClientMessages. With this function, we pass * the app, the list of all field posibilities, and a default value. * This check is done with a typeof check over undefined, to make sure that false booleans or 0 values * are being parsed properly and are not being ignored. */ protected extractFromPassedKeys(app: { [key: string]: any; }, parameters: string[], defaultValue: any): any { let extractedValue = defaultValue; parameters.forEach(param => { if (typeof app[param] !== 'undefined' && !['', null].includes(app[param])) { extractedValue = app[param]; } }); return extractedValue; } /** * If it's already an array, it returns the array. For an invalid JSON, it returns an empty array. * If it's a JSON-formatted string, it parses it and returns the value. */ protected transformPotentialJsonToArray(potentialJson: any): any { if (potentialJson instanceof Array) { return potentialJson; } try { let potentialArray = JSON.parse(potentialJson); if (potentialArray instanceof Array) { return potentialArray; } } catch (e) { // } return []; } } ================================================ FILE: src/cache-managers/cache-manager-interface.ts ================================================ import Redis, { Cluster } from 'ioredis'; export interface CacheManagerInterface { /** * The cache interface manager driver. */ driver?: CacheManagerInterface; /** * The Redis connection. */ redisConnection?: Redis|Cluster; /** * Check if the given key exists in cache. */ has(key: string): Promise; /** * Check if the given key exists in cache. * Returns false-returning value if cache does not exist. */ get(key: string): Promise; /** * Set or overwrite the value in the cache. */ set(key: string, value: any, ttlSeconds: number): Promise; /** * Disconnect the manager's made connections. */ disconnect(): Promise; } ================================================ FILE: src/cache-managers/cache-manager.ts ================================================ import { CacheManagerInterface } from './cache-manager-interface'; import { Log } from '../log'; import { MemoryCacheManager } from './memory-cache-manager'; import { RedisCacheManager } from './redis-cache-manager'; import { Server } from '../server'; export class CacheManager implements CacheManagerInterface { /** * The cache interface manager driver. */ public driver: CacheManagerInterface; /** * Create a new cache instance. */ constructor(protected server: Server) { if (server.options.cache.driver === 'memory') { this.driver = new MemoryCacheManager(server); } else if (server.options.cache.driver === 'redis') { this.driver = new RedisCacheManager(server); } else { Log.error('Cache driver not set.'); } } /** * Check if the given key exists in cache. */ has(key: string): Promise { return this.driver.has(key); } /** * Check if the given key exists in cache. * Returns false-returning value if cache does not exist. */ get(key: string): Promise { return this.driver.get(key); } /** * Set or overwrite the value in the cache. */ set(key: string, value: any, ttlSeconds: number): Promise { return this.driver.set(key, value, ttlSeconds); } /** * Disconnect the manager's made connections. */ disconnect(): Promise { return this.driver.disconnect(); } } ================================================ FILE: src/cache-managers/index.ts ================================================ export * from './cache-manager'; export * from './cache-manager-interface'; export * from './memory-cache-manager'; export * from './redis-cache-manager'; ================================================ FILE: src/cache-managers/memory-cache-manager.ts ================================================ import { CacheManagerInterface } from './cache-manager-interface'; import { Server } from '../server'; interface Memory { [key: string]: { value: any; ttlSeconds: number; setTime: number; }; } export class MemoryCacheManager implements CacheManagerInterface { /** * The cache storage as in-memory. */ protected memory: Memory = { // }; /** * Create a new memory cache instance. */ constructor(protected server: Server) { setInterval(() => { for (let [key, { ttlSeconds, setTime }] of Object.entries(this.memory)) { let currentTime = parseInt((new Date().getTime() / 1000) as unknown as string); if (ttlSeconds > 0 && (setTime + ttlSeconds) <= currentTime) { delete this.memory[key]; } } }, 1_000); } /** * Check if the given key exists in cache. */ has(key: string): Promise { return Promise.resolve(typeof this.memory[key] !== 'undefined' ? Boolean(this.memory[key]) : false); } /** * Get a key from the cache. * Returns false-returning value if cache does not exist. */ get(key: string): Promise { return Promise.resolve(typeof this.memory[key] !== 'undefined' ? this.memory[key].value : null); } /** * Set or overwrite the value in the cache. */ set(key: string, value: any, ttlSeconds = -1): Promise { this.memory[key] = { value, ttlSeconds, setTime: parseInt((new Date().getTime() / 1000) as unknown as string), }; return Promise.resolve(true); } /** * Disconnect the manager's made connections. */ disconnect(): Promise { this.memory = {}; return Promise.resolve(); } } ================================================ FILE: src/cache-managers/redis-cache-manager.ts ================================================ import { CacheManagerInterface } from './cache-manager-interface'; import Redis, { Cluster, ClusterOptions, RedisOptions } from 'ioredis'; import { Server } from '../server'; export class RedisCacheManager implements CacheManagerInterface { /** * The Redis connection. */ public redisConnection: Redis|Cluster; /** * Create a new Redis cache instance. */ constructor(protected server: Server) { let redisOptions: RedisOptions|ClusterOptions = { ...server.options.database.redis, ...server.options.cache.redis.redisOptions, }; this.redisConnection = server.options.cache.redis.clusterMode ? new Cluster(server.options.database.redis.clusterNodes, { scaleReads: 'slave', ...redisOptions, }) : new Redis(redisOptions); } /** * Check if the given key exists in cache. */ has(key: string): Promise { return this.get(key).then(result => { return result ? true : false; }); } /** * Get a key from the cache. * Returns false-returning value if cache does not exist. */ get(key: string): Promise { return this.redisConnection.get(key); } /** * Set or overwrite the value in the cache. */ set(key: string, value: any, ttlSeconds = -1): Promise { return ttlSeconds > 0 ? this.redisConnection.set(key, value, 'EX', ttlSeconds) : this.redisConnection.set(key, value); } /** * Disconnect the manager's made connections. */ disconnect(): Promise { return this.redisConnection.quit().then(() => { // }); } } ================================================ FILE: src/channels/encrypted-private-channel-manager.ts ================================================ import { PrivateChannelManager } from './private-channel-manager'; export class EncryptedPrivateChannelManager extends PrivateChannelManager { // } ================================================ FILE: src/channels/index.ts ================================================ export * from './encrypted-private-channel-manager'; export * from './presence-channel-manager'; export * from './private-channel-manager'; export * from './public-channel-manager'; ================================================ FILE: src/channels/presence-channel-manager.ts ================================================ import { JoinResponse, LeaveResponse } from './public-channel-manager'; import { Log } from '../log'; import { PrivateChannelManager } from './private-channel-manager'; import { PusherMessage } from '../message'; import { Utils } from '../utils'; import { WebSocket } from 'uWebSockets.js'; export interface PresenceMemberInfo { [key: string]: any; } export interface PresenceMember { user_id: number|string; user_info: PresenceMemberInfo; socket_id?: string; } export class PresenceChannelManager extends PrivateChannelManager { /** * Join the connection to the channel. */ join(ws: WebSocket, channel: string, message?: PusherMessage): Promise { return this.server.adapter.getChannelMembersCount(ws.app.id, channel).then(membersCount => { if (membersCount + 1 > ws.app.maxPresenceMembersPerChannel) { return { success: false, ws, errorCode: 4100, errorMessage: 'The maximum members per presence channel limit was reached', type: 'LimitReached', }; } let member: PresenceMember = JSON.parse(message.data.channel_data); let memberSizeInKb = Utils.dataToKilobytes(member.user_info); if (memberSizeInKb > ws.app.maxPresenceMemberSizeInKb) { return { success: false, ws, errorCode: 4301, errorMessage: `The maximum size for a channel member is ${ws.app.maxPresenceMemberSizeInKb} KB.`, type: 'LimitReached', }; } return super.join(ws, channel, message).then(response => { // Make sure to forward the response in case an error occurs. if (!response.success) { return response; } return { ...response, ...{ member, }, }; }); }).catch(err => { Log.error(err); return { success: false, ws, errorCode: 4302, errorMessage: 'A server error has occured.', type: 'ServerError', }; }); } /** * Mark the connection as closed and unsubscribe it. */ leave(ws: WebSocket, channel: string): Promise { return super.leave(ws, channel).then(response => { return { ...response, ...{ member: ws.presence.get(channel), }, }; }); } /** * Get the data to sign for the token for specific channel. */ protected getDataToSignForSignature(socketId: string, message: PusherMessage): string { return `${socketId}:${message.data.channel}:${message.data.channel_data}`; } } ================================================ FILE: src/channels/private-channel-manager.ts ================================================ import { App } from '../app'; import { JoinResponse, PublicChannelManager } from './public-channel-manager'; import { PusherMessage } from '../message'; import { WebSocket } from 'uWebSockets.js'; const Pusher = require('pusher'); export class PrivateChannelManager extends PublicChannelManager { /** * Join the connection to the channel. */ join(ws: WebSocket, channel: string, message?: PusherMessage): Promise { let passedSignature = message?.data?.auth; return this.signatureIsValid(ws.app, ws.id, message, passedSignature).then(isValid => { if (!isValid) { return { ws, success: false, errorCode: 4009, errorMessage: 'The connection is unauthorized.', authError: true, type: 'AuthError', }; } return super.join(ws, channel, message).then(joinResponse => { // If the users joined to a private channel with authentication, // proceed clearing the authentication timeout. if (joinResponse.success && ws.userAuthenticationTimeout) { clearTimeout(ws.userAuthenticationTimeout); } return joinResponse; }); }); } /** * Check is an incoming connection can subscribe. */ protected signatureIsValid(app: App, socketId: string, message: PusherMessage, signatureToCheck: string): Promise { return this.getExpectedSignature(app, socketId, message).then(expectedSignature => { return signatureToCheck === expectedSignature; }); } /** * Get the signed token from the given message, by the Socket. */ protected getExpectedSignature(app: App, socketId: string, message: PusherMessage): Promise { return new Promise(resolve => { let token = new Pusher.Token(app.key, app.secret); resolve( app.key + ':' + token.sign(this.getDataToSignForSignature(socketId, message)) ); }); } /** * Get the data to sign for the token for specific channel. */ protected getDataToSignForSignature(socketId: string, message: PusherMessage): string { return `${socketId}:${message.data.channel}`; } } ================================================ FILE: src/channels/public-channel-manager.ts ================================================ import { PresenceMember } from '../channels/presence-channel-manager'; import { PusherMessage } from '../message'; import { Server } from '../server'; import { Utils } from '../utils'; import { WebSocket } from 'uWebSockets.js'; export interface JoinResponse { ws: WebSocket; success: boolean; channelConnections?: number; authError?: boolean; member?: PresenceMember; errorMessage?: string; errorCode?: number; type?: string; } export interface LeaveResponse { left: boolean; remainingConnections?: number; member?: PresenceMember; } export class PublicChannelManager { constructor(protected server: Server) { // } /** * Join the connection to the channel. */ join(ws: WebSocket, channel: string, message?: PusherMessage): Promise { if (Utils.restrictedChannelName(channel)) { return Promise.resolve({ ws, success: false, errorCode: 4009, errorMessage: 'The channel name is not allowed. Read channel conventions: https://pusher.com/docs/channels/using_channels/channels/#channel-naming-conventions', }); } if (!ws.app) { return Promise.resolve({ ws, success: false, errorCode: 4009, errorMessage: 'Subscriptions messages should be sent after the pusher:connection_established event is received.', }); } return this.server.adapter.addToChannel(ws.app.id, channel, ws).then(connections => { return { ws, success: true, channelConnections: connections, }; }); } /** * Mark the connection as closed and unsubscribe it. */ leave(ws: WebSocket, channel: string): Promise { return this.server.adapter.removeFromChannel(ws.app.id, channel, ws.id).then((remainingConnections) => { return { left: true, remainingConnections: remainingConnections as number, }; }); } } ================================================ FILE: src/cli/cli.ts ================================================ import { readFileSync } from 'fs'; import { Log } from '..'; import { Server } from './../server'; export class Cli { /** * The server to run. */ public server: Server; /** * Allowed environment variables. * * @type {any} */ public envVariables: { [key: string]: string; } = { ADAPTER_DRIVER: 'adapter.driver', ADAPTER_CLUSTER_REQUESTS_TIMEOUT: 'adapter.cluster.requestsTimeout', ADAPTER_REDIS_PREFIX: 'adapter.redis.prefix', ADAPTER_REDIS_CLUSTER_MODE: 'adapter.redis.clusterMode', ADAPTER_REDIS_REQUESTS_TIMEOUT: 'adapter.redis.requestsTimeout', ADAPTER_REDIS_SUB_OPTIONS: 'adapter.redis.redisSubOptions', ADAPTER_REDIS_PUB_OPTIONS: 'adapter.redis.redisPubOptions', ADAPTER_NATS_PREFIX: 'adapter.nats.prefix', ADAPTER_NATS_SERVERS: 'adapter.nats.servers', ADAPTER_NATS_USER: 'adapter.nats.user', ADAPTER_NATS_PASSWORD: 'adapter.nats.pass', ADAPTER_NATS_TOKEN: 'adapter.nats.token', ADAPTER_NATS_TIMEOUT: 'adapter.nats.timeout', ADAPTER_NATS_REQUESTS_TIMEOUT: 'adapter.nats.requestsTimeout', ADAPTER_NATS_NODES_NUMBER: 'adapter.nats.nodesNumber', APP_MANAGER_DRIVER: 'appManager.driver', APP_MANAGER_CACHE_ENABLED: 'appManager.cache.enabled', APP_MANAGER_CACHE_TTL: 'appManager.cache.ttl', APP_MANAGER_DYNAMODB_TABLE: 'appManager.dynamodb.table', APP_MANAGER_DYNAMODB_REGION: 'appManager.dynamodb.region', APP_MANAGER_DYNAMODB_ENDPOINT: 'appManager.dynamodb.endpoint', APP_MANAGER_MYSQL_TABLE: 'appManager.mysql.table', APP_MANAGER_MYSQL_VERSION: 'appManager.mysql.version', APP_MANAGER_POSTGRES_TABLE: 'appManager.postgres.table', APP_MANAGER_POSTGRES_VERSION: 'appManager.postgres.version', APP_MANAGER_MYSQL_USE_V2: 'appManager.mysql.useMysql2', CHANNEL_LIMITS_MAX_NAME_LENGTH: 'channelLimits.maxNameLength', CHANNEL_CACHE_TTL: 'channelLimits.cacheTtl', CACHE_DRIVER: 'cache.driver', CACHE_REDIS_CLUSTER_MODE: 'cache.redis.clusterMode', CACHE_REDIS_OPTIONS: 'cache.redis.redisOptions', CLUSTER_CHECK_INTERVAL: 'cluster.checkInterval', CLUSTER_HOST: 'cluster.hostname', CLUSTER_IGNORE_PROCESS: 'cluster.ignoreProcess', CLUSTER_BROADCAST_ADDRESS: 'cluster.broadcast', CLUSTER_KEEPALIVE_INTERVAL: 'cluster.helloInterval', CLUSTER_MASTER_TIMEOUT: 'cluster.masterTimeout', CLUSTER_MULTICAST_ADDRESS: 'cluster.multicast', CLUSTER_NODE_TIMEOUT: 'cluster.nodeTimeout', CLUSTER_PORT: 'cluster.port', CLUSTER_PREFIX: 'cluster.prefix', CLUSTER_UNICAST_ADDRESSES: 'cluster.unicast', DEBUG: 'debug', DEFAULT_APP_ID: 'appManager.array.apps.0.id', DEFAULT_APP_KEY: 'appManager.array.apps.0.key', DEFAULT_APP_SECRET: 'appManager.array.apps.0.secret', DEFAULT_APP_MAX_CONNS: 'appManager.array.apps.0.maxConnections', DEFAULT_APP_ENABLE_CLIENT_MESSAGES: 'appManager.array.apps.0.enableClientMessages', DEFAULT_APP_ENABLED: 'appManager.array.apps.0.enabled', DEFAULT_APP_MAX_BACKEND_EVENTS_PER_SEC: 'appManager.array.apps.0.maxBackendEventsPerSecond', DEFAULT_APP_MAX_CLIENT_EVENTS_PER_SEC: 'appManager.array.apps.0.maxClientEventsPerSecond', DEFAULT_APP_MAX_READ_REQ_PER_SEC: 'appManager.array.apps.0.maxReadRequestsPerSecond', DEFAULT_APP_USER_AUTHENTICATION: 'appManager.array.apps.0.enableUserAuthentication', DEFAULT_APP_WEBHOOKS: 'appManager.array.apps.0.webhooks', DB_POOLING_ENABLED: 'databasePooling.enabled', DB_POOLING_MIN: 'databasePooling.min', DB_POOLING_MAX: 'databasePooling.max', DB_MYSQL_HOST: 'database.mysql.host', DB_MYSQL_PORT: 'database.mysql.port', DB_MYSQL_USERNAME: 'database.mysql.user', DB_MYSQL_PASSWORD: 'database.mysql.password', DB_MYSQL_DATABASE: 'database.mysql.database', DB_POSTGRES_HOST: 'database.postgres.host', DB_POSTGRES_PORT: 'database.postgres.port', DB_POSTGRES_USERNAME: 'database.postgres.user', DB_POSTGRES_PASSWORD: 'database.postgres.password', DB_POSTGRES_DATABASE: 'database.postgres.database', DB_REDIS_HOST: 'database.redis.host', DB_REDIS_PORT: 'database.redis.port', DB_REDIS_DB: 'database.redis.db', DB_REDIS_USERNAME: 'database.redis.username', DB_REDIS_PASSWORD: 'database.redis.password', DB_REDIS_KEY_PREFIX: 'database.redis.keyPrefix', DB_REDIS_SENTINELS: 'database.redis.sentinels', DB_REDIS_SENTINEL_PASSWORD: 'database.redis.sentinelPassword', DB_REDIS_CLUSTER_NODES: 'database.redis.clusterNodes', DB_REDIS_INSTANCE_NAME: 'database.redis.name', EVENT_MAX_BATCH_SIZE: 'eventLimits.maxBatchSize', EVENT_MAX_CHANNELS_AT_ONCE: 'eventLimits.maxChannelsAtOnce', EVENT_MAX_NAME_LENGTH: 'eventLimits.maxNameLength', EVENT_MAX_SIZE_IN_KB: 'eventLimits.maxPayloadInKb', HOST: 'host', HTTP_ACCEPT_TRAFFIC_MEMORY_THRESHOLD: 'httpApi.acceptTraffic.memoryThreshold', METRICS_ENABLED: 'metrics.enabled', METRICS_DRIVER: 'metrics.driver', METRICS_HOST: 'metrics.host', METRICS_PROMETHEUS_PREFIX: 'metrics.prometheus.prefix', METRICS_SERVER_PORT: 'metrics.port', MODE: 'mode', PORT: 'port', PATH_PREFIX: 'pathPrefix', PRESENCE_MAX_MEMBER_SIZE: 'presence.maxMemberSizeInKb', PRESENCE_MAX_MEMBERS: 'presence.maxMembersPerChannel', QUEUE_DRIVER: 'queue.driver', QUEUE_REDIS_CONCURRENCY: 'queue.redis.concurrency', QUEUE_REDIS_OPTIONS: 'queue.redis.redisOptions', QUEUE_REDIS_CLUSTER_MODE: 'queue.redis.clusterMode', QUEUE_SQS_REGION: 'queue.sqs.region', QUEUE_SQS_CLIENT_OPTIONS: 'queue.sqs.clientOptions', QUEUE_SQS_URL: 'queue.sqs.queueUrl', QUEUE_SQS_ENDPOINT: 'queue.sqs.endpoint', QUEUE_SQS_PROCESS_BATCH: 'queue.sqs.processBatch', QUEUE_SQS_BATCH_SIZE: 'queue.sqs.batchSize', QUEUE_SQS_POLLING_WAIT_TIME_MS: 'queue.sqs.pollingWaitTimeMs', RATE_LIMITER_DRIVER: 'rateLimiter.driver', RATE_LIMITER_REDIS_OPTIONS: 'rateLimiter.redis.redisOptions', RATE_LIMITER_REDIS_CLUSTER_MODE: 'rateLimiter.redis.clusterMode', SHUTDOWN_GRACE_PERIOD: 'shutdownGracePeriod', SSL_CERT: 'ssl.certPath', SSL_KEY: 'ssl.keyPath', SSL_PASS: 'ssl.passphrase', SSL_CA: 'ssl.caPath', USER_AUTHENTICATION_TIMEOUT: 'userAuthenticationTimeout', WEBHOOKS_BATCHING: 'webhooks.batching.enabled', WEBHOOKS_BATCHING_DURATION: 'webhooks.batching.duration', }; /** * Create new CLI instance. */ constructor(protected pm2 = false) { this.server = new Server; this.server.pm2 = pm2; } /** * Inject the .env vars into options if they exist. */ protected overwriteOptionsFromEnv(): void { require('dotenv').config(); for (let envVar in this.envVariables) { let value = process.env[`SOKETI_${envVar}`] || null; let optionKey = this.envVariables[envVar.replace('SOKETI_', '')]; if (value !== null) { let json = null; if (typeof value === 'string') { try { json = JSON.parse(value); } catch (e) { json = null; } if (json !== null) { value = json; } } let settingObject = {}; settingObject[optionKey] = value; this.server.setOptions(settingObject); } } } /** * Inject the variables from a config file. */ protected overwriteOptionsFromConfig(path?: string): void { if (!path) { return; } try { let config = JSON.parse(readFileSync(path, { encoding: 'utf-8' })); for (let optionKey in config) { let value = config[optionKey]; let settingObject = {}; settingObject[optionKey] = value; this.server.setOptions(settingObject); } } catch (e) { Log.errorTitle('There was an error while parsing the JSON in your config file. It has not been loaded.'); } } /** * Start the server. */ static async start(cliArgs: any): Promise { return (new Cli).start(cliArgs); } /** * Start the server with PM2 support. */ static async startWithPm2(cliArgs: any): Promise { return (new Cli(true)).start(cliArgs); } /** * Start the server. */ async start(cliArgs: any): Promise { this.overwriteOptionsFromConfig(cliArgs ? cliArgs.config : null); this.overwriteOptionsFromEnv(); const handleFailure = () => { this.server.stop().then(() => { process.exit(); }); } process.on('SIGINT', handleFailure); process.on('SIGHUP', handleFailure); process.on('SIGTERM', handleFailure); process.on('uncaughtException', (err, origin) => { Log.error('process uncaughtException'); Log.error({ err, origin }); handleFailure(); }); return this.server.start(); } } ================================================ FILE: src/cli/index.ts ================================================ import { Cli } from './cli'; let yargs = require('yargs') .usage('Usage: soketi [options]') .command('start', 'Start the server.', yargs => { return yargs.option('config', { describe: 'The path for the config file. (optional)'}); }, (argv) => Cli.start(argv)) .demandCommand(1, 'Please provide a valid command.') .help('help') .alias('help', 'h'); yargs.$0 = ''; let argv = yargs.argv; ================================================ FILE: src/http-handler.ts ================================================ import { App } from './app'; import async from 'async'; import { HttpResponse, RecognizedString } from 'uWebSockets.js'; import { PusherApiMessage } from './message'; import { Server } from './server'; import { Utils } from './utils'; import { Log } from './log'; const v8 = require('v8'); export interface ChannelResponse { subscription_count: number; user_count?: number; occupied: boolean; } export interface MessageCheckError { message: string; code: number; } export class HttpHandler { /** * Initialize the HTTP handler. */ constructor(protected server: Server) { // } ready(res: HttpResponse) { this.attachMiddleware(res, [ this.corkMiddleware, this.corsMiddleware, ]).then(res => { if (this.server.closing) { this.serverErrorResponse(res, 'The server is closing. Choose another server. :)'); } else { this.send(res, 'OK'); } }); } acceptTraffic(res: HttpResponse) { this.attachMiddleware(res, [ this.corsMiddleware, ]).then(res => { if (this.server.closing) { return this.serverErrorResponse(res, 'The server is closing. Choose another server. :)'); } let threshold = this.server.options.httpApi.acceptTraffic.memoryThreshold; let { rss, heapTotal, external, arrayBuffers, } = process.memoryUsage(); let totalSize = v8.getHeapStatistics().total_available_size; let usedSize = rss + heapTotal + external + arrayBuffers; let percentUsage = (usedSize / totalSize) * 100; if (threshold < percentUsage) { return this.serverErrorResponse(res, 'Low on memory here. Choose another server. :)'); } this.sendJson(res, { memory: { usedSize, totalSize, percentUsage, }, }); }); } healthCheck(res: HttpResponse) { this.attachMiddleware(res, [ this.corkMiddleware, this.corsMiddleware, ]).then(res => { this.send(res, 'OK'); }); } usage(res: HttpResponse) { this.attachMiddleware(res, [ this.corkMiddleware, this.corsMiddleware, ]).then(res => { let { rss, heapTotal, external, arrayBuffers, } = process.memoryUsage(); let totalSize = v8.getHeapStatistics().total_available_size; let usedSize = rss + heapTotal + external + arrayBuffers; let freeSize = totalSize - usedSize; let percentUsage = (usedSize / totalSize) * 100; return this.sendJson(res, { memory: { free: freeSize, used: usedSize, total: totalSize, percent: percentUsage, }, }); }); } metrics(res: HttpResponse) { this.attachMiddleware(res, [ this.corkMiddleware, this.corsMiddleware, ]).then(res => { let handleError = err => { this.serverErrorResponse(res, 'A server error has occurred.'); } if (res.query.json) { this.server.metricsManager .getMetricsAsJson() .then(metrics => { this.sendJson(res, metrics); }) .catch(handleError); } else { this.server.metricsManager .getMetricsAsPlaintext() .then(metrics => { this.send(res, metrics); }) .catch(handleError); } }); } channels(res: HttpResponse) { this.attachMiddleware(res, [ this.corkMiddleware, this.corsMiddleware, this.appMiddleware, this.authMiddleware, this.readRateLimitingMiddleware, ]).then(res => { this.server.adapter.getChannelsWithSocketsCount(res.params.appId).then(channels => { let response: { [channel: string]: ChannelResponse } = [...channels].reduce((channels, [channel, connections]) => { if (connections === 0) { return channels; } // In case ?filter_by_prefix= is specified, the channel must start with that prefix. if (res.query.filter_by_prefix && !channel.startsWith(res.query.filter_by_prefix)) { return channels; } channels[channel] = { subscription_count: connections, occupied: true, }; return channels; }, {}); return response; }).catch(err => { Log.error(err); return this.serverErrorResponse(res, 'A server error has occurred.'); }).then(channels => { let broadcastMessage = { channels }; this.server.metricsManager.markApiMessage(res.params.appId, {}, broadcastMessage); this.sendJson(res, broadcastMessage); }); }); } channel(res: HttpResponse) { this.attachMiddleware(res, [ this.corkMiddleware, this.corsMiddleware, this.appMiddleware, this.authMiddleware, this.readRateLimitingMiddleware, ]).then(res => { let response: ChannelResponse; this.server.adapter.getChannelSocketsCount(res.params.appId, res.params.channel).then(socketsCount => { response = { subscription_count: socketsCount, occupied: socketsCount > 0, }; // For presence channels, attach an user_count. // Avoid extra call to get channel members if there are no sockets. if (res.params.channel.startsWith('presence-')) { response.user_count = 0; if (response.subscription_count > 0) { this.server.adapter.getChannelMembersCount(res.params.appId, res.params.channel).then(membersCount => { let broadcastMessage = { ...response, ...{ user_count: membersCount, }, }; this.server.metricsManager.markApiMessage(res.params.appId, {}, broadcastMessage); this.sendJson(res, broadcastMessage); }).catch(err => { Log.error(err); return this.serverErrorResponse(res, 'A server error has occurred.'); }); return; } } this.server.metricsManager.markApiMessage(res.params.appId, {}, response); return this.sendJson(res, response); }).catch(err => { Log.error(err); return this.serverErrorResponse(res, 'A server error has occurred.'); }); }); } channelUsers(res: HttpResponse) { this.attachMiddleware(res, [ this.corkMiddleware, this.corsMiddleware, this.appMiddleware, this.authMiddleware, this.readRateLimitingMiddleware, ]).then(res => { if (!res.params.channel.startsWith('presence-')) { return this.badResponse(res, 'The channel must be a presence channel.'); } this.server.adapter.getChannelMembers(res.params.appId, res.params.channel).then(members => { let broadcastMessage = { users: [...members].map(([user_id, user_info]) => { return res.query.with_user_info === '1' ? { id: user_id, user_info } : { id: user_id }; }), }; this.server.metricsManager.markApiMessage(res.params.appId, {}, broadcastMessage); this.sendJson(res, broadcastMessage); }); }); } events(res: HttpResponse) { this.attachMiddleware(res, [ this.corkMiddleware, this.jsonBodyMiddleware, this.corsMiddleware, this.appMiddleware, this.authMiddleware, this.broadcastEventRateLimitingMiddleware, ]).then(res => { this.checkMessageToBroadcast(res.body as PusherApiMessage, res.app as App).then(message => { this.broadcastMessage(message, res.app.id); this.server.metricsManager.markApiMessage(res.app.id, res.body, { ok: true }); this.sendJson(res, { ok: true }); }).catch(error => { if (error.code === 400) { this.badResponse(res, error.message); } else if (error.code === 413) { this.entityTooLargeResponse(res, error.message); } }); }); } batchEvents(res: HttpResponse) { this.attachMiddleware(res, [ this.jsonBodyMiddleware, this.corsMiddleware, this.appMiddleware, this.authMiddleware, this.broadcastBatchEventsRateLimitingMiddleware, ]).then(res => { let batch = res.body.batch as PusherApiMessage[]; // Make sure the batch size is not too big. if (batch.length > res.app.maxEventBatchSize) { return this.badResponse(res, `Cannot batch-send more than ${res.app.maxEventBatchSize} messages at once`); } Promise.all(batch.map(message => this.checkMessageToBroadcast(message, res.app as App))).then(messages => { messages.forEach(message => this.broadcastMessage(message, res.app.id)); this.server.metricsManager.markApiMessage(res.app.id, res.body, { ok: true }); this.sendJson(res, { ok: true }); }).catch((error: MessageCheckError) => { if (error.code === 400) { this.badResponse(res, error.message); } else if (error.code === 413) { this.entityTooLargeResponse(res, error.message); } }); }); } terminateUserConnections(res: HttpResponse) { this.attachMiddleware(res, [ this.jsonBodyMiddleware, this.corsMiddleware, this.appMiddleware, this.authMiddleware, ]).then(res => { this.server.adapter.terminateUserConnections(res.app.id, res.params.userId); this.sendJson(res, { ok: true }); }); } protected checkMessageToBroadcast(message: PusherApiMessage, app: App): Promise { return new Promise((resolve, reject) => { if ( (!message.channels && !message.channel) || !message.name || !message.data ) { return reject({ message: 'The received data is incorrect', code: 400, }); } let channels: string[] = message.channels || [message.channel]; message.channels = channels; // Make sure the channels length is not too big. if (channels.length > app.maxEventChannelsAtOnce) { return reject({ message: `Cannot broadcast to more than ${app.maxEventChannelsAtOnce} channels at once`, code: 400, }); } // Make sure the event name length is not too big. if (message.name.length > app.maxEventNameLength) { return reject({ message: `Event name is too long. Maximum allowed size is ${app.maxEventNameLength}.`, code: 400, }); } let payloadSizeInKb = Utils.dataToKilobytes(message.data); // Make sure the total payload of the message body is not too big. if (payloadSizeInKb > parseFloat(app.maxEventPayloadInKb as string)) { return reject({ message: `The event data should be less than ${app.maxEventPayloadInKb} KB.`, code: 413, }); } resolve(message); }); } protected broadcastMessage(message: PusherApiMessage, appId: string): void { message.channels.forEach(channel => { let msg = { event: message.name, channel, data: message.data, }; this.server.adapter.send(appId, channel, JSON.stringify(msg), message.socket_id); if (Utils.isCachingChannel(channel)) { this.server.cacheManager.set( `app:${appId}:channel:${channel}:cache_miss`, JSON.stringify({ event: msg.event, data: msg.data }), this.server.options.channelLimits.cacheTtl, ); } }); } notFound(res: HttpResponse) { try { res.writeStatus('404 Not Found'); this.attachMiddleware(res, [ this.corkMiddleware, this.corsMiddleware, ]).then(res => { this.send(res, '', '404 Not Found'); }); } catch (e) { Log.warningTitle('Response could not be sent'); Log.warning(e); } } protected badResponse(res: HttpResponse, error: string) { return this.sendJson(res, { error, code: 400 }, '400 Invalid Request'); } protected notFoundResponse(res: HttpResponse, error: string) { return this.sendJson(res, { error, code: 404 }, '404 Not Found'); } protected unauthorizedResponse(res: HttpResponse, error: string) { return this.sendJson(res, { error, code: 401 }, '401 Authorization Required'); } protected entityTooLargeResponse(res: HttpResponse, error: string) { return this.sendJson(res, { error, code: 413 }, '413 Payload Too Large'); } protected tooManyRequestsResponse(res: HttpResponse) { return this.sendJson(res, { error: 'Too many requests.', code: 429 }, '429 Too Many Requests'); } protected serverErrorResponse(res: HttpResponse, error: string) { return this.sendJson(res, { error, code: 500 }, '500 Internal Server Error'); } protected jsonBodyMiddleware(res: HttpResponse, next: CallableFunction): any { this.readJson(res, (body, rawBody) => { res.body = body; res.rawBody = rawBody; let requestSizeInMb = Utils.dataToMegabytes(rawBody); if (requestSizeInMb > this.server.options.httpApi.requestLimitInMb) { return this.entityTooLargeResponse(res, 'The payload size is too big.'); } next(null, res); }, err => { return this.badResponse(res, 'The received data is incorrect.'); }); } protected corkMiddleware(res: HttpResponse, next: CallableFunction): any { res.cork(() => next(null, res)); } protected corsMiddleware(res: HttpResponse, next: CallableFunction): any { res.writeHeader('Access-Control-Allow-Origin', this.server.options.cors.origin.join(', ')); res.writeHeader('Access-Control-Allow-Methods', this.server.options.cors.methods.join(', ')); res.writeHeader('Access-Control-Allow-Headers', this.server.options.cors.allowedHeaders.join(', ')); next(null, res); } protected appMiddleware(res: HttpResponse, next: CallableFunction): any { return this.server.appManager.findById(res.params.appId).then(validApp => { if (!validApp) { return this.notFoundResponse(res, `The app ${res.params.appId} could not be found.`); } res.app = validApp; next(null, res); }); } protected authMiddleware(res: HttpResponse, next: CallableFunction): any { this.signatureIsValid(res).then(valid => { if (valid) { return next(null, res); } return this.unauthorizedResponse(res, 'The secret authentication failed'); }); } protected readRateLimitingMiddleware(res: HttpResponse, next: CallableFunction): any { this.server.rateLimiter.consumeReadRequestsPoints(1, res.app).then(response => { if (response.canContinue) { for (let header in response.headers) { res.writeHeader(header, '' + response.headers[header]); } return next(null, res); } this.tooManyRequestsResponse(res); }); } protected broadcastEventRateLimitingMiddleware(res: HttpResponse, next: CallableFunction): any { let channels = res.body.channels || [res.body.channel]; this.server.rateLimiter.consumeBackendEventPoints(Math.max(channels.length, 1), res.app).then(response => { if (response.canContinue) { for (let header in response.headers) { res.writeHeader(header, '' + response.headers[header]); } return next(null, res); } this.tooManyRequestsResponse(res); }); } protected broadcastBatchEventsRateLimitingMiddleware(res: HttpResponse, next: CallableFunction): any { let rateLimiterPoints = res.body.batch.reduce((rateLimiterPoints, event) => { let channels: string[] = event.channels || [event.channel]; return rateLimiterPoints += channels.length; }, 0); this.server.rateLimiter.consumeBackendEventPoints(rateLimiterPoints, res.app).then(response => { if (response.canContinue) { for (let header in response.headers) { res.writeHeader(header, '' + response.headers[header]); } return next(null, res); } this.tooManyRequestsResponse(res); }); } protected attachMiddleware(res: HttpResponse, functions: any[]): Promise { return new Promise((resolve, reject) => { let waterfallInit = callback => callback(null, res); let abortHandlerMiddleware = (res, callback) => { res.onAborted(() => { Log.warning({ message: 'Aborted request.', res }); // this.serverErrorResponse(res, 'Aborted request.'); }); callback(null, res); }; async.waterfall([ waterfallInit.bind(this), abortHandlerMiddleware.bind(this), ...functions.map(fn => fn.bind(this)), ], (err, res) => { if (err) { this.serverErrorResponse(res, 'A server error has occurred.'); Log.error(err); return reject({ res, err }); } resolve(res); }); }); } /** * Read the JSON content of a request. */ protected readJson(res: HttpResponse, cb: CallableFunction, err: any) { let buffer; let loggingAction = (payload) => { if (this.server.options.debug) { Log.httpTitle('⚡ HTTP Payload received'); Log.http(payload); } }; res.onData((ab, isLast) => { let chunk = Buffer.from(ab); if (isLast) { let json = {}; let raw = '{}'; if (buffer) { try { // @ts-ignore json = JSON.parse(Buffer.concat([buffer, chunk])); } catch (e) { // } try { raw = Buffer.concat([buffer, chunk]).toString(); } catch (e) { // } cb(json, raw); loggingAction(json); } else { try { // @ts-ignore json = JSON.parse(chunk); raw = chunk.toString(); } catch (e) { // } cb(json, raw); loggingAction(json); } } else { if (buffer) { buffer = Buffer.concat([buffer, chunk]); } else { buffer = Buffer.concat([chunk]); } } }); res.onAborted(err); } /** * Check is an incoming request can access the api. */ protected signatureIsValid(res: HttpResponse): Promise { return this.getSignedToken(res).then(token => { return token === res.query.auth_signature; }); } protected sendJson(res: HttpResponse, data: any, status: RecognizedString = '200 OK') { try { return res.writeStatus(status) .writeHeader('Content-Type', 'application/json') .end(JSON.stringify(data), true); } catch (e) { Log.warningTitle('Response could not be sent'); Log.warning(e); } } protected send(res: HttpResponse, data: RecognizedString, status: RecognizedString = '200 OK') { try { return res.writeStatus(status).end(data, true); } catch (e) { Log.warningTitle('Response could not be sent'); Log.warning(e); } } /** * Get the signed token from the given request. */ protected getSignedToken(res: HttpResponse): Promise { return Promise.resolve(res.app.signingTokenFromRequest(res)); } } ================================================ FILE: src/index.ts ================================================ export * from './app'; export * from './http-handler'; export * from './job'; export * from './log'; export * from './namespace'; export * from './options'; export * from './server'; export * from './utils'; export * from './webhook-sender'; export * from './ws-handler'; ================================================ FILE: src/job.ts ================================================ import { v4 as uuidv4 } from 'uuid'; export class Job { /** * Create a new job instance. */ constructor(public id: string = uuidv4(), public data: { [key: string]: any; } = {}) { // } } ================================================ FILE: src/log.ts ================================================ const colors = require('colors'); export class Log { static infoTitle(message: any): void { this.log(message, 'bold', 'black', 'bgCyan', 'mx-2', 'px-1'); } static successTitle(message: any): void { this.log(message, 'bold', 'black', 'bgGreen', 'mx-2', 'px-1'); } static errorTitle(message: any): void { this.log(this.prefixWithTime(message), 'bold', 'black', 'bgRed', 'mx-2', 'px-1'); } static warningTitle(message: any): void { this.log(this.prefixWithTime(message), 'bold', 'black', 'bgYellow', 'mx-2', 'px-1'); } static clusterTitle(message: any): void { this.log(this.prefixWithTime(message), 'bold', 'yellow', 'bgMagenta', 'mx-2', 'px-1'); } static httpTitle(message: any): void { this.infoTitle(this.prefixWithTime(message)); } static discoverTitle(message: any): void { this.log(this.prefixWithTime(message), 'bold', 'gray', 'bgBrightCyan', 'mx-2', 'px-1'); } static websocketTitle(message: any): void { this.successTitle(this.prefixWithTime(message)); } static webhookSenderTitle(message: any): void { this.log(this.prefixWithTime(message), 'bold', 'blue', 'bgWhite', 'mx-2', 'px-1'); } static info(message: any): void { this.log(message, 'cyan', 'mx-2'); } static success(message: any): void { this.log(message, 'green', 'mx-2'); } static error(message: any): void { this.log(message, 'red', 'mx-2'); } static warning(message: any): void { this.log(message, 'yellow', 'mx-2'); } static cluster(message: any): void { this.log(message, 'bold', 'magenta', 'mx-2'); } static http(message: any): void { this.info(message); } static discover(message: any): void { this.log(message, 'bold', 'brightCyan', 'mx-2'); } static websocket(message: any): void { this.success(message); } static webhookSender(message: any): void { this.log(message, 'bold', 'white', 'mx-2'); } static br(): void { console.log(''); } protected static prefixWithTime(message: any): any { if (typeof message === 'string') { return '[' + (new Date).toString() + '] ' + message; } return message; } protected static log(message: any, ...styles: string[]): void { let withColor = colors; if (typeof message !== 'string') { return console.log(message); } styles .filter(style => ! /^[m|p]x-/.test(style)) .forEach((style) => withColor = withColor[style]); const applyMargins = (message: string): string => { const spaces = styles .filter(style => /^mx-/.test(style)) .map(style => ' '.repeat(parseInt(style.substr(3)))) .join(''); return spaces + message + spaces; } const applyPadding = (message: string): string => { const spaces = styles .filter(style => /^px-/.test(style)) .map(style => ' '.repeat(parseInt(style.substr(3)))) .join(''); return spaces + message + spaces; } console.log(applyMargins(withColor(applyPadding(message)))); } } ================================================ FILE: src/message.ts ================================================ export interface MessageData { channel_data?: string; channel?: string; user_data?: string; [key: string]: any; } export interface PusherMessage { channel?: string; name?: string; event?: string; data?: MessageData; } export interface PusherApiMessage { name?: string; data?: string|{ [key: string]: any }; channel?: string; channels?: string[]; socket_id?: string; } export interface SentPusherMessage { channel?: string; event?: string; data?: MessageData|string; } export type uWebSocketMessage = ArrayBuffer|PusherMessage; ================================================ FILE: src/metrics/index.ts ================================================ export * from './metrics'; export * from './metrics-interface'; export * from './prometheus-metrics-driver'; ================================================ FILE: src/metrics/metrics-interface.ts ================================================ import * as prom from 'prom-client'; import { WebSocket } from 'uWebSockets.js'; export interface MetricsInterface { /** * The Metrics driver. */ driver?: MetricsInterface; /** * Handle a new connection. */ markNewConnection(ws: WebSocket): void; /** * Handle a disconnection. */ markDisconnection(ws: WebSocket): void; /** * Handle a new API message event being received and sent out. */ markApiMessage(appId: string, incomingMessage: any, sentMessage: any): void; /** * Handle a new WS client message event being sent. */ markWsMessageSent(appId: string, sentMessage: any): void; /** * Handle a new WS client message being received. */ markWsMessageReceived(appId: string, message: any): void; /** * Track the time in which horizontal adapter resolves requests from other nodes. */ trackHorizontalAdapterResolveTime(appId: string, time: number): void; /** * Track the fulfillings in which horizontal adapter resolves requests from other nodes. */ trackHorizontalAdapterResolvedPromises(appId: string, resolved?: boolean): void; /** * Handle a new horizontal adapter request sent. */ markHorizontalAdapterRequestSent(appId: string): void; /** * Handle a new horizontal adapter request that was marked as received. */ markHorizontalAdapterRequestReceived(appId: string): void; /** * Handle a new horizontal adapter response from other node. */ markHorizontalAdapterResponseReceived(appId: string): void; /** * Get the stored metrics as plain text, if possible. */ getMetricsAsPlaintext(): Promise; /** * Get the stored metrics as JSON. */ getMetricsAsJson(): Promise; /** * Reset the metrics at the server level. */ clear(): Promise; } ================================================ FILE: src/metrics/metrics.ts ================================================ import * as prom from 'prom-client'; import { WebSocket } from 'uWebSockets.js'; import { Log } from './../log'; import { MetricsInterface } from './metrics-interface'; import { PrometheusMetricsDriver } from './prometheus-metrics-driver'; import { Server } from '../server'; export class Metrics implements MetricsInterface { /** * The Metrics driver. */ public driver: MetricsInterface; /** * Initialize the Prometheus exporter. */ constructor(protected server: Server) { if (server.options.metrics.driver === 'prometheus') { this.driver = new PrometheusMetricsDriver(server); } else { Log.error('No metrics driver specified.'); } } /** * Handle a new connection. */ markNewConnection(ws: WebSocket): void { if (this.server.options.metrics.enabled) { this.driver.markNewConnection(ws); } } /** * Handle a disconnection. */ markDisconnection(ws: WebSocket): void { if (this.server.options.metrics.enabled) { this.driver.markDisconnection(ws); } } /** * Handle a new API message event being received and sent out. */ markApiMessage(appId: string, incomingMessage: any, sentMessage: any): void { if (this.server.options.metrics.enabled) { this.driver.markApiMessage(appId, incomingMessage, sentMessage); } } /** * Handle a new WS client message event being sent. */ markWsMessageSent(appId: string, sentMessage: any): void { if (this.server.options.metrics.enabled) { this.driver.markWsMessageSent(appId, sentMessage); } } /** * Handle a new WS client message being received. */ markWsMessageReceived(appId: string, message: any): void { if (this.server.options.metrics.enabled) { this.driver.markWsMessageReceived(appId, message); } } /** * Track the time in which horizontal adapter resolves requests from other nodes. */ trackHorizontalAdapterResolveTime(appId: string, time: number): void { this.driver.trackHorizontalAdapterResolveTime(appId, time); } /** * Track the fulfillings in which horizontal adapter resolves requests from other nodes. */ trackHorizontalAdapterResolvedPromises(appId: string, resolved = true): void { this.driver.trackHorizontalAdapterResolvedPromises(appId, resolved); } /** * Handle a new horizontal adapter request sent. */ markHorizontalAdapterRequestSent(appId: string): void { this.driver.markHorizontalAdapterRequestSent(appId); } /** * Handle a new horizontal adapter request that was marked as received. */ markHorizontalAdapterRequestReceived(appId: string): void { this.driver.markHorizontalAdapterRequestReceived(appId); } /** * Handle a new horizontal adapter response from other node. */ markHorizontalAdapterResponseReceived(appId: string): void { this.driver.markHorizontalAdapterResponseReceived(appId); } /** * Get the stored metrics as plain text, if possible. */ getMetricsAsPlaintext(): Promise { if (!this.server.options.metrics.enabled) { return Promise.resolve(''); } return this.driver.getMetricsAsPlaintext(); } /** * Get the stored metrics as JSON. */ getMetricsAsJson(): Promise { if (!this.server.options.metrics.enabled) { return Promise.resolve(); } return this.driver.getMetricsAsJson(); } /** * Reset the metrics at the server level. */ clear(): Promise { return this.driver.clear(); } } ================================================ FILE: src/metrics/prometheus-metrics-driver.ts ================================================ import * as prom from 'prom-client'; import { WebSocket } from 'uWebSockets.js'; import { MetricsInterface } from './metrics-interface'; import { Server } from '../server'; import { Utils } from '../utils'; interface PrometheusMetrics { connectedSockets?: prom.Gauge<'app_id'|'port'>; newConnectionsTotal?: prom.Counter<'app_id'|'port'>; newDisconnectionsTotal?: prom.Counter<'app_id'|'port'>; socketBytesReceived?: prom.Counter<'app_id'|'port'>; socketBytesTransmitted?: prom.Counter<'app_id'|'port'>; wsMessagesReceived?: prom.Counter<'app_id'|'port'>; wsMessagesSent?: prom.Counter<'app_id'|'port'>; httpBytesReceived?: prom.Counter<'app_id'|'port'>; httpBytesTransmitted?: prom.Counter<'app_id'|'port'>; httpCallsReceived?: prom.Counter<'app_id'|'port'>; horizontalAdapterResolveTime?: prom.Histogram<'app_id'|'port'>; horizontalAdapterResolvedPromises?: prom.Counter<'app_id'|'port'>; horizontalAdapterUncompletePromises?: prom.Counter<'app_id'|'port'>; horizontalAdapterSentRequests?: prom.Counter<'app_id'|'port'>; horizontalAdapterReceivedRequests?: prom.Counter<'app_id'|'port'>; horizontalAdapterReceivedResponses?: prom.Counter<'app_id'|'port'>; } interface InfraMetadata { [key: string]: any; } interface NamespaceTags { app_id: string; [key: string]: any; } export class PrometheusMetricsDriver implements MetricsInterface { /** * The list of metrics that will register. * * @type {PrometheusMetrics} */ protected metrics: PrometheusMetrics = { // TODO: Metrics for subscribes/unsubscribes/client events? }; /** * Prometheus register repo. * * @type {prom.Registry} */ register: prom.Registry; /** * The infra-related metadata. * * @type {InfraMetadata} */ protected infraMetadata: InfraMetadata = { // }; /** * Initialize the Prometheus exporter. */ constructor(protected server: Server) { this.register = new prom.Registry(); this.registerMetrics(); this.infraMetadata = { port: server.options.port }; prom.collectDefaultMetrics({ prefix: server.options.metrics.prometheus.prefix, register: this.register, labels: this.infraMetadata, }); } /** * Handle a new connection. */ markNewConnection(ws: WebSocket): void { this.metrics.connectedSockets.inc(this.getTags(ws.app.id)); this.metrics.newConnectionsTotal.inc(this.getTags(ws.app.id)); } /** * Handle a disconnection. */ markDisconnection(ws: WebSocket): void { this.metrics.connectedSockets.dec(this.getTags(ws.app.id)); this.metrics.newDisconnectionsTotal.inc(this.getTags(ws.app.id)); } /** * Handle a new API message event being received and sent out. */ markApiMessage(appId: string, incomingMessage: any, sentMessage: any): void { this.metrics.httpBytesReceived.inc(this.getTags(appId), Utils.dataToBytes(incomingMessage)); this.metrics.httpBytesTransmitted.inc(this.getTags(appId), Utils.dataToBytes(sentMessage)); this.metrics.httpCallsReceived.inc(this.getTags(appId)); } /** * Handle a new WS client message event being sent. */ markWsMessageSent(appId: string, sentMessage: any): void { this.metrics.socketBytesTransmitted.inc(this.getTags(appId), Utils.dataToBytes(sentMessage)); this.metrics.wsMessagesSent.inc(this.getTags(appId), 1); } /** * Handle a new WS client message being received. */ markWsMessageReceived(appId: string, message: any): void { this.metrics.socketBytesReceived.inc(this.getTags(appId), Utils.dataToBytes(message)); this.metrics.wsMessagesReceived.inc(this.getTags(appId), 1); } /** * Track the time in which horizontal adapter resolves requests from other nodes. */ trackHorizontalAdapterResolveTime(appId: string, time: number): void { this.metrics.horizontalAdapterResolveTime.observe(this.getTags(appId), time); } /** * Track the fulfillings in which horizontal adapter resolves requests from other nodes. */ trackHorizontalAdapterResolvedPromises(appId: string, resolved = true): void { if (resolved) { this.metrics.horizontalAdapterResolvedPromises.inc(this.getTags(appId)); } else { this.metrics.horizontalAdapterUncompletePromises.inc(this.getTags(appId)); } } /** * Handle a new horizontal adapter request sent. */ markHorizontalAdapterRequestSent(appId: string): void { this.metrics.horizontalAdapterSentRequests.inc(this.getTags(appId)); } /** * Handle a new horizontal adapter request that was marked as received. */ markHorizontalAdapterRequestReceived(appId: string): void { this.metrics.horizontalAdapterReceivedRequests.inc(this.getTags(appId)); } /** * Handle a new horizontal adapter response from other node. */ markHorizontalAdapterResponseReceived(appId: string): void { this.metrics.horizontalAdapterReceivedResponses.inc(this.getTags(appId)); } /** * Get the stored metrics as plain text, if possible. */ getMetricsAsPlaintext(): Promise { return this.register.metrics(); } /** * Get the stored metrics as JSON. */ getMetricsAsJson(): Promise { return this.register.getMetricsAsJSON(); } /** * Reset the metrics at the server level. */ clear(): Promise { return Promise.resolve(this.register.clear()); } /** * Get the tags for Prometheus. */ protected getTags(appId: string): NamespaceTags { return { app_id: appId, ...this.infraMetadata, }; } protected registerMetrics(): void { let prefix = this.server.options.metrics.prometheus.prefix; this.metrics = { connectedSockets: new prom.Gauge({ name: `${prefix}connected`, help: 'The number of currently connected sockets.', labelNames: ['app_id', 'port'], registers: [this.register], }), newConnectionsTotal: new prom.Counter({ name: `${prefix}new_connections_total`, help: 'Total amount of soketi connection requests.', labelNames: ['app_id', 'port'], registers: [this.register], }), newDisconnectionsTotal: new prom.Counter({ name: `${prefix}new_disconnections_total`, help: 'Total amount of soketi disconnections.', labelNames: ['app_id', 'port'], registers: [this.register], }), socketBytesReceived: new prom.Counter({ name: `${prefix}socket_received_bytes`, help: 'Total amount of bytes that soketi received.', labelNames: ['app_id', 'port'], registers: [this.register], }), socketBytesTransmitted: new prom.Counter({ name: `${prefix}socket_transmitted_bytes`, help: 'Total amount of bytes that soketi transmitted.', labelNames: ['app_id', 'port'], registers: [this.register], }), wsMessagesReceived: new prom.Counter({ name: `${prefix}ws_messages_received_total`, help: 'The total amount of WS messages received from connections by the server.', labelNames: ['app_id', 'port'], registers: [this.register], }), wsMessagesSent: new prom.Counter({ name: `${prefix}ws_messages_sent_total`, help: 'The total amount of WS messages sent to the connections from the server.', labelNames: ['app_id', 'port'], registers: [this.register], }), httpBytesReceived: new prom.Counter({ name: `${prefix}http_received_bytes`, help: 'Total amount of bytes that soketi\'s REST API received.', labelNames: ['app_id', 'port'], registers: [this.register], }), httpBytesTransmitted: new prom.Counter({ name: `${prefix}http_transmitted_bytes`, help: 'Total amount of bytes that soketi\'s REST API sent back.', labelNames: ['app_id', 'port'], registers: [this.register], }), httpCallsReceived: new prom.Counter({ name: `${prefix}http_calls_received_total`, help: 'Total amount of received REST API calls.', labelNames: ['app_id', 'port'], registers: [this.register], }), horizontalAdapterResolveTime: new prom.Histogram({ name: `${prefix}horizontal_adapter_resolve_time`, help: 'The average resolve time for requests to other nodes.', labelNames: ['app_id', 'port'], registers: [this.register], }), horizontalAdapterResolvedPromises: new prom.Counter({ name: `${prefix}horizontal_adapter_resolved_promises`, help: 'The total amount of promises that were fulfilled by other nodes.', labelNames: ['app_id', 'port'], registers: [this.register], }), horizontalAdapterUncompletePromises: new prom.Counter({ name: `${prefix}horizontal_adapter_uncomplete_promises`, help: 'The total amount of promises that were not fulfilled entirely by other nodes.', labelNames: ['app_id', 'port'], registers: [this.register], }), horizontalAdapterSentRequests: new prom.Counter({ name: `${prefix}horizontal_adapter_sent_requests`, help: 'The total amount of sent requests to other nodes.', labelNames: ['app_id', 'port'], registers: [this.register], }), horizontalAdapterReceivedRequests: new prom.Counter({ name: `${prefix}horizontal_adapter_received_requests`, help: 'The total amount of received requests from other nodes.', labelNames: ['app_id', 'port'], registers: [this.register], }), horizontalAdapterReceivedResponses: new prom.Counter({ name: `${prefix}horizontal_adapter_received_responses`, help: 'The total amount of received responses from other nodes.', labelNames: ['app_id', 'port'], registers: [this.register], }), }; } } ================================================ FILE: src/namespace.ts ================================================ import { PresenceMember, PresenceMemberInfo } from './channels/presence-channel-manager'; import { WebSocket } from 'uWebSockets.js'; export class Namespace { /** * The list of channel connections for the current app. */ public channels: Map> = new Map(); /** * The list of sockets connected to the namespace. */ public sockets: Map = new Map(); /** * The list of user IDs and their associated socket ids. */ public users: Map> = new Map(); /** * Initialize the namespace for an app. */ constructor(protected appId: string) { // } /** * Get all sockets from this namespace. */ getSockets(): Promise> { return Promise.resolve(this.sockets); } /** * Add a new socket to the namespace. */ addSocket(ws: WebSocket): Promise { return new Promise(resolve => { this.sockets.set(ws.id, ws); resolve(true); }); } /** * Remove a socket from the namespace. */ async removeSocket(wsId: string): Promise { this.removeFromChannel(wsId, [...this.channels.keys()]); return this.sockets.delete(wsId); } /** * Add a socket ID to the channel identifier. * Return the total number of connections after the connection. */ addToChannel(ws: WebSocket, channel: string): Promise { return new Promise(resolve => { if (!this.channels.has(channel)) { this.channels.set(channel, new Set); } this.channels.get(channel).add(ws.id); resolve(this.channels.get(channel).size); }); } /** * Remove a socket ID from the channel identifier. * Return the total number of connections remaining to the channel. */ async removeFromChannel(wsId: string, channel: string|string[]): Promise { let remove = (channel) => { if (this.channels.has(channel)) { this.channels.get(channel).delete(wsId); if (this.channels.get(channel).size === 0) { this.channels.delete(channel); } } }; return new Promise(resolve => { if (Array.isArray(channel)) { channel.forEach(ch => remove(ch)); return resolve(); } remove(channel); resolve(this.channels.has(channel) ? this.channels.get(channel).size : 0); }); } /** * Check if a socket ID is joined to the channel. */ isInChannel(wsId: string, channel: string): Promise { return new Promise(resolve => { if (!this.channels.has(channel)) { return resolve(false); } resolve(this.channels.get(channel).has(wsId)); }); } /** * Get the list of channels with the websocket IDs. */ getChannels(): Promise>> { return Promise.resolve(this.channels); } /** * Get the list of channels with the websocket IDs. */ getChannelsWithSocketsCount(): Promise> { return this.getChannels().then((channels) => { let list = new Map(); for (let [channel, connections] of [...channels]) { list.set(channel, connections.size); } return list; }); } /** * Get all the channel sockets associated with this namespace. */ getChannelSockets(channel: string): Promise> { return new Promise(resolve => { if (!this.channels.has(channel)) { return resolve(new Map()); } let wsIds = this.channels.get(channel); resolve( Array.from(wsIds).reduce((sockets, wsId) => { if (!this.sockets.has(wsId)) { return sockets; } return sockets.set(wsId, this.sockets.get(wsId)); }, new Map()) ); }); } /** * Get a given presence channel's members. */ getChannelMembers(channel: string): Promise> { return this.getChannelSockets(channel).then(sockets => { return Array.from(sockets).reduce((members, [wsId, ws]) => { let member: PresenceMember = ws.presence ? ws.presence.get(channel) : null; if (member) { members.set(member.user_id as string, member.user_info); } return members; }, new Map()); }); } /** * Terminate the user's connections. */ terminateUserConnections(userId: number|string): void { this.getSockets().then(sockets => { [...sockets].forEach(([wsId, ws]) => { if (ws.user && ws.user.id == userId) { ws.sendJson({ event: 'pusher:error', data: { code: 4009, message: 'You got disconnected by the app.', }, }); try { ws.end(4009); } catch (e) { // } } }); }); } /** * Add to the users list the associated socket connection ID. */ addUser(ws: WebSocket): Promise { if (!ws.user) { return Promise.resolve(); } if (!this.users.has(ws.user.id)) { this.users.set(ws.user.id, new Set()); } if (!this.users.get(ws.user.id).has(ws.id)) { this.users.get(ws.user.id).add(ws.id); } return Promise.resolve(); } /** * Remove the user associated with the connection ID. */ removeUser(ws: WebSocket): Promise { if (!ws.user) { return Promise.resolve(); } if (this.users.has(ws.user.id)) { this.users.get(ws.user.id).delete(ws.id); } if (this.users.get(ws.user.id) && this.users.get(ws.user.id).size === 0) { this.users.delete(ws.user.id); } return Promise.resolve(); } /** * Get the sockets associated with an user. */ getUserSockets(userId: string|number): Promise> { let wsIds = this.users.get(userId); if (!wsIds || wsIds.size === 0) { return Promise.resolve(new Set()); } return Promise.resolve( [...wsIds].reduce((sockets, wsId) => { sockets.add(this.sockets.get(wsId)); return sockets; }, new Set()) ); } } ================================================ FILE: src/node.ts ================================================ export interface Node { isMaster: boolean; address: string; port: number; lastSeen: number; id: string; } ================================================ FILE: src/options.ts ================================================ import { AppInterface } from './app'; import { ClusterOptions, RedisOptions } from 'ioredis'; import { ConsumerOptions } from 'sqs-consumer'; import { SQS } from 'aws-sdk'; interface Redis { host: string; port: number; db: number; username: string|null; password: string|null; keyPrefix: string; sentinels: RedisSentinel[]; sentinelPassword: string|null; name: string; clusterNodes: ClusterNode[]; } interface RedisSentinel { host: string; port: number; } interface ClusterNode { host: string; port: number; } interface KnexConnection { host: string; port: number; user: string; password: string; database: string; } export interface Options { adapter: { driver: string; redis: { requestsTimeout: number; prefix: string; redisPubOptions: any; redisSubOptions: any; clusterMode: boolean; }; cluster: { requestsTimeout: 5_000, }, nats: { requestsTimeout: number; prefix: string; servers: string[]; user?: string; pass?: string|null; token: string|null; timeout: number; nodesNumber: number|null; }; }; appManager: { driver: string; array: { apps: AppInterface[]; }; cache: { enabled: boolean; ttl: number; }; dynamodb: { table: string; region: string; endpoint?: string; }; mysql: { table: string; version: string|number; useMysql2: boolean; }; postgres: { table: string; version: string|number; }; }; cache: { driver: string; redis: { redisOptions: RedisOptions|ClusterOptions; clusterMode: boolean; }; }; channelLimits: { maxNameLength: number; cacheTtl: number; }; cluster: { hostname: string; helloInterval: number; checkInterval: number; nodeTimeout: number, masterTimeout: number; port: number; prefix: string; ignoreProcess: boolean; broadcast: string; unicast: string|null; multicast: string|null; }; cors: { credentials: boolean; origin: string[]; methods: string[]; allowedHeaders: string[]; }; database: { mysql: KnexConnection; postgres: KnexConnection; redis: Redis; }; databasePooling: { enabled: boolean; min: number; max: number; }; debug: boolean; eventLimits: { maxChannelsAtOnce: string|number; maxNameLength: string|number; maxPayloadInKb: string|number; maxBatchSize: string|number; }; host: string; httpApi: { requestLimitInMb: string|number; acceptTraffic: { memoryThreshold: number; }; }; instance: { process_id: string|number; }; metrics: { enabled: boolean; driver: string; host: string; prometheus: { prefix: string; }; port: number; }; mode: string; port: number; pathPrefix: string; presence: { maxMembersPerChannel: string|number; maxMemberSizeInKb: string|number; }; queue: { driver: string; redis: { concurrency: number; redisOptions: RedisOptions|ClusterOptions; clusterMode: boolean; }; sqs: { region?: string; endpoint?: string; clientOptions?: SQS.Types.ClientConfiguration; consumerOptions?: ConsumerOptions; queueUrl: string; processBatch: boolean; batchSize: number; pollingWaitTimeMs: number; }; }; rateLimiter: { driver: string; redis: { redisOptions: RedisOptions|ClusterOptions; clusterMode: boolean; }; }; shutdownGracePeriod: number; ssl: { certPath: string; keyPath: string; passphrase: string; caPath: string; }; userAuthenticationTimeout: number; webhooks: { batching: { enabled: boolean; duration: number; }; }; } ================================================ FILE: src/queues/index.ts ================================================ export * from './queue-interface'; export * from './queue'; export * from './redis-queue-driver'; export * from './sqs-queue-driver'; export * from './sync-queue-driver'; ================================================ FILE: src/queues/queue-interface.ts ================================================ import { JobData } from '../webhook-sender'; export interface QueueInterface { /** * The Queue driver. */ driver?: QueueInterface; /** * Add a new event with data to queue. */ addToQueue(queueName: string, data?: JobData): Promise; /** * Register the code to run when handing the queue. */ processQueue(queueName: string, callback: CallableFunction): Promise; /** * Clear the queues for a graceful shutdown. */ disconnect(): Promise; } ================================================ FILE: src/queues/queue.ts ================================================ import { JobData } from '../webhook-sender'; import { Log } from '../log'; import { QueueInterface } from './queue-interface'; import { RedisQueueDriver } from './redis-queue-driver'; import { SqsQueueDriver } from './sqs-queue-driver'; import { SyncQueueDriver } from './sync-queue-driver'; import { Server } from '../server'; export class Queue implements QueueInterface { /** * The Queue driver. */ public driver: QueueInterface; /** * Initialize the queue. */ constructor(protected server: Server) { if (server.options.queue.driver === 'sync') { this.driver = new SyncQueueDriver(server); } else if (server.options.queue.driver === 'redis') { this.driver = new RedisQueueDriver(server); } else if (server.options.queue.driver === 'sqs') { this.driver = new SqsQueueDriver(server); } else { Log.error('No valid queue driver specified.'); } } /** * Add a new event with data to queue. */ addToQueue(queueName: string, data?: JobData): Promise { return this.driver.addToQueue(queueName, data); } /** * Register the code to run when handing the queue. */ processQueue(queueName: string, callback: CallableFunction): Promise { return this.driver.processQueue(queueName, callback); } /** * Clear the queues for a graceful shutdown. */ disconnect(): Promise { return this.driver.disconnect(); } } ================================================ FILE: src/queues/redis-queue-driver.ts ================================================ import async from 'async'; import { JobData } from '../webhook-sender'; import { Queue, Worker, QueueScheduler } from 'bullmq' import { QueueInterface } from './queue-interface'; import Redis, { Cluster, ClusterOptions, RedisOptions } from 'ioredis'; import { Server } from '../server'; interface QueueWithWorker { queue: Queue; worker: Worker; scheduler: QueueScheduler; } export class RedisQueueDriver implements QueueInterface { /** * The queues with workers list. */ protected queueWithWorker: Map = new Map(); /** * Initialize the Redis Queue Driver. */ constructor(protected server: Server) { // } /** * Add a new event with data to queue. */ addToQueue(queueName: string, data: JobData): Promise { return new Promise(resolve => { let queueWithWorker = this.queueWithWorker.get(queueName); if (!queueWithWorker) { return resolve(); } queueWithWorker.queue.add('webhook', data).then(() => resolve()); }); } /** * Register the code to run when handing the queue. */ processQueue(queueName: string, callback: CallableFunction): Promise { return new Promise(resolve => { if (!this.queueWithWorker.has(queueName)) { let redisOptions: RedisOptions|ClusterOptions = { maxRetriesPerRequest: null, enableReadyCheck: false, ...this.server.options.database.redis, ...this.server.options.queue.redis.redisOptions, // We set the key prefix on the queue, worker and scheduler instead of on the connection itself keyPrefix: undefined, }; const connection = this.server.options.queue.redis.clusterMode ? new Cluster(this.server.options.database.redis.clusterNodes, { scaleReads: 'slave', ...redisOptions }) : new Redis(redisOptions); const queueSharedOptions = { // We remove a trailing `:` from the prefix because BullMQ adds that already prefix: this.server.options.database.redis.keyPrefix.replace(/:$/, ''), connection, }; this.queueWithWorker.set(queueName, { queue: new Queue(queueName, { ...queueSharedOptions, defaultJobOptions: { attempts: 6, backoff: { type: 'exponential', delay: 1000, }, removeOnComplete: true, removeOnFail: true, }, }), // TODO: Sandbox the worker? https://docs.bullmq.io/guide/workers/sandboxed-processors worker: new Worker(queueName, callback as any, { ...queueSharedOptions, concurrency: this.server.options.queue.redis.concurrency, }), // TODO: Seperate this from the queue with worker when multipe workers are supported. // A single scheduler per queue is needed: https://docs.bullmq.io/guide/queuescheduler scheduler: new QueueScheduler(queueName, queueSharedOptions), }); } resolve(); }); } /** * Clear the queues for a graceful shutdown. */ disconnect(): Promise { return async.each([...this.queueWithWorker], ([queueName, { queue, worker, scheduler }]: [string, QueueWithWorker], callback) => { scheduler.close().then(() => { worker.close().then(() => callback()); }); }); } } ================================================ FILE: src/queues/sqs-queue-driver.ts ================================================ import async from 'async'; import { Consumer } from 'sqs-consumer'; import { createHash } from 'crypto'; import { Job } from '../job'; import { JobData } from '../webhook-sender'; import { Log } from '../log'; import { QueueInterface } from './queue-interface'; import { Server } from '../server'; import { SQS } from 'aws-sdk'; import { v4 as uuidv4 } from 'uuid'; export class SqsQueueDriver implements QueueInterface { /** * The list of consumers with their instance. */ protected queueWithConsumer: Map = new Map(); /** * Initialize the Prometheus exporter. */ constructor(protected server: Server) { // } /** * Add a new event with data to queue. */ addToQueue(queueName: string, data: JobData): Promise { return new Promise(resolve => { let message = JSON.stringify(data); let params = { MessageBody: message, MessageDeduplicationId: createHash('sha256').update(message).digest('hex'), MessageGroupId: `${data.appId}_${queueName}`, QueueUrl: this.server.options.queue.sqs.queueUrl, }; this.sqsClient().sendMessage(params, (err, data) => { if (err) { Log.errorTitle('❎ SQS client could not publish to the queue.'); Log.error({ data, err, params, queueName }); } if (this.server.options.debug && !err) { Log.successTitle('✅ SQS client publsihed message to the queue.'); Log.success({ data, err, params, queueName }); } resolve(); }); }); } /** * Register the code to run when handing the queue. */ processQueue(queueName: string, callback: CallableFunction): Promise { return new Promise(resolve => { let handleMessage = ({ Body }: { Body: string; }) => { return new Promise(resolve => { callback( new Job(uuidv4(), JSON.parse(Body)), () => { if (this.server.options.debug) { Log.successTitle('✅ SQS message processed.'); Log.success({ Body, queueName }); } resolve(); }, ); }); }; let consumerOptions = { queueUrl: this.server.options.queue.sqs.queueUrl, sqs: this.sqsClient(), batchSize: this.server.options.queue.sqs.batchSize, pollingWaitTimeMs: this.server.options.queue.sqs.pollingWaitTimeMs, ...this.server.options.queue.sqs.consumerOptions, }; if (this.server.options.queue.sqs.processBatch) { consumerOptions.handleMessageBatch = (messages) => { return Promise.all(messages.map(({ Body }) => handleMessage({ Body }))).then(() => { // }); }; } else { consumerOptions.handleMessage = handleMessage; } let consumer = Consumer.create(consumerOptions); consumer.start(); this.queueWithConsumer.set(queueName, consumer); resolve(); }); } /** * Clear the queues for a graceful shutdown. */ disconnect(): Promise { return async.each([...this.queueWithConsumer], ([queueName, consumer]: [string, Consumer], callback) => { if (consumer.isRunning) { consumer.stop(); callback(); } }); } /** * Get the SQS client. */ protected sqsClient(): SQS { let sqsOptions = this.server.options.queue.sqs; return new SQS({ apiVersion: '2012-11-05', region: sqsOptions.region || 'us-east-1', endpoint: sqsOptions.endpoint, ...sqsOptions.clientOptions, }); } } ================================================ FILE: src/queues/sync-queue-driver.ts ================================================ import { Job } from '../job'; import { JobData } from '../webhook-sender'; import { QueueInterface } from './queue-interface'; import { Server } from '../server'; import { v4 as uuidv4 } from 'uuid'; export class SyncQueueDriver implements QueueInterface { /** * The list of queues with their code. */ protected queues: Map = new Map(); /** * Initialize the Sync Queue Driver. */ constructor(protected server: Server) { // } /** * Add a new event with data to queue. */ addToQueue(queueName: string, data: JobData): Promise { return new Promise(resolve => { let jobCallback = this.queues.get(queueName); if (!jobCallback) { return resolve(); } let jobId = uuidv4(); jobCallback(new Job(jobId, data), resolve); }); } /** * Register the code to run when handing the queue. */ processQueue(queueName: string, callback: CallableFunction): Promise { return new Promise(resolve => { this.queues.set(queueName, callback); resolve(); }); } /** * Clear the queues for a graceful shutdown. */ disconnect(): Promise { return Promise.resolve(); } } ================================================ FILE: src/rate-limiters/cluster-rate-limiter.ts ================================================ import { App } from './../app'; import { ConsumptionResponse } from './rate-limiter-interface'; import { LocalRateLimiter } from './local-rate-limiter'; import { RateLimiterAbstract, RateLimiterClusterMasterPM2 } from 'rate-limiter-flexible'; import { Server } from '../server'; const cluster = require('cluster'); const pm2 = require('pm2'); export interface ConsumptionMessage { app: App; eventKey: string; points: number; maxPoints: number; } export class ClusterRateLimiter extends LocalRateLimiter { /** * Initialize the local rate limiter driver. */ constructor(protected server: Server) { super(server); if (cluster.isPrimary || typeof cluster.isPrimary === 'undefined') { if (server.pm2) { // With PM2, discovery is not needed. new RateLimiterClusterMasterPM2(pm2); } else { // When a new master is demoted, the rate limiters it has become the pivot points of the real, synced // rate limiter instances. Just trust this value. server.discover.join('rate_limiter:limiters', (rateLimiters: { [key: string]: RateLimiterAbstract }) => { this.rateLimiters = Object.fromEntries( Object.entries(rateLimiters).map(([key, rateLimiterObject]: [string, any]) => { return [ key, this.createNewRateLimiter(key.split(':')[0], rateLimiterObject._points), ]; }) ); }); // All nodes need to know when other nodes consumed from the rate limiter. server.discover.join('rate_limiter:consume', ({ app, eventKey, points, maxPoints }: ConsumptionMessage) => { super.consume(app, eventKey, points, maxPoints); }); server.discover.on('added', () => { if (server.nodes.get('self').isMaster) { // When a new node is added, just send the rate limiters this master instance has. // This value is the true value of the rate limiters. this.sendRateLimiters(); } }); } } } /** * Consume points for a given key, then * return a response object with headers and the success indicator. */ protected consume(app: App, eventKey: string, points: number, maxPoints: number): Promise { return super.consume(app, eventKey, points, maxPoints).then((response) => { if (response.canContinue) { this.server.discover.send('rate_limiter:consume', { app, eventKey, points, maxPoints, }); } return response; }); } /** * Clear the rate limiter or active connections. */ disconnect(): Promise { return super.disconnect().then(() => { // If the current instance is the master and the server is closing, // demote and send the rate limiter of the current instance to the new master. if (this.server.nodes.get('self').isMaster) { this.server.discover.demote(); this.server.discover.send('rate_limiter:limiters', this.rateLimiters); } }); } /** * Send the stored rate limiters this instance currently have. */ protected sendRateLimiters(): void { this.server.discover.send('rate_limiter:limiters', this.rateLimiters); } } ================================================ FILE: src/rate-limiters/index.ts ================================================ export * from './cluster-rate-limiter'; export * from './local-rate-limiter'; export * from './rate-limiter-interface'; export * from './rate-limiter'; export * from './redis-rate-limiter'; ================================================ FILE: src/rate-limiters/local-rate-limiter.ts ================================================ import { App } from './../app'; import { ConsumptionResponse, RateLimiterInterface } from './rate-limiter-interface'; import { RateLimiterAbstract, RateLimiterMemory, RateLimiterRes } from 'rate-limiter-flexible'; import { Server } from '../server'; import { WebSocket } from 'uWebSockets.js'; export class LocalRateLimiter implements RateLimiterInterface { /** * The list of rate limiters bound to each apps that interacts. */ protected rateLimiters: { [appId: string]: RateLimiterAbstract } = { // }; /** * Initialize the local rate limiter driver. */ constructor(protected server: Server) { // } /** * Consume the points for backend-received events. */ consumeBackendEventPoints(points: number, app?: App, ws?: WebSocket): Promise { return this.consume( app, `${app.id}:backend:events`, points, app.maxBackendEventsPerSecond as number, ); } /** * Consume the points for frontend-received events. */ consumeFrontendEventPoints(points: number, app?: App, ws?: WebSocket): Promise { return this.consume( app, `${app.id}:frontend:events:${ws.id}`, points, app.maxClientEventsPerSecond as number, ); } /** * Consume the points for HTTP read requests. */ consumeReadRequestsPoints(points: number, app?: App, ws?: WebSocket): Promise { return this.consume( app, `${app.id}:backend:request_read`, points, app.maxReadRequestsPerSecond as number, ); } /** * Create a new rate limiter instance. */ createNewRateLimiter(appId: string, maxPoints: number): RateLimiterAbstract { return new RateLimiterMemory({ points: maxPoints, duration: 1, keyPrefix: `app:${appId}`, }); } /** * Clear the rate limiter or active connections. */ disconnect(): Promise { return Promise.resolve(); } /** * Initialize a new rate limiter for the given app and event key. */ protected initializeRateLimiter(appId: string, eventKey: string, maxPoints: number): Promise { if (this.rateLimiters[`${appId}:${eventKey}`]) { return new Promise(resolve => { this.rateLimiters[`${appId}:${eventKey}`].points = maxPoints; resolve(this.rateLimiters[`${appId}:${eventKey}`]); }); } this.rateLimiters[`${appId}:${eventKey}`] = this.createNewRateLimiter(appId, maxPoints); return Promise.resolve(this.rateLimiters[`${appId}:${eventKey}`]); } /** * Consume points for a given key, then * return a response object with headers and the success indicator. */ protected consume(app: App, eventKey: string, points: number, maxPoints: number): Promise { if (maxPoints < 0) { return Promise.resolve({ canContinue: true, rateLimiterRes: null, headers: { // }, }); } let calculateHeaders = (rateLimiterRes: RateLimiterRes) => ({ 'Retry-After': rateLimiterRes.msBeforeNext / 1000, 'X-RateLimit-Limit': maxPoints, 'X-RateLimit-Remaining': rateLimiterRes.remainingPoints, }); return this.initializeRateLimiter(app.id, eventKey, maxPoints).then(rateLimiter => { return rateLimiter.consume(eventKey, points).then((rateLimiterRes: RateLimiterRes) => { return { canContinue: true, rateLimiterRes, headers: calculateHeaders(rateLimiterRes), }; }).catch((rateLimiterRes: RateLimiterRes) => { return { canContinue: false, rateLimiterRes, headers: calculateHeaders(rateLimiterRes), }; }); }); } } ================================================ FILE: src/rate-limiters/rate-limiter-interface.ts ================================================ import { App } from './../app'; import { RateLimiterAbstract, RateLimiterRes } from 'rate-limiter-flexible'; import { WebSocket } from 'uWebSockets.js'; export interface ConsumptionResponse { canContinue: boolean; rateLimiterRes: RateLimiterRes|null; headers: { 'Retry-After'?: number; 'X-RateLimit-Limit'?: number; 'X-RateLimit-Remaining'?: number; }; } export interface RateLimiterInterface { /** * Rate Limiter driver. */ driver?: RateLimiterInterface; /** * Consume the points for backend-received events. */ consumeBackendEventPoints(points: number, app?: App, ws?: WebSocket): Promise; /** * Consume the points for frontend-received events. */ consumeFrontendEventPoints(points: number, app?: App, ws?: WebSocket): Promise; /** * Consume the points for HTTP read requests. */ consumeReadRequestsPoints(points: number, app?: App, ws?: WebSocket): Promise; /** * Create a new rate limiter instance. */ createNewRateLimiter(appId: string, maxPoints: number): RateLimiterAbstract; /** * Clear the rate limiter or active connections. */ disconnect(): Promise; } ================================================ FILE: src/rate-limiters/rate-limiter.ts ================================================ import { App } from './../app'; import { ClusterRateLimiter } from './cluster-rate-limiter'; import { ConsumptionResponse, RateLimiterInterface } from './rate-limiter-interface'; import { LocalRateLimiter } from './local-rate-limiter'; import { Log } from './../log'; import { RateLimiterAbstract } from 'rate-limiter-flexible'; import { RedisRateLimiter } from './redis-rate-limiter'; import { Server } from '../server'; import { WebSocket } from 'uWebSockets.js'; export class RateLimiter implements RateLimiterInterface { /** * Rate Limiter driver. */ public driver: RateLimiterInterface; /** * Initialize the rate limiter driver. */ constructor(server: Server) { if (server.options.rateLimiter.driver === 'local') { this.driver = new LocalRateLimiter(server); } else if (server.options.rateLimiter.driver === 'redis') { this.driver = new RedisRateLimiter(server); } else if (server.options.rateLimiter.driver === 'cluster') { this.driver = new ClusterRateLimiter(server); } else { Log.error('No stats driver specified.'); } } /** * Consume the points for backend-received events. */ consumeBackendEventPoints(points: number, app?: App, ws?: WebSocket): Promise { return this.driver.consumeBackendEventPoints(points, app, ws); } /** * Consume the points for frontend-received events. */ consumeFrontendEventPoints(points: number, app?: App, ws?: WebSocket): Promise { return this.driver.consumeFrontendEventPoints(points, app, ws); } /** * Consume the points for HTTP read requests. */ consumeReadRequestsPoints(points: number, app?: App, ws?: WebSocket): Promise { return this.driver.consumeReadRequestsPoints(points, app, ws); } /** * Create a new rate limiter instance. */ createNewRateLimiter(appId: string, maxPoints: number): RateLimiterAbstract { return this.driver.createNewRateLimiter(appId, maxPoints); } /** * Clear the rate limiter or active connections. */ disconnect(): Promise { return this.driver.disconnect(); } } ================================================ FILE: src/rate-limiters/redis-rate-limiter.ts ================================================ import { LocalRateLimiter } from './local-rate-limiter'; import { RateLimiterAbstract, RateLimiterRedis } from 'rate-limiter-flexible'; import Redis, { Cluster, ClusterOptions, RedisOptions } from 'ioredis'; import { Server } from '../server'; export class RedisRateLimiter extends LocalRateLimiter { /** * The Redis connection. */ protected redisConnection: Redis|Cluster; /** * Initialize the Redis rate limiter driver. */ constructor(protected server: Server) { super(server); let redisOptions: ClusterOptions|RedisOptions = { ...server.options.database.redis, ...server.options.rateLimiter.redis.redisOptions, }; this.redisConnection = server.options.rateLimiter.redis.clusterMode ? new Cluster(server.options.database.redis.clusterNodes, { scaleReads: 'slave', ...redisOptions, }) : new Redis(redisOptions); } /** * Initialize a new rate limiter for the given app and event key. */ protected initializeRateLimiter(appId: string, eventKey: string, maxPoints: number): Promise { return Promise.resolve(new RateLimiterRedis({ points: maxPoints, duration: 1, storeClient: this.redisConnection, keyPrefix: `app:${appId}`, // TODO: Insurance limiter? // insuranceLimiter: super.createNewRateLimiter(appId, maxPoints), })); } /** * Clear the rate limiter or active connections. */ disconnect(): Promise { return this.redisConnection.quit().then(() => { // }); } } ================================================ FILE: src/server.ts ================================================ import * as dot from 'dot-wild'; import { Adapter, AdapterInterface } from './adapters'; import { AppManager, AppManagerInterface } from './app-managers'; import { CacheManager } from './cache-managers/cache-manager'; import { CacheManagerInterface } from './cache-managers/cache-manager-interface'; import { HttpHandler } from './http-handler'; import { HttpRequest, HttpResponse, TemplatedApp } from 'uWebSockets.js'; import { Log } from './log'; import { Metrics, MetricsInterface } from './metrics'; import { Node } from './node'; import { Options } from './options'; import { Queue } from './queues/queue'; import { QueueInterface } from './queues/queue-interface'; import { RateLimiter } from './rate-limiters/rate-limiter'; import { RateLimiterInterface } from './rate-limiters/rate-limiter-interface'; import { uWebSocketMessage } from './message'; import { v4 as uuidv4 } from 'uuid'; import { WebhookSender } from './webhook-sender'; import { WebSocket } from 'uWebSockets.js'; import { WsHandler } from './ws-handler'; const Discover = require('node-discover'); const queryString = require('query-string'); const uWS = require('uWebSockets.js'); export class Server { /** * The list of options for the server. */ public options: Options = { adapter: { driver: 'local', redis: { requestsTimeout: 5_000, prefix: '', redisPubOptions: { // }, redisSubOptions: { // }, clusterMode: false, }, cluster: { requestsTimeout: 5_000, }, nats: { requestsTimeout: 5_000, prefix: '', servers: ['127.0.0.1:4222'], user: null, pass: null, token: null, timeout: 10_000, nodesNumber: null, }, }, appManager: { driver: 'array', cache: { enabled: false, ttl: -1, }, array: { apps: [ { id: 'app-id', key: 'app-key', secret: 'app-secret', maxConnections: -1, enableClientMessages: false, enabled: true, maxBackendEventsPerSecond: -1, maxClientEventsPerSecond: -1, maxReadRequestsPerSecond: -1, webhooks: [], }, ], }, dynamodb: { table: 'apps', region: 'us-east-1', endpoint: null, }, mysql: { table: 'apps', version: '8.0', useMysql2: false, }, postgres: { table: 'apps', version: '13.3', }, }, cache: { driver: 'memory', redis: { redisOptions: { // }, clusterMode: false, }, }, channelLimits: { maxNameLength: 200, cacheTtl: 3600, }, cluster: { hostname: '0.0.0.0', helloInterval: 500, checkInterval: 500, nodeTimeout: 2000, masterTimeout: 2000, port: 11002, prefix: '', ignoreProcess: true, broadcast: '255.255.255.255', unicast: null, multicast: null, }, cors: { credentials: true, origin: ['*'], methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], allowedHeaders: [ 'Origin', 'Content-Type', 'X-Auth-Token', 'X-Requested-With', 'Accept', 'Authorization', 'X-CSRF-TOKEN', 'XSRF-TOKEN', 'X-Socket-Id', ], }, database: { mysql: { host: '127.0.0.1', port: 3306, user: 'root', password: 'password', database: 'main', }, postgres: { host: '127.0.0.1', port: 5432, user: 'postgres', password: 'password', database: 'main', }, redis: { host: '127.0.0.1', port: 6379, db: 0, username: null, password: null, keyPrefix: '', sentinels: null, sentinelPassword: null, name: 'mymaster', clusterNodes: [], }, }, databasePooling: { enabled: false, min: 0, max: 7, }, debug: false, eventLimits: { maxChannelsAtOnce: 100, maxNameLength: 200, maxPayloadInKb: 100, maxBatchSize: 10, }, host: '0.0.0.0', httpApi: { requestLimitInMb: 100, acceptTraffic: { memoryThreshold: 85, }, }, instance: { process_id: process.pid || uuidv4(), }, metrics: { enabled: false, driver: 'prometheus', host: '0.0.0.0', prometheus: { prefix: 'soketi_', }, port: 9601, }, mode: 'full', port: 6001, pathPrefix: '', presence: { maxMembersPerChannel: 100, maxMemberSizeInKb: 2, }, queue: { driver: 'sync', redis: { concurrency: 1, redisOptions: { // }, clusterMode: false, }, sqs: { region: 'us-east-1', endpoint: null, clientOptions: {}, consumerOptions: {}, queueUrl: '', processBatch: false, batchSize: 1, pollingWaitTimeMs: 0, }, }, rateLimiter: { driver: 'local', redis: { redisOptions: { // }, clusterMode: false, }, }, shutdownGracePeriod: 3_000, ssl: { certPath: '', keyPath: '', passphrase: '', caPath: '', }, userAuthenticationTimeout: 30_000, webhooks: { batching: { enabled: false, duration: 50, }, }, }; /** * Wether the server is closing or not. */ public closing = false; /** * The server process. */ private serverProcess; /** * The metrics server process. */ private metricsServerProcess; /** * The WS handler for the incoming connections. */ public wsHandler: WsHandler; /** * The HTTP handler for the REST API. */ public httpHandler: HttpHandler; /** * The app manager used for retrieving apps. */ public appManager: AppManagerInterface; /** * The metrics handler. */ public metricsManager: MetricsInterface; /** * The adapter used to interact with the socket storage. */ public adapter: AdapterInterface; /** * The rate limiter handler for the server. */ public rateLimiter: RateLimiterInterface; /** * The queue manager. */ public queueManager: QueueInterface; /** * The cache manager. */ public cacheManager: CacheManagerInterface; /** * The sender for webhooks. */ public webhookSender: WebhookSender; /** * Wether the server is running under PM2. */ public pm2 = false; /** * The list of nodes in the current private network. */ public nodes: Map = new Map(); /** * The Discover instance. */ public discover: typeof Discover; /** * Initialize the server. */ constructor(options = {}) { this.setOptions(options); } /** * Start the server statically. */ static async start(options: any = {}, callback?: CallableFunction) { return (new Server(options)).start(callback); } /** * Start the server. */ async start(callback?: CallableFunction) { Log.br(); this.configureDiscovery().then(() => { this.initializeDrivers().then(() => { if (this.options.debug) { console.dir(this.options, { depth: 100 }); } this.wsHandler = new WsHandler(this); this.httpHandler = new HttpHandler(this); if (this.options.debug) { Log.info('📡 soketi initialization....'); Log.info('⚡ Initializing the HTTP API & Websockets Server...'); } let server: TemplatedApp = this.shouldConfigureSsl() ? uWS.SSLApp({ key_file_name: this.options.ssl.keyPath, cert_file_name: this.options.ssl.certPath, passphrase: this.options.ssl.passphrase, ca_file_name: this.options.ssl.caPath, }) : uWS.App(); let metricsServer: TemplatedApp = uWS.App(); if (this.options.debug) { Log.info('⚡ Initializing the Websocket listeners and channels...'); } this.configureWebsockets(server).then(server => { if (this.options.debug) { Log.info('⚡ Initializing the HTTP webserver...'); } this.configureHttp(server).then(server => { this.configureMetricsServer(metricsServer).then(metricsServer => { metricsServer.listen(this.options.metrics.host, this.options.metrics.port, metricsServerProcess => { this.metricsServerProcess = metricsServerProcess; server.listen(this.options.host, this.options.port, serverProcess => { this.serverProcess = serverProcess; Log.successTitle('🎉 Server is up and running!'); Log.successTitle(`📡 The Websockets server is available at 127.0.0.1:${this.options.port}`); Log.successTitle(`🔗 The HTTP API server is available at http://127.0.0.1:${this.options.port}`); Log.successTitle(`🎊 The /usage endpoint is available on port ${this.options.metrics.port}.`); if (this.options.metrics.enabled) { Log.successTitle(`🌠 Prometheus /metrics endpoint is available on port ${this.options.metrics.port}.`); } Log.br(); if (callback) { callback(this); } }); }); }); }); }); }); }); } /** * Stop the server. */ stop(): Promise { this.closing = true; Log.br(); Log.warning('🚫 New users cannot connect to this instance anymore. Preparing for signaling...'); Log.warning('⚡ The server is closing and signaling the existing connections to terminate.'); Log.br(); return this.wsHandler.closeAllLocalSockets().then(() => { return new Promise(resolve => { if (this.options.debug) { Log.warningTitle('⚡ All sockets were closed. Now closing the server.'); } setTimeout(() => { Promise.all([ this.metricsManager.clear(), this.queueManager.disconnect(), this.rateLimiter.disconnect(), this.cacheManager.disconnect(), ]).then(() => { this.adapter.disconnect().then(() => { if (this.serverProcess) { uWS.us_listen_socket_close(this.serverProcess); } if (this.metricsServerProcess) { uWS.us_listen_socket_close(this.metricsServerProcess); } }).then(() => resolve()); }); }, this.options.shutdownGracePeriod); }); }); } /** * Set the options for the server. The key should be string. * For nested values, use the dot notation. */ setOptions(options: { [key: string]: any; }): void { for (let optionKey in options) { // Make sure none of the id's are int. if (optionKey.match("^appManager.array.apps.\\d+.id")) { if (Number.isInteger(options[optionKey])) { options[optionKey] = options[optionKey].toString(); } } this.options = dot.set(this.options, optionKey, options[optionKey]); } } /** * Initialize the drivers for the server. */ initializeDrivers(): Promise { return Promise.all([ this.setAppManager(new AppManager(this)), this.setAdapter(new Adapter(this)), this.setMetricsManager(new Metrics(this)), this.setRateLimiter(new RateLimiter(this)), this.setQueueManager(new Queue(this)), this.setCacheManager(new CacheManager(this)), this.setWebhookSender(), ]); } /** * Set the app manager. */ setAppManager(instance: AppManagerInterface): void { this.appManager = instance; } /** * Set the adapter. */ setAdapter(instance: AdapterInterface): Promise { return new Promise(resolve => { instance.init().then(() => { this.adapter = instance; resolve(); }); }); } /** * Set the metrics manager. */ setMetricsManager(instance: MetricsInterface): Promise { return new Promise(resolve => { this.metricsManager = instance; resolve(); }); } /** * Set the rate limiter. */ setRateLimiter(instance: RateLimiterInterface): Promise { return new Promise(resolve => { this.rateLimiter = instance; resolve(); }); } /** * Set the queue manager. */ setQueueManager(instance: QueueInterface): Promise { return new Promise(resolve => { this.queueManager = instance; resolve(); }); } /** * Set the cache manager. */ setCacheManager(instance: CacheManagerInterface): Promise { return new Promise(resolve => { this.cacheManager = instance; resolve(); }); } /** * Set the webhook sender. */ setWebhookSender(): Promise { return new Promise(resolve => { this.webhookSender = new WebhookSender(this); resolve(); }); } /** * Generates the URL with the set pathPrefix from options. */ protected url(path: string): string { return this.options.pathPrefix + path; } /** * Get the cluster prefix name for discover. */ clusterPrefix(channel: string): string { if (this.options.cluster.prefix) { channel = this.options.cluster.prefix + '#' + channel; } return channel; } /** * Configure the private network discovery for this node. */ protected configureDiscovery(): Promise { return new Promise(resolve => { this.discover = Discover(this.options.cluster, () => { this.nodes.set('self', this.discover.me); this.discover.on('promotion', () => { this.nodes.set('self', this.discover.me); if (this.options.debug) { Log.discoverTitle('Promoted from node to master.'); Log.discover(this.discover.me); } }); this.discover.on('demotion', () => { this.nodes.set('self', this.discover.me); if (this.options.debug) { Log.discoverTitle('Demoted from master to node.'); Log.discover(this.discover.me); } }); this.discover.on('added', (node: Node) => { this.nodes.set('self', this.discover.me); this.nodes.set(node.id, node); if (this.options.debug) { Log.discoverTitle('New node added.'); Log.discover(node); } }); this.discover.on('removed', (node: Node) => { this.nodes.set('self', this.discover.me); this.nodes.delete(node.id); if (this.options.debug) { Log.discoverTitle('Node removed.'); Log.discover(node); } }); this.discover.on('master', (node: Node) => { this.nodes.set('self', this.discover.me); this.nodes.set(node.id, node); if (this.options.debug) { Log.discoverTitle('New master.'); Log.discover(node); } }); resolve(); }); }); } /** * Configure the WebSocket logic. */ protected configureWebsockets(server: TemplatedApp): Promise { return new Promise(resolve => { if (this.canProcessRequests()) { server = server.ws(this.url('/app/:id'), { idleTimeout: 120, // According to protocol maxBackpressure: 1024 * 1024, maxPayloadLength: 100 * 1024 * 1024, // 100 MB message: (ws: WebSocket, message: uWebSocketMessage, isBinary: boolean) => this.wsHandler.onMessage(ws, message, isBinary), open: (ws: WebSocket) => this.wsHandler.onOpen(ws), close: (ws: WebSocket, code: number, message: uWebSocketMessage) => this.wsHandler.onClose(ws, code, message), upgrade: (res: HttpResponse, req: HttpRequest, context) => this.wsHandler.handleUpgrade(res, req, context), }); } resolve(server); }); } /** * Configure the HTTP REST API server. */ protected configureHttp(server: TemplatedApp): Promise { return new Promise(resolve => { server.get(this.url('/'), (res, req) => this.httpHandler.healthCheck(res)); server.get(this.url('/ready'), (res, req) => this.httpHandler.ready(res)); if (this.canProcessRequests()) { server.get(this.url('/accept-traffic'), (res, req) => this.httpHandler.acceptTraffic(res)); server.get(this.url('/apps/:appId/channels'), (res, req) => { res.params = { appId: req.getParameter(0) }; res.query = queryString.parse(req.getQuery()); res.method = req.getMethod().toUpperCase(); res.url = req.getUrl(); return this.httpHandler.channels(res); }); server.get(this.url('/apps/:appId/channels/:channelName'), (res, req) => { res.params = { appId: req.getParameter(0), channel: req.getParameter(1) }; res.query = queryString.parse(req.getQuery()); res.method = req.getMethod().toUpperCase(); res.url = req.getUrl(); return this.httpHandler.channel(res); }); server.get(this.url('/apps/:appId/channels/:channelName/users'), (res, req) => { res.params = { appId: req.getParameter(0), channel: req.getParameter(1) }; res.query = queryString.parse(req.getQuery()); res.method = req.getMethod().toUpperCase(); res.url = req.getUrl(); return this.httpHandler.channelUsers(res); }); server.post(this.url('/apps/:appId/events'), (res, req) => { res.params = { appId: req.getParameter(0) }; res.query = queryString.parse(req.getQuery()); res.method = req.getMethod().toUpperCase(); res.url = req.getUrl(); return this.httpHandler.events(res); }); server.post(this.url('/apps/:appId/batch_events'), (res, req) => { res.params = { appId: req.getParameter(0) }; res.query = queryString.parse(req.getQuery()); res.method = req.getMethod().toUpperCase(); res.url = req.getUrl(); return this.httpHandler.batchEvents(res); }); server.post(this.url('/apps/:appId/users/:userId/terminate_connections'), (res, req) => { res.params = { appId: req.getParameter(0), userId: req.getParameter(1) }; res.query = queryString.parse(req.getQuery()); res.method = req.getMethod().toUpperCase(); res.url = req.getUrl(); return this.httpHandler.terminateUserConnections(res); }); } server.any(this.url('/*'), (res, req) => { return this.httpHandler.notFound(res); }); resolve(server); }); } /** * Configure the metrics server at a separate port for under-the-firewall access. */ protected configureMetricsServer(metricsServer: TemplatedApp): Promise { return new Promise(resolve => { Log.info('🕵️‍♂️ Initiating metrics endpoints...'); Log.br(); metricsServer.get(this.url('/'), (res, req) => this.httpHandler.healthCheck(res)); metricsServer.get(this.url('/ready'), (res, req) => this.httpHandler.ready(res)); metricsServer.get(this.url('/usage'), (res, req) => this.httpHandler.usage(res)); if (this.options.metrics.enabled) { metricsServer.get(this.url('/metrics'), (res, req) => { res.query = queryString.parse(req.getQuery()); return this.httpHandler.metrics(res); }); } resolve(metricsServer); }); } /** * Wether the server should start in SSL mode. */ protected shouldConfigureSsl(): boolean { return this.options.ssl.certPath !== '' || this.options.ssl.keyPath !== ''; } /** * Check if the server instance can process queues. */ public canProcessQueues(): boolean { return ['worker', 'full'].includes(this.options.mode); } /** * Check if the server instance can process requests * for the Pusher protocol API (both REST and WebSockets). */ public canProcessRequests(): boolean { return ['server', 'full'].includes(this.options.mode); } } ================================================ FILE: src/utils.ts ================================================ export class Utils { /** * Allowed client events patterns. * * @type {string[]} */ protected static _clientEventPatterns: string[] = [ 'client-*', ]; /** * Channels and patters for private channels. * * @type {string[]} */ protected static _privateChannelPatterns: string[] = [ 'private-*', 'private-encrypted-*', 'presence-*', ]; /** * Channels with patters for caching channels. * * @type {string[]} */ protected static _cachingChannelPatterns: string[] = [ 'cache-*', 'private-cache-*', 'private-encrypted-cache-*', 'presence-cache-*', ]; /** * Get the amount of bytes from given parameters. */ static dataToBytes(...data: any): number { return data.reduce((totalBytes, element) => { element = typeof element === 'string' ? element : JSON.stringify(element); try { return totalBytes += Buffer.byteLength(element, 'utf8'); } catch (e) { return totalBytes; } }, 0); } /** * Get the amount of kilobytes from given parameters. */ static dataToKilobytes(...data: any): number { return this.dataToBytes(...data) / 1024; } /** * Get the amount of megabytes from given parameters. */ static dataToMegabytes(...data: any): number { return this.dataToKilobytes(...data) / 1024; } /** * Check if the given channel name is private. */ static isPrivateChannel(channel: string): boolean { let isPrivate = false; this._privateChannelPatterns.forEach(pattern => { let regex = new RegExp(pattern.replace('*', '.*')); if (regex.test(channel)) { isPrivate = true; } }); return isPrivate; } /** * Check if the given channel name is a presence channel. */ static isPresenceChannel(channel: string): boolean { return channel.lastIndexOf('presence-', 0) === 0; } /** * Check if the given channel name is a encrypted private channel. */ static isEncryptedPrivateChannel(channel: string): boolean { return channel.lastIndexOf('private-encrypted-', 0) === 0; } /** * Check if the given channel accepts caching. */ static isCachingChannel(channel: string): boolean { let isCachingChannel = false; this._cachingChannelPatterns.forEach(pattern => { let regex = new RegExp(pattern.replace('*', '.*')); if (regex.test(channel)) { isCachingChannel = true; } }); return isCachingChannel; } /** * Check if client is a client event. */ static isClientEvent(event: string): boolean { let isClientEvent = false; this._clientEventPatterns.forEach(pattern => { let regex = new RegExp(pattern.replace('*', '.*')); if (regex.test(event)) { isClientEvent = true; } }); return isClientEvent; } /** * Check if the channel name is restricted for connections from the client. * Read: https://pusher.com/docs/channels/using_channels/channels/#channel-naming-conventions */ static restrictedChannelName(name: string) { return /^#?[-a-zA-Z0-9_=@,.;]+$/.test(name) === false; } } ================================================ FILE: src/webhook-sender.ts ================================================ import { App, WebhookInterface } from './app'; import async from 'async'; import axios from 'axios'; import { createHmac } from 'crypto'; import { Utils } from './utils'; import { Lambda } from 'aws-sdk'; import { Log } from './log'; import { Server } from './server'; export interface ClientEventData { name: string; channel: string; event?: string, data?: { [key: string]: any; }; socket_id?: string; user_id?: string; time_ms?: number; } export interface JobData { appKey: string; appId: string; payload: { time_ms: number; events: ClientEventData[]; }, originalPusherSignature: string; } /** * Create the HMAC for the given data. */ export function createWebhookHmac(data: string, secret: string): string { return createHmac('sha256', secret) .update(data) .digest('hex'); } export class WebhookSender { /** * Batch of ClientEventData, to be sent as one webhook. */ public batch: ClientEventData[] = []; /** * Whether current process has nominated batch handler. */ public batchHasLeader = false; /** * Initialize the Webhook sender. */ constructor(protected server: Server) { let queueProcessor = (job, done) => { let rawData: JobData = job.data; const { appKey, payload, originalPusherSignature } = rawData; server.appManager.findByKey(appKey).then(app => { // Ensure the payload hasn't been tampered with between the job being dispatched // and here, as we may need to recalculate the signature post filtration. if (originalPusherSignature !== createWebhookHmac(JSON.stringify(payload), app.secret)) { return; } async.each(app.webhooks, (webhook: WebhookInterface, resolveWebhook) => { const originalEventsLength = payload.events.length; let filteredPayloadEvents = payload.events; filteredPayloadEvents = filteredPayloadEvents.filter(event => { if (!webhook.event_types.includes(event.name)) { return false; } if (webhook.filter) { if (webhook.filter.channel_name_starts_with && !event.channel.startsWith(webhook.filter.channel_name_starts_with)) { return false; } if (webhook.filter.channel_name_ends_with && !event.channel.endsWith(webhook.filter.channel_name_ends_with)) { return false; } } return true; }); // If there's no webhooks to send after filtration, we should resolve early. if (filteredPayloadEvents.length === 0) { return resolveWebhook(); } // If any events have been filtered out, regenerate the signature let pusherSignature = (originalEventsLength !== filteredPayloadEvents.length) ? createWebhookHmac(JSON.stringify(payload), app.secret) : originalPusherSignature; if (this.server.options.debug) { Log.webhookSenderTitle('🚀 Processing webhook from queue.'); Log.webhookSender({ appKey, payload, pusherSignature }); } const headers = { 'Accept': 'application/json', 'Content-Type': 'application/json', 'User-Agent': `SoketiWebhooksAxiosClient/1.0 (Process: ${this.server.options.instance.process_id})`, // We specifically merge in the custom headers here so the headers below cannot be overwritten ...webhook.headers ?? {}, 'X-Pusher-Key': appKey, 'X-Pusher-Signature': pusherSignature, }; // Send HTTP POST to the target URL if (webhook.url) { axios.post(webhook.url, payload, { headers }).then((res) => { if (this.server.options.debug) { Log.webhookSenderTitle('✅ Webhook sent.'); Log.webhookSender({ webhook, payload }); } }).catch(err => { // TODO: Maybe retry exponentially? if (this.server.options.debug) { Log.webhookSenderTitle('❎ Webhook could not be sent.'); Log.webhookSender({ err, webhook, payload }); } }).then(() => resolveWebhook()); } else if (webhook.lambda_function) { // Invoke a Lambda function const params = { FunctionName: webhook.lambda_function, InvocationType: webhook.lambda.async ? 'Event' : 'RequestResponse', Payload: Buffer.from(JSON.stringify({ payload, headers })), }; let lambda = new Lambda({ apiVersion: '2015-03-31', region: webhook.lambda.region || 'us-east-1', ...(webhook.lambda.client_options || {}), }); lambda.invoke(params, (err, data) => { if (err) { if (this.server.options.debug) { Log.webhookSenderTitle('❎ Lambda trigger failed.'); Log.webhookSender({ webhook, err, data }); } } else { if (this.server.options.debug) { Log.webhookSenderTitle('✅ Lambda triggered.'); Log.webhookSender({ webhook, payload }); } } resolveWebhook(); }); } }).then(() => { if (typeof done === 'function') { done(); } }); }); }; // TODO: Maybe have one queue per app to reserve queue thresholds? if (server.canProcessQueues()) { server.queueManager.processQueue('client_event_webhooks', queueProcessor); server.queueManager.processQueue('member_added_webhooks', queueProcessor); server.queueManager.processQueue('member_removed_webhooks', queueProcessor); server.queueManager.processQueue('channel_vacated_webhooks', queueProcessor); server.queueManager.processQueue('channel_occupied_webhooks', queueProcessor); server.queueManager.processQueue('cache_miss_webhooks', queueProcessor); } } /** * Send a webhook for the client event. */ public sendClientEvent(app: App, channel: string, event: string, data: any, socketId?: string, userId?: string) { if (!app.hasClientEventWebhooks) { return; } let formattedData: ClientEventData = { name: App.CLIENT_EVENT_WEBHOOK, channel, event, data, }; if (socketId) { formattedData.socket_id = socketId; } if (userId && Utils.isPresenceChannel(channel)) { formattedData.user_id = userId; } this.send(app, formattedData, 'client_event_webhooks'); } /** * Send a member_added event. */ public sendMemberAdded(app: App, channel: string, userId: string): void { if (!app.hasMemberAddedWebhooks) { return; } this.send(app, { name: App.MEMBER_ADDED_WEBHOOK, channel, user_id: userId, }, 'member_added_webhooks'); } /** * Send a member_removed event. */ public sendMemberRemoved(app: App, channel: string, userId: string): void { if (!app.hasMemberRemovedWebhooks) { return; } this.send(app, { name: App.MEMBER_REMOVED_WEBHOOK, channel, user_id: userId, }, 'member_removed_webhooks'); } /** * Send a channel_vacated event. */ public sendChannelVacated(app: App, channel: string): void { if (!app.hasChannelVacatedWebhooks) { return; } this.send(app, { name: App.CHANNEL_VACATED_WEBHOOK, channel, }, 'channel_vacated_webhooks'); } /** * Send a channel_occupied event. */ public sendChannelOccupied(app: App, channel: string): void { if (!app.hasChannelOccupiedWebhooks) { return; } this.send(app, { name: App.CHANNEL_OCCUPIED_WEBHOOK, channel, }, 'channel_occupied_webhooks'); } /** * Send a cache_missed event. */ public sendCacheMissed(app: App, channel: string): void { if (!app.hasCacheMissedWebhooks) { return; } this.send(app, { name: App.CACHE_MISSED_WEBHOOK, channel, }, 'cache_miss_webhooks'); } /** * Send a webhook for the app with the given data. */ protected send(app: App, data: ClientEventData, queueName: string): void { if (this.server.options.webhooks.batching.enabled) { this.sendWebhookByBatching(app, data, queueName); } else { this.sendWebhook(app, data, queueName) } } /** * Send a webhook for the app with the given data, without batching. */ protected sendWebhook(app: App, data: ClientEventData|ClientEventData[], queueName: string): void { let events = data instanceof Array ? data : [data]; if (events.length === 0) { return; } // According to the Pusher docs: The time_ms key provides the unix timestamp in milliseconds when the webhook was created. // So we set the time here instead of creating a new one in the queue handler so you can detect delayed webhooks when the queue is busy. let time = (new Date).getTime(); let payload = { time_ms: time, events, }; let originalPusherSignature = createWebhookHmac(JSON.stringify(payload), app.secret); this.server.queueManager.addToQueue(queueName, { appKey: app.key, appId: app.id, payload, originalPusherSignature, }); } /** * Send a webhook for the app with the given data, with batching enabled. */ protected sendWebhookByBatching(app: App, data: ClientEventData, queueName: string): void { this.batch.push(data); // If there's no batch leader, elect itself as the batch leader, then wait an arbitrary time using // setTimeout to build up a batch, before firing off the full batch of events in one webhook. if (!this.batchHasLeader) { this.batchHasLeader = true; setTimeout(() => { if (this.batch.length > 0) { this.sendWebhook(app, this.batch.splice(0, this.batch.length), queueName); } this.batchHasLeader = false; }, this.server.options.webhooks.batching.duration); } } } ================================================ FILE: src/ws-handler.ts ================================================ import { App } from './app'; import async from 'async'; import { EncryptedPrivateChannelManager } from './channels'; import { HttpRequest, HttpResponse } from 'uWebSockets.js'; import { Log } from './log'; import { Namespace } from './namespace'; import { PresenceChannelManager } from './channels'; import { PresenceMemberInfo } from './channels/presence-channel-manager'; import { PrivateChannelManager } from './channels'; import { PublicChannelManager } from './channels'; import { PusherMessage, uWebSocketMessage } from './message'; import { Server } from './server'; import { Utils } from './utils'; import { WebSocket } from 'uWebSockets.js'; const ab2str = require('arraybuffer-to-string'); const Pusher = require('pusher'); export class WsHandler { /** * The manager for the public channels. */ protected publicChannelManager: PublicChannelManager; /** * The manager for the private channels. */ protected privateChannelManager: PrivateChannelManager; /** * The manager for the encrypted private channels. */ protected encryptedPrivateChannelManager: EncryptedPrivateChannelManager; /** * The manager for the presence channels. */ protected presenceChannelManager: PresenceChannelManager; /** * Initialize the Websocket connections handler. */ constructor(protected server: Server) { this.publicChannelManager = new PublicChannelManager(server); this.privateChannelManager = new PrivateChannelManager(server); this.encryptedPrivateChannelManager = new EncryptedPrivateChannelManager(server); this.presenceChannelManager = new PresenceChannelManager(server); } /** * Handle a new open connection. */ onOpen(ws: WebSocket): any { if (this.server.options.debug) { Log.websocketTitle('👨‍🔬 New connection:'); Log.websocket({ ws }); } ws.sendJson = (data) => { try { ws.send(JSON.stringify(data)); this.updateTimeout(ws); if (ws.app) { this.server.metricsManager.markWsMessageSent(ws.app.id, data); } if (this.server.options.debug) { Log.websocketTitle('✈ Sent message to client:'); Log.websocket({ ws, data }); } } catch (e) { // } } ws.id = this.generateSocketId(); ws.subscribedChannels = new Set(); ws.presence = new Map(); if (this.server.closing) { ws.sendJson({ event: 'pusher:error', data: { code: 4200, message: 'Server is closing. Please reconnect shortly.', }, }); return ws.end(4200); } this.checkForValidApp(ws).then(validApp => { if (!validApp) { ws.sendJson({ event: 'pusher:error', data: { code: 4001, message: `App key ${ws.appKey} does not exist.`, }, }); return ws.end(4001); } ws.app = validApp.forWebSocket(); this.checkIfAppIsEnabled(ws).then(enabled => { if (!enabled) { ws.sendJson({ event: 'pusher:error', data: { code: 4003, message: 'The app is not enabled.', }, }); return ws.end(4003); } this.checkAppConnectionLimit(ws).then(canConnect => { if (!canConnect) { ws.sendJson({ event: 'pusher:error', data: { code: 4100, message: 'The current concurrent connections quota has been reached.', }, }); ws.end(4100); } else { // Make sure to update the socket after new data was pushed in. this.server.adapter.addSocket(ws.app.id, ws); let broadcastMessage = { event: 'pusher:connection_established', data: JSON.stringify({ socket_id: ws.id, activity_timeout: 30, }), }; ws.sendJson(broadcastMessage); if (ws.app.enableUserAuthentication) { this.setUserAuthenticationTimeout(ws); } this.server.metricsManager.markNewConnection(ws); } }); }); }); } /** * Handle a received message from the client. */ onMessage(ws: WebSocket, message: uWebSocketMessage, isBinary: boolean): any { if (message instanceof ArrayBuffer) { try { message = JSON.parse(ab2str(message)) as PusherMessage; } catch (err) { return; } } if (this.server.options.debug) { Log.websocketTitle('⚡ New message received:'); Log.websocket({ message, isBinary }); } if (message) { if (message.event === 'pusher:ping') { this.handlePong(ws); } else if (message.event === 'pusher:subscribe') { this.subscribeToChannel(ws, message); } else if (message.event === 'pusher:unsubscribe') { this.unsubscribeFromChannel(ws, message.data.channel); } else if (Utils.isClientEvent(message.event)) { this.handleClientEvent(ws, message); } else if (message.event === 'pusher:signin') { this.handleSignin(ws, message); } else { Log.warning({ info: 'Message event handler not implemented.', message, }); } } if (ws.app) { this.server.metricsManager.markWsMessageReceived(ws.app.id, message); } } /** * Handle the event of the client closing the connection. */ onClose(ws: WebSocket, code: number, message: uWebSocketMessage): any { if (this.server.options.debug) { Log.websocketTitle('❌ Connection closed:'); Log.websocket({ ws, code, message }); } // If code 4200 (reconnect immediately) is called, it means the `closeAllLocalSockets()` was called. if (code !== 4200) { this.evictSocketFromMemory(ws); } } /** * Evict the local socket. */ evictSocketFromMemory(ws: WebSocket): Promise { return this.unsubscribeFromAllChannels(ws, true).then(() => { if (ws.app) { this.server.adapter.removeSocket(ws.app.id, ws.id); this.server.metricsManager.markDisconnection(ws); } this.clearTimeout(ws); }); } /** * Handle the event to close all existing sockets. */ async closeAllLocalSockets(): Promise { let namespaces = this.server.adapter.getNamespaces(); if (namespaces.size === 0) { return Promise.resolve(); } return async.each([...namespaces], ([namespaceId, namespace]: [string, Namespace], nsCallback) => { namespace.getSockets().then(sockets => { async.each([...sockets], ([wsId, ws]: [string, WebSocket], wsCallback) => { try { ws.sendJson({ event: 'pusher:error', data: { code: 4200, message: 'Server closed. Please reconnect shortly.', }, }); ws.end(4200); } catch (e) { // } this.evictSocketFromMemory(ws).then(() => { wsCallback(); }); }).then(() => { this.server.adapter.clearNamespace(namespaceId).then(() => { nsCallback(); }); }); }); }).then(() => { // One last clear to make sure everything went away. return this.server.adapter.clearNamespaces(); }); } /** * Mutate the upgrade request. */ handleUpgrade(res: HttpResponse, req: HttpRequest, context): any { res.upgrade( { ip: ab2str(res.getRemoteAddressAsText()), ip2: ab2str(res.getProxiedRemoteAddressAsText()), appKey: req.getParameter(0), }, req.getHeader('sec-websocket-key'), req.getHeader('sec-websocket-protocol'), req.getHeader('sec-websocket-extensions'), context, ); } /** * Send back the pong response. */ handlePong(ws: WebSocket): any { ws.sendJson({ event: 'pusher:pong', data: {}, }); if (this.server.closing) { ws.sendJson({ event: 'pusher:error', data: { code: 4200, message: 'Server closed. Please reconnect shortly.', }, }); ws.end(4200); this.evictSocketFromMemory(ws); } } /** * Instruct the server to subscribe the connection to the channel. */ subscribeToChannel(ws: WebSocket, message: PusherMessage): any { if (this.server.closing) { ws.sendJson({ event: 'pusher:error', data: { code: 4200, message: 'Server closed. Please reconnect shortly.', }, }); ws.end(4200); this.evictSocketFromMemory(ws); return; } let channel = message.data.channel; let channelManager = this.getChannelManagerFor(channel); if (channel.length > ws.app.maxChannelNameLength) { let broadcastMessage = { event: 'pusher:subscription_error', channel, data: { type: 'LimitReached', error: `The channel name is longer than the allowed ${ws.app.maxChannelNameLength} characters.`, status: 4009, }, }; ws.sendJson(broadcastMessage); return; } channelManager.join(ws, channel, message).then((response) => { if (!response.success) { let { authError, type, errorMessage, errorCode } = response; // For auth errors, send pusher:subscription_error if (authError) { return ws.sendJson({ event: 'pusher:subscription_error', channel, data: { type: 'AuthError', error: errorMessage, status: 401, }, }); } // Otherwise, catch any non-auth related errors. return ws.sendJson({ event: 'pusher:subscription_error', channel, data: { type: type, error: errorMessage, status: errorCode, }, }); } if (!ws.subscribedChannels.has(channel)) { ws.subscribedChannels.add(channel); } // Make sure to update the socket after new data was pushed in. this.server.adapter.addSocket(ws.app.id, ws); // If the connection freshly joined, send the webhook: if (response.channelConnections === 1) { this.server.webhookSender.sendChannelOccupied(ws.app, channel); } // For non-presence channels, end with subscription succeeded. if (!(channelManager instanceof PresenceChannelManager)) { let broadcastMessage = { event: 'pusher_internal:subscription_succeeded', channel, }; ws.sendJson(broadcastMessage); if (Utils.isCachingChannel(channel)) { this.sendMissedCacheIfExists(ws, channel); } return; } // Otherwise, prepare a response for the presence channel. this.server.adapter.getChannelMembers(ws.app.id, channel, false).then(members => { let { user_id, user_info } = response.member; ws.presence.set(channel, response.member); // Make sure to update the socket after new data was pushed in. this.server.adapter.addSocket(ws.app.id, ws); // If the member already exists in the channel, don't resend the member_added event. if (!members.has(user_id as string)) { this.server.webhookSender.sendMemberAdded(ws.app, channel, user_id as string); this.server.adapter.send(ws.app.id, channel, JSON.stringify({ event: 'pusher_internal:member_added', channel, data: JSON.stringify({ user_id: user_id, user_info: user_info, }), }), ws.id); members.set(user_id as string, user_info); } let broadcastMessage = { event: 'pusher_internal:subscription_succeeded', channel, data: JSON.stringify({ presence: { ids: Array.from(members.keys()), hash: Object.fromEntries(members), count: members.size, }, }), }; ws.sendJson(broadcastMessage); if (Utils.isCachingChannel(channel)) { this.sendMissedCacheIfExists(ws, channel); } }).catch(err => { Log.error(err); ws.sendJson({ event: 'pusher:error', channel, data: { type: 'ServerError', error: 'A server error has occured.', code: 4302, }, }); }); }); } /** * Instruct the server to unsubscribe the connection from the channel. */ unsubscribeFromChannel(ws: WebSocket, channel: string, closing = false): Promise { let channelManager = this.getChannelManagerFor(channel); return channelManager.leave(ws, channel).then(response => { let member = ws.presence.get(channel); if (response.left) { // Send presence channel-speific events and delete specific data. // This can happen only if the user is connected to the presence channel. if (channelManager instanceof PresenceChannelManager && ws.presence.has(channel)) { ws.presence.delete(channel); // Make sure to update the socket after new data was pushed in. this.server.adapter.addSocket(ws.app.id, ws); this.server.adapter.getChannelMembers(ws.app.id, channel, false).then(members => { if (!members.has(member.user_id as string)) { this.server.webhookSender.sendMemberRemoved(ws.app, channel, member.user_id); this.server.adapter.send(ws.app.id, channel, JSON.stringify({ event: 'pusher_internal:member_removed', channel, data: JSON.stringify({ user_id: member.user_id, }), }), ws.id); } }); } ws.subscribedChannels.delete(channel); // Make sure to update the socket after new data was pushed in, // but only if the user is not closing the connection. if (!closing) { this.server.adapter.addSocket(ws.app.id, ws); } if (response.remainingConnections === 0) { this.server.webhookSender.sendChannelVacated(ws.app, channel); } } // ws.send(JSON.stringify({ // event: 'pusher_internal:unsubscribed', // channel, // })); return; }); } /** * Unsubscribe the connection from all channels. */ unsubscribeFromAllChannels(ws: WebSocket, closing = true): Promise { if (!ws.subscribedChannels) { return Promise.resolve(); } return Promise.all([ async.each(ws.subscribedChannels, (channel, callback) => { this.unsubscribeFromChannel(ws, channel, closing).then(() => callback()); }), ws.app && ws.user ? this.server.adapter.removeUser(ws) : new Promise(resolve => resolve()), ]).then(() => { return; }) } /** * Handle the events coming from the client. */ handleClientEvent(ws: WebSocket, message: PusherMessage): any { let { event, data, channel } = message; if (!ws.app.enableClientMessages) { return ws.sendJson({ event: 'pusher:error', channel, data: { code: 4301, message: `The app does not have client messaging enabled.`, }, }); } // Make sure the event name length is not too big. if (event.length > ws.app.maxEventNameLength) { let broadcastMessage = { event: 'pusher:error', channel, data: { code: 4301, message: `Event name is too long. Maximum allowed size is ${ws.app.maxEventNameLength}.`, }, }; ws.sendJson(broadcastMessage); return; } let payloadSizeInKb = Utils.dataToKilobytes(message.data); // Make sure the total payload of the message body is not too big. if (payloadSizeInKb > parseFloat(ws.app.maxEventPayloadInKb as string)) { let broadcastMessage = { event: 'pusher:error', channel, data: { code: 4301, message: `The event data should be less than ${ws.app.maxEventPayloadInKb} KB.`, }, }; ws.sendJson(broadcastMessage); return; } this.server.adapter.isInChannel(ws.app.id, channel, ws.id).then(canBroadcast => { if (!canBroadcast) { return; } this.server.rateLimiter.consumeFrontendEventPoints(1, ws.app, ws).then(response => { if (response.canContinue) { let userId = ws.presence.has(channel) ? ws.presence.get(channel).user_id : null; let message = JSON.stringify({ event, channel, data, ...userId ? { user_id: userId } : {}, }); this.server.adapter.send(ws.app.id, channel, message, ws.id); this.server.webhookSender.sendClientEvent( ws.app, channel, event, data, ws.id, userId, ); return; } ws.sendJson({ event: 'pusher:error', channel, data: { code: 4301, message: 'The rate limit for sending client events exceeded the quota.', }, }); }); }); } /** * Handle the signin coming from the frontend. */ handleSignin(ws: WebSocket, message: PusherMessage): void { if (!ws.userAuthenticationTimeout) { return; } this.signinTokenIsValid(ws, message.data.user_data, message.data.auth).then(isValid => { if (!isValid) { ws.sendJson({ event: 'pusher:error', data: { code: 4009, message: 'Connection not authorized.', }, }); try { ws.end(4009); } catch (e) { // } return; } let decodedUser = JSON.parse(message.data.user_data); if (!decodedUser.id) { ws.sendJson({ event: 'pusher:error', data: { code: 4009, message: 'The returned user data must contain the "id" field.', }, }); try { ws.end(4009); } catch (e) { // } return; } ws.user = { ...decodedUser, ...{ id: decodedUser.id.toString(), }, }; if (ws.userAuthenticationTimeout) { clearTimeout(ws.userAuthenticationTimeout); } this.server.adapter.addSocket(ws.app.id, ws); this.server.adapter.addUser(ws).then(() => { ws.sendJson({ event: 'pusher:signin_success', data: message.data, }); }); }); } /** * Send the first event as cache_missed, if it exists, to catch up. */ sendMissedCacheIfExists(ws: WebSocket, channel: string) { this.server.cacheManager.get(`app:${ws.app.id}:channel:${channel}:cache_miss`).then(cachedEvent => { if (cachedEvent) { let { event, data } = JSON.parse(cachedEvent); ws.sendJson({ event: event, channel, data: data }); } else { ws.sendJson({ event: 'pusher:cache_miss', channel }); this.server.webhookSender.sendCacheMissed(ws.app, channel); } }); } /** * Get the channel manager for the given channel name, * respecting the Pusher protocol. */ getChannelManagerFor(channel: string): PublicChannelManager|PrivateChannelManager|EncryptedPrivateChannelManager|PresenceChannelManager { if (Utils.isPresenceChannel(channel)) { return this.presenceChannelManager; } else if (Utils.isEncryptedPrivateChannel(channel)) { return this.encryptedPrivateChannelManager; } else if (Utils.isPrivateChannel(channel)) { return this.privateChannelManager; } else { return this.publicChannelManager; } } /** * Use the app manager to retrieve a valid app. */ protected checkForValidApp(ws: WebSocket): Promise { return this.server.appManager.findByKey(ws.appKey); } /** * Make sure that the app is enabled. */ protected checkIfAppIsEnabled(ws: WebSocket): Promise { return Promise.resolve(ws.app.enabled); } /** * Make sure the connection limit is not reached with this connection. * Return a boolean wether the user can connect or not. */ protected checkAppConnectionLimit(ws: WebSocket): Promise { return this.server.adapter.getSocketsCount(ws.app.id).then(wsCount => { let maxConnections = parseInt(ws.app.maxConnections as string) || -1; if (maxConnections < 0) { return true; } return wsCount + 1 <= maxConnections; }).catch(err => { Log.error(err); return false; }); } /** * Check is an incoming connection can subscribe. */ signinTokenIsValid(ws: WebSocket, userData: string, signatureToCheck: string): Promise { return this.signinTokenForUserData(ws, userData).then(expectedSignature => { return signatureToCheck === expectedSignature; }); } /** * Get the signin token from the given message, by the Socket. */ protected signinTokenForUserData(ws: WebSocket, userData: string): Promise { return new Promise(resolve => { let decodedString = `${ws.id}::user::${userData}`; let token = new Pusher.Token(ws.app.key, ws.app.secret); resolve( ws.app.key + ':' + token.sign(decodedString) ); }); } /** * Generate a Pusher-like Socket ID. */ protected generateSocketId(): string { let min = 0; let max = 10000000000; let randomNumber = (min, max) => Math.floor(Math.random() * (max - min + 1) + min); return randomNumber(min, max) + '.' + randomNumber(min, max); } /** * Clear WebSocket timeout. */ protected clearTimeout(ws: WebSocket): void { if (ws.timeout) { clearTimeout(ws.timeout); } } /** * Update WebSocket timeout. */ protected updateTimeout(ws: WebSocket): void { this.clearTimeout(ws); ws.timeout = setTimeout(() => { try { ws.end(4201); } catch (e) { // } }, 120_000); } /** * Set the authentication timeout for the socket. */ protected setUserAuthenticationTimeout(ws: WebSocket): void { ws.userAuthenticationTimeout = setTimeout(() => { ws.sendJson({ event: 'pusher:error', data: { code: 4009, message: 'Connection not authorized within timeout.', }, }); try { ws.end(4009); } catch (e) { // } }, this.server.options.userAuthenticationTimeout); } } ================================================ FILE: tests/encrypted-private.test.ts ================================================ import { Server } from './../src/server'; import { Utils } from './utils'; jest.retryTimes(parseInt(process.env.RETRY_TIMES || '1')); describe('private-encrypted channel test', () => { beforeEach(() => { jest.resetModules(); return Utils.waitForPortsToFreeUp(); }); afterEach(() => { return Utils.flushServers(); }); test('connects to private-encrypted channel', done => { Utils.newServer({}, (server: Server) => { let client = Utils.newClientForEncryptedPrivateChannel(); let backend = Utils.newBackend(); let channelName = `private-encrypted-${Utils.randomChannelName()}`; client.connection.bind('connected', () => { let channel = client.subscribe(channelName); channel.bind('greeting', e => { expect(e.message).toBe('hello'); client.disconnect(); done(); }); channel.bind('pusher:subscription_succeeded', () => { backend.trigger(channelName, 'greeting', { message: 'hello' }) .catch(error => { throw new Error(error); }); }); }); }); }); test('cannot connect to private-encrypted channel with wrong authentication', done => { Utils.newServer({}, (server: Server) => { let client = Utils.newClientForEncryptedPrivateChannel({ authorizer: (channel, options) => ({ authorize: (socketId, callback) => { callback(false, { auth: 'incorrect_token', channel_data: null, shared_secret: Utils.newBackend().channelSharedSecret(channel.name).toString('base64'), }); }, }), }); let channelName = `private-encrypted-${Utils.randomChannelName()}`; client.connection.bind('message', ({ event, channel, data }) => { if (event === 'pusher:subscription_error' && channel === channelName) { expect(data.type).toBe('AuthError'); expect(data.status).toBe(401); client.disconnect(); done(); } }); client.connection.bind('connected', () => { client.subscribe(channelName); }); }); }); test('connects and disconnects to private-encrypted channel and does not leak memory', done => { Utils.newServer({}, (server: Server) => { let client = Utils.newClientForEncryptedPrivateChannel(); let backend = Utils.newBackend(); let channelName = `private-encrypted-${Utils.randomChannelName()}`; client.connection.bind('disconnected', () => { Utils.wait(3000).then(() => { let namespace = server.adapter.getNamespace('app-id'); expect(namespace.sockets.size).toBe(0); expect(namespace.channels.size).toBe(0); done(); }); }); client.connection.bind('connected', () => { let channel = client.subscribe(channelName); channel.bind('greeting', e => { expect(e.message).toBe('hello'); client.unsubscribe(channelName); Utils.wait(3000).then(() => { let namespace = server.adapter.getNamespace('app-id'); let socket = namespace.sockets.get(namespace.sockets.keys().next().value); expect(namespace.channels.size).toBe(0); expect(namespace.sockets.size).toBe(1); expect(socket.subscribedChannels.size).toBe(0); expect(socket.presence.size).toBe(0); client.disconnect(); }); }); channel.bind('pusher:subscription_succeeded', () => { backend.trigger(channelName, 'greeting', { message: 'hello' }); }); }); }); }); test('sudden close connection in private-encrypted channel and does not leak memory', done => { Utils.newServer({}, (server: Server) => { let client = Utils.newClientForEncryptedPrivateChannel(); let backend = Utils.newBackend(); let channelName = `private-encrypted-${Utils.randomChannelName()}`; client.connection.bind('disconnected', () => { Utils.wait(3000).then(() => { let namespace = server.adapter.getNamespace('app-id'); expect(namespace.sockets.size).toBe(0); expect(namespace.channels.size).toBe(0); done(); }); }); client.connection.bind('connected', () => { let channel = client.subscribe(channelName); channel.bind('greeting', e => { expect(e.message).toBe('hello'); client.disconnect(); }); channel.bind('pusher:subscription_succeeded', () => { backend.trigger(channelName, 'greeting', { message: 'hello' }); }); }); }); }); test('cached private-encrypted channels work', done => { Utils.newServer({}, (server: Server) => { let client1 = Utils.newClientForEncryptedPrivateChannel(); let backend = Utils.newBackend(); let channelName = `private-encrypted-cache-${Utils.randomChannelName()}`; client1.connection.bind('connected', () => { let channel = client1.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { channel.bind('pusher:cache_miss', (data) => { expect(data).toBe(undefined); channel.bind('greeting', e => { expect(e.message).toBe('hello'); let client2 = Utils.newClientForEncryptedPrivateChannel(); client2.connection.bind('connected', () => { let channel = client2.subscribe(channelName); channel.bind('pusher:cache_miss', () => { throw new Error('Did not expect cache_miss to be invoked.'); }); channel.bind('greeting', e => { expect(e.message).toBe('hello'); done() }) }); }); }); backend.trigger(channelName, 'greeting', { message: 'hello' }).catch(error => { throw new Error(error); }); }); }); }); }); }); ================================================ FILE: tests/fixtures/dynamodb_schema.js ================================================ const AWS = require('aws-sdk'); let ddb = new AWS.DynamoDB({ apiVersion: '2012-08-10', region: 'us-east-1', endpoint: `http://${process.env.DYNAMODB_URL || '127.0.0.1:8000'}`, }); let createRecord = () => { const params = { TableName: 'apps', Item: { AppId: { S: 'app-id' }, AppKey: { S: 'app-key' }, AppSecret: { S: 'app-secret' }, MaxConnections: { N: '-1' }, EnableClientMessages: { B: 'false' }, Enabled: { B: 'true' }, MaxBackendEventsPerSecond: { N: '-1' }, MaxClientEventsPerSecond: { N: '-1' }, MaxReadRequestsPerSecond: { N: '-1' }, Webhooks: { S: '[]', }, /** * The following fields are optional. It's not a problem, because DynamoDB is NoSQL. * If one of the following fields doesn't exist, * the default ones defined at the server-level will take priority. */ // MaxPresenceMembersPerChannel: { N: '-1' }, // MaxPresenceMemberSizeInKb: { N: '-1' }, // MaxChannelNameLength: { N: '-1' }, // MaxEventChannelsAtOnce: { N: '-1' }, // MaxEventNameLength: { N: '-1' }, // MaxEventPayloadInKb: { N: '-1' }, // MaxEventBatchSize: { N: '-1' }, // EnableUserAuthentication: { B: 'false' } }, }; return ddb.putItem(params).promise().then(() => { console.log('Record created.'); }).catch(err => { console.error(err); console.log('Record already existent.'); }); }; ddb.describeTable({ TableName: 'apps' }).promise().then((result) => { createRecord(); }).catch(err => { console.error(err); ddb.createTable({ TableName: 'apps', AttributeDefinitions: [ { AttributeName: 'AppId', AttributeType: 'S', }, { AttributeName: 'AppKey', AttributeType: 'S', }, ], KeySchema: [{ AttributeName: 'AppId', KeyType: 'HASH', }], GlobalSecondaryIndexes: [{ IndexName: 'AppKeyIndex', KeySchema: [{ AttributeName: 'AppKey', KeyType: 'HASH', }], Projection: { ProjectionType: 'ALL', }, ProvisionedThroughput: { ReadCapacityUnits: 100, WriteCapacityUnits: 100, }, }], StreamSpecification: { StreamEnabled: false, }, ProvisionedThroughput: { ReadCapacityUnits: 100, WriteCapacityUnits: 100, }, }).promise().then(() => { console.log('Table created.'); }).then(createRecord).catch((err) => { console.error(err); console.log('Table already existent.'); }); }); ================================================ FILE: tests/fixtures/mysql_schema.sql ================================================ CREATE TABLE IF NOT EXISTS `apps` ( `id` varchar(255) NOT NULL, `key` varchar(255) NOT NULL, `secret` varchar(255) NOT NULL, `max_connections` integer(10) NOT NULL, `enabled` tinyint(1) NOT NULL, `enable_client_messages` tinyint(1) NOT NULL, `max_backend_events_per_sec` integer(10) NOT NULL, `max_client_events_per_sec` integer(10) NOT NULL, `max_read_req_per_sec` integer(10) NOT NULL, `webhooks` json, `max_presence_members_per_channel` tinyint(1) NULL, `max_presence_member_size_in_kb` tinyint(1) NULL, `max_channel_name_length` tinyint(1) NULL, `max_event_channels_at_once` tinyint(1) NULL, `max_event_name_length` tinyint(1) NULL, `max_event_payload_in_kb` tinyint(1) NULL, `max_event_batch_size` tinyint(1) NULL, `enable_user_authentication` tinyint(1) NOT NULL, PRIMARY KEY (`id`) ); INSERT INTO apps ( id, `key`, secret, max_connections, `enabled`, enable_client_messages, max_backend_events_per_sec, max_client_events_per_sec, max_read_req_per_sec, webhooks, max_presence_members_per_channel, max_presence_member_size_in_kb, max_channel_name_length, max_event_channels_at_once, max_event_name_length, max_event_payload_in_kb, max_event_batch_size, enable_user_authentication ) VALUES ( 'app-id', 'app-key', 'app-secret', 200, 1, 1, -1, -1, -1, '[]', null, null, null, null, null, null, null, 0 ); ================================================ FILE: tests/fixtures/postgres_schema.sql ================================================ CREATE TABLE IF NOT EXISTS apps ( id varchar(255) PRIMARY KEY, "key" varchar(255) NOT NULL, secret varchar(255) NOT NULL, max_connections integer NOT NULL, enable_client_messages smallint NOT NULL, "enabled" smallint NOT NULL, max_backend_events_per_sec integer NOT NULL, max_client_events_per_sec integer NOT NULL, max_read_req_per_sec integer NOT NULL, webhooks json, max_presence_members_per_channel integer DEFAULT NULL, max_presence_member_size_in_kb integer DEFAULT NULL, max_channel_name_length integer DEFAULT NULL, max_event_channels_at_once integer DEFAULT NULL, max_event_name_length integer DEFAULT NULL, max_event_payload_in_kb integer DEFAULT NULL, max_event_batch_size integer DEFAULT NULL, enable_user_authentication smallint NOT NULL ); INSERT INTO apps ( id, "key", secret, max_connections, "enabled", enable_client_messages, max_backend_events_per_sec, max_client_events_per_sec, max_read_req_per_sec, webhooks, max_presence_members_per_channel, max_presence_member_size_in_kb, max_channel_name_length, max_event_channels_at_once, max_event_name_length, max_event_payload_in_kb, max_event_batch_size, enable_user_authentication ) VALUES ( 'app-id', 'app-key', 'app-secret', 200, 1, 1, -1, -1, -1, '[]', null, null, null, null, null, null, null, 0 ); ================================================ FILE: tests/fixtures/sqs.json ================================================ { "FifoQueue": "true", "ContentBasedDeduplication": "true", "DeduplicationScope": "messageGroup", "FifoThroughputLimit": "perMessageGroupId", "MessageRetentionPeriod": "3600", "ReceiveMessageWaitTimeSeconds": "1", "VisibilityTimeout": "5" } ================================================ FILE: tests/http-api.cluster-adapter.test.ts ================================================ import { Server } from './../src/server'; import { Utils } from './utils'; jest.retryTimes(parseInt(process.env.RETRY_TIMES || '1')); describe('http api test for cluster adapter', () => { beforeEach(() => { jest.resetModules(); return Utils.waitForPortsToFreeUp(); }); afterEach(() => { return Utils.flushServers(); }); Utils.shouldRun(Utils.adapterIs('cluster'))('get api channels with cluster adapter', done => { Utils.newServer({ port: 6001 }, (server1: Server) => { Utils.newClonedServer(server1, { port: 6002 }, (server2: Server) => { let client1 = Utils.newClient(); let backend = Utils.newBackend(); let channelName = Utils.randomChannelName(); client1.connection.bind('connected', () => { let channel = client1.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { backend.get({ path: '/channels' }).then(res => res.json()).then(body => { expect(body.channels[channelName]).toBeDefined(); expect(body.channels[channelName].subscription_count).toBe(1); expect(body.channels[channelName].occupied).toBe(true); let client2 = Utils.newClient({}, 6002); client2.connection.bind('connected', () => { let channel = client2.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { backend.get({ path: '/channels' }).then(res => res.json()).then(body => { expect(body.channels[channelName]).toBeDefined(); expect(body.channels[channelName].subscription_count).toBe(2); expect(body.channels[channelName].occupied).toBe(true); client1.connection.bind('disconnected', () => { client2.disconnect(); }); client2.connection.bind('disconnected', () => { backend.get({ path: '/channels' }).then(res => res.json()).then(body => { // TODO: Expect // expect(body.channels[channelName]).toBeUndefined(); done(); }); }); client1.disconnect(); }); }); }); }); }); }); }); }); }); Utils.shouldRun(Utils.adapterIs('cluster'))('get api channel with cluster adapter', done => { Utils.newServer({ port: 6001 }, (server1: Server) => { Utils.newClonedServer(server1, { port: 6002 }, (server2: Server) => { let client1 = Utils.newClient(); let backend = Utils.newBackend(); let channelName = Utils.randomChannelName(); client1.connection.bind('connected', () => { let channel = client1.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { backend.get({ path: '/channels/' + channelName }).then(res => res.json()).then(body => { expect(body.subscription_count).toBe(1); expect(body.occupied).toBe(true); let client2 = Utils.newClient(); client2.connection.bind('connected', () => { let channel = client2.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { backend.get({ path: '/channels/' + channelName }).then(res => res.json()).then(body => { expect(body.subscription_count).toBe(2); expect(body.occupied).toBe(true); client1.connection.bind('disconnected', () => { client2.disconnect(); }); client2.connection.bind('disconnected', () => { backend.get({ path: '/channels/' + channelName }).then(res => res.json()).then(body => { expect(body.subscription_count).toBe(0); expect(body.occupied).toBe(false); done(); }); }); client1.disconnect(); }); }); }); }); }); }); }); }); }); Utils.shouldRun(Utils.adapterIs('cluster'))('get api presence channel with cluster adapter', done => { let user1 = { user_id: 1, user_info: { id: 1, name: 'John', }, }; let user2 = { user_id: 2, user_info: { id: 2, name: 'Alice', }, }; Utils.newServer({ port: 6001 }, (server1: Server) => { Utils.newClonedServer(server1, { port: 6002 }, (server2: Server) => { let client1 = Utils.newClientForPresenceUser(user1); let backend = Utils.newBackend(); let channelName = `presence-${Utils.randomChannelName()}`; client1.connection.bind('connected', () => { let channel = client1.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { backend.get({ path: '/channels/' + channelName }).then(res => res.json()).then(body => { expect(body.subscription_count).toBe(1); expect(body.occupied).toBe(true); let client2 = Utils.newClientForPresenceUser(user2, {}, 6002); client2.connection.bind('connected', () => { let channel = client2.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { backend.get({ path: '/channels/' + channelName }).then(res => res.json()).then(body => { expect(body.subscription_count).toBe(2); expect(body.user_count).toBe(2); expect(body.occupied).toBe(true); client1.connection.bind('disconnected', () => { client2.disconnect(); }); client2.connection.bind('disconnected', () => { backend.get({ path: '/channels/' + channelName }).then(res => res.json()).then(body => { expect(body.subscription_count).toBe(0); expect(body.user_count).toBe(0); expect(body.occupied).toBe(false); done(); }); }); client1.disconnect(); }); }); }); }); }); }); }); }); }); Utils.shouldRun(Utils.adapterIs('cluster'))('get api presence users with cluster adapter', done => { let user1 = { user_id: 1, user_info: { id: 1, name: 'John', }, }; let user2 = { user_id: 2, user_info: { id: 2, name: 'Alice', }, }; Utils.newServer({ port: 6001 }, (server1: Server) => { Utils.newClonedServer(server1, { port: 6002 }, (server2: Server) => { let client1 = Utils.newClientForPresenceUser(user1); let backend = Utils.newBackend(); let channelName = `presence-${Utils.randomChannelName()}`; client1.connection.bind('connected', () => { let channel = client1.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => { expect(body.users.length).toBe(1); let client2 = Utils.newClientForPresenceUser(user2, {}, 6002); client2.connection.bind('connected', () => { let channel = client2.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => { expect(body.users.length).toBe(2); client1.connection.bind('disconnected', () => { client2.disconnect(); }); client2.connection.bind('disconnected', () => { backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => { expect(body.users.length).toBe(0); done(); }); }); client1.disconnect(); }); }); }); }); }); }); }); }); }); Utils.shouldRun(Utils.adapterIs('cluster'))('presence channel users should count only once for same-user multiple connections with cluster adapter', done => { let user = { user_id: 1, user_info: { id: 1, name: 'John', }, }; Utils.newServer({ port: 6001 }, (server1: Server) => { Utils.newClonedServer(server1, { port: 6002 }, (server2: Server) => { let client1 = Utils.newClientForPresenceUser(user); let backend = Utils.newBackend(); let channelName = `presence-${Utils.randomChannelName()}`; client1.connection.bind('connected', () => { let channel = client1.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => { expect(body.users.length).toBe(1); let client2 = Utils.newClientForPresenceUser(user, {}, 6002); client2.connection.bind('connected', () => { let channel = client2.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => { expect(body.users.length).toBe(1); client1.connection.bind('disconnected', () => { client2.disconnect(); }); client2.connection.bind('disconnected', () => { backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => { expect(body.users.length).toBe(0); done(); }); }); client1.disconnect(); }); }); }); }); }); }); }); }); }); Utils.shouldRun(Utils.adapterIs('cluster') && Utils.appManagerIs('array'))('signin after connection with termination call for cluster', done => { Utils.newServer({ 'appManager.array.apps.0.enableUserAuthentication': true, 'userAuthenticationTimeout': 5_000 }, (server1: Server) => { Utils.newClonedServer(server1, { port: 6002, 'appManager.array.apps.0.enableUserAuthentication': true, 'userAuthenticationTimeout': 5_000 }, (server2: Server) => { let client1 = Utils.newClientForPrivateChannel({}, 6001, 'app-key', { id: 1 }); let client2; let backend = Utils.newBackend(); client1.connection.bind('connected', () => { client1.connection.bind('message', (payload) => { if (payload.event === 'pusher:error' && payload.data.code === 4009) { client1.disconnect(); client2.disconnect(); done(); } if (payload.event === 'pusher:signin_success') { client2 = Utils.newClientForPrivateChannel({}, 6002, 'app-key', { id: 2 }); client2.connection.bind('connected', () => { client2.connection.bind('message', (payload) => { if (payload.event === 'pusher:signin_success') { backend.terminateUserConnections('1'); } }); client2.signin(); }); } }); client1.signin(); }); }); }); }); Utils.shouldRun(Utils.adapterIs('cluster') && Utils.appManagerIs('array'))('broadcast to user for cluster', done => { Utils.newServer({ 'appManager.array.apps.0.enableUserAuthentication': true, 'userAuthenticationTimeout': 5_000 }, (server1: Server) => { Utils.newClonedServer(server1, { 'port': 6002, 'appManager.array.apps.0.enableUserAuthentication': true, 'userAuthenticationTimeout': 5_000 }, (server2: Server) => { let client1 = Utils.newClientForPrivateChannel({}, 6001, 'app-key', { id: 1 }); let client2; let backend = Utils.newBackend(); client1.connection.bind('connected', () => { client1.connection.bind('message', (message) => { if (message.event === 'pusher:signin_success') { client2 = Utils.newClientForPrivateChannel({}, 6002, 'app-key', { id: 2 }); client2.connection.bind('connected', () => { client2.connection.bind('message', (payload) => { if (payload.event === 'pusher:signin_success') { backend.sendToUser('1', 'my-event', { works: true }); } }); client2.signin(); }); } if (message.event === 'my-event') { client1.disconnect(); client2.disconnect(); done(); } }); client1.signin(); }); }); }); }); }); ================================================ FILE: tests/http-api.nats-adapter.test.ts ================================================ import { Server } from './../src/server'; import { Utils } from './utils'; jest.retryTimes(parseInt(process.env.RETRY_TIMES || '1')); describe('http api test for nats adapter', () => { beforeEach(() => { jest.resetModules(); return Utils.waitForPortsToFreeUp(); }); afterEach(() => { return Utils.flushServers(); }); Utils.shouldRun(Utils.adapterIs('nats'))('get api channels with nats adapter', done => { Utils.newServer({ port: 6001 }, (server1: Server) => { Utils.newClonedServer(server1, { port: 6002 }, (server2: Server) => { let client1 = Utils.newClient(); let backend = Utils.newBackend(); let channelName = Utils.randomChannelName(); client1.connection.bind('connected', () => { let channel = client1.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { backend.get({ path: '/channels' }).then(res => res.json()).then(body => { expect(body.channels[channelName]).toBeDefined(); expect(body.channels[channelName].subscription_count).toBe(1); expect(body.channels[channelName].occupied).toBe(true); let client2 = Utils.newClient({}, 6002); client2.connection.bind('connected', () => { let channel = client2.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { backend.get({ path: '/channels' }).then(res => res.json()).then(body => { expect(body.channels[channelName]).toBeDefined(); expect(body.channels[channelName].subscription_count).toBe(2); expect(body.channels[channelName].occupied).toBe(true); client1.connection.bind('disconnected', () => { client2.disconnect(); }); client2.connection.bind('disconnected', () => { backend.get({ path: '/channels' }).then(res => res.json()).then(body => { // TODO: Expect // expect(body.channels[channelName]).toBeUndefined(); done(); }); }); client1.disconnect(); }); }); }); }); }); }); }); }); }); Utils.shouldRun(Utils.adapterIs('nats'))('get api channel with nats adapter', done => { Utils.newServer({ port: 6001 }, (server1: Server) => { Utils.newClonedServer(server1, { port: 6002 }, (server2: Server) => { let client1 = Utils.newClient(); let backend = Utils.newBackend(); let channelName = Utils.randomChannelName(); client1.connection.bind('connected', () => { let channel = client1.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { backend.get({ path: '/channels/' + channelName }).then(res => res.json()).then(body => { expect(body.subscription_count).toBe(1); expect(body.occupied).toBe(true); let client2 = Utils.newClient(); client2.connection.bind('connected', () => { let channel = client2.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { backend.get({ path: '/channels/' + channelName }).then(res => res.json()).then(body => { expect(body.subscription_count).toBe(2); expect(body.occupied).toBe(true); client1.connection.bind('disconnected', () => { client2.disconnect(); }); client2.connection.bind('disconnected', () => { backend.get({ path: '/channels/' + channelName }).then(res => res.json()).then(body => { expect(body.subscription_count).toBe(0); expect(body.occupied).toBe(false); done(); }); }); client1.disconnect(); }); }); }); }); }); }); }); }); }); Utils.shouldRun(Utils.adapterIs('nats'))('get api presence channel with nats adapter', done => { let user1 = { user_id: 1, user_info: { id: 1, name: 'John', }, }; let user2 = { user_id: 2, user_info: { id: 2, name: 'Alice', }, }; Utils.newServer({ port: 6001 }, (server1: Server) => { Utils.newClonedServer(server1, { port: 6002 }, (server2: Server) => { let client1 = Utils.newClientForPresenceUser(user1); let backend = Utils.newBackend(); let channelName = `presence-${Utils.randomChannelName()}`; client1.connection.bind('connected', () => { let channel = client1.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { backend.get({ path: '/channels/' + channelName }).then(res => res.json()).then(body => { expect(body.subscription_count).toBe(1); expect(body.occupied).toBe(true); let client2 = Utils.newClientForPresenceUser(user2, {}, 6002); client2.connection.bind('connected', () => { let channel = client2.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { backend.get({ path: '/channels/' + channelName }).then(res => res.json()).then(body => { expect(body.subscription_count).toBe(2); expect(body.user_count).toBe(2); expect(body.occupied).toBe(true); client1.connection.bind('disconnected', () => { client2.disconnect(); }); client2.connection.bind('disconnected', () => { backend.get({ path: '/channels/' + channelName }).then(res => res.json()).then(body => { expect(body.subscription_count).toBe(0); expect(body.user_count).toBe(0); expect(body.occupied).toBe(false); done(); }); }); client1.disconnect(); }); }); }); }); }); }); }); }); }); Utils.shouldRun(Utils.adapterIs('nats'))('get api presence users with nats adapter', done => { let user1 = { user_id: 1, user_info: { id: 1, name: 'John', }, }; let user2 = { user_id: 2, user_info: { id: 2, name: 'Alice', }, }; Utils.newServer({ port: 6001 }, (server1: Server) => { Utils.newClonedServer(server1, { port: 6002 }, (server2: Server) => { let client1 = Utils.newClientForPresenceUser(user1); let backend = Utils.newBackend(); let channelName = `presence-${Utils.randomChannelName()}`; client1.connection.bind('connected', () => { let channel = client1.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => { expect(body.users.length).toBe(1); let client2 = Utils.newClientForPresenceUser(user2, {}, 6002); client2.connection.bind('connected', () => { let channel = client2.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => { expect(body.users.length).toBe(2); client1.connection.bind('disconnected', () => { client2.disconnect(); }); client2.connection.bind('disconnected', () => { backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => { expect(body.users.length).toBe(0); done(); }); }); client1.disconnect(); }); }); }); }); }); }); }); }); }); Utils.shouldRun(Utils.adapterIs('nats'))('presence channel users should count only once for same-user multiple connections with nats adapter', done => { let user = { user_id: 1, user_info: { id: 1, name: 'John', }, }; Utils.newServer({ port: 6001 }, (server1: Server) => { Utils.newClonedServer(server1, { port: 6002 }, (server2: Server) => { let client1 = Utils.newClientForPresenceUser(user); let backend = Utils.newBackend(); let channelName = `presence-${Utils.randomChannelName()}`; client1.connection.bind('connected', () => { let channel = client1.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => { expect(body.users.length).toBe(1); let client2 = Utils.newClientForPresenceUser(user, {}, 6002); client2.connection.bind('connected', () => { let channel = client2.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => { expect(body.users.length).toBe(1); client1.connection.bind('disconnected', () => { client2.disconnect(); }); client2.connection.bind('disconnected', () => { backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => { expect(body.users.length).toBe(0); done(); }); }); client1.disconnect(); }); }); }); }); }); }); }); }); }); Utils.shouldRun(Utils.adapterIs('nats') && Utils.appManagerIs('array'))('signin after connection with termination call for nats', done => { Utils.newServer({ 'appManager.array.apps.0.enableUserAuthentication': true, 'userAuthenticationTimeout': 5_000 }, (server1: Server) => { Utils.newClonedServer(server1, { port: 6002, 'appManager.array.apps.0.enableUserAuthentication': true, 'userAuthenticationTimeout': 5_000 }, (server2: Server) => { let client1 = Utils.newClientForPrivateChannel({}, 6001, 'app-key', { id: 1 }); let client2; let backend = Utils.newBackend(); client1.connection.bind('connected', () => { client1.connection.bind('message', (payload) => { if (payload.event === 'pusher:error' && payload.data.code === 4009) { client1.disconnect(); client2.disconnect(); done(); } if (payload.event === 'pusher:signin_success') { client2 = Utils.newClientForPrivateChannel({}, 6002, 'app-key', { id: 2 }); client2.connection.bind('connected', () => { client2.connection.bind('message', (payload) => { if (payload.event === 'pusher:signin_success') { backend.terminateUserConnections('1'); } }); client2.signin(); }); } }); client1.signin(); }); }); }); }); Utils.shouldRun(Utils.adapterIs('nats') && Utils.appManagerIs('array'))('broadcast to user for nats', done => { Utils.newServer({ 'appManager.array.apps.0.enableUserAuthentication': true, 'userAuthenticationTimeout': 5_000 }, (server1: Server) => { Utils.newClonedServer(server1, { 'port': 6002, 'appManager.array.apps.0.enableUserAuthentication': true, 'userAuthenticationTimeout': 5_000 }, (server2: Server) => { let client1 = Utils.newClientForPrivateChannel({}, 6001, 'app-key', { id: 1 }); let client2; let backend = Utils.newBackend(); client1.connection.bind('connected', () => { client1.connection.bind('message', (message) => { if (message.event === 'pusher:signin_success') { client2 = Utils.newClientForPrivateChannel({}, 6002, 'app-key', { id: 2 }); client2.connection.bind('connected', () => { client2.connection.bind('message', (payload) => { if (payload.event === 'pusher:signin_success') { backend.sendToUser('1', 'my-event', { works: true }); } }); client2.signin(); }); } if (message.event === 'my-event') { client1.disconnect(); client2.disconnect(); done(); } }); client1.signin(); }); }); }); }); }); ================================================ FILE: tests/http-api.redis-adapter.test.ts ================================================ import { Server } from './../src/server'; import { Utils } from './utils'; jest.retryTimes(parseInt(process.env.RETRY_TIMES || '1')); describe('http api test for redis adapter', () => { beforeEach(() => { jest.resetModules(); return Utils.waitForPortsToFreeUp(); }); afterEach(() => { return Utils.flushServers(); }); Utils.shouldRun(Utils.adapterIs('redis'))('get api channels with redis adapter', done => { Utils.newServer({ port: 6001 }, (server1: Server) => { Utils.newClonedServer(server1, { port: 6002 }, (server2: Server) => { let client1 = Utils.newClient(); let backend = Utils.newBackend(); let channelName = Utils.randomChannelName(); client1.connection.bind('connected', () => { let channel = client1.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { backend.get({ path: '/channels' }).then(res => res.json()).then(body => { expect(body.channels[channelName]).toBeDefined(); expect(body.channels[channelName].subscription_count).toBe(1); expect(body.channels[channelName].occupied).toBe(true); let client2 = Utils.newClient({}, 6002); client2.connection.bind('connected', () => { let channel = client2.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { backend.get({ path: '/channels' }).then(res => res.json()).then(body => { expect(body.channels[channelName]).toBeDefined(); expect(body.channels[channelName].subscription_count).toBe(2); expect(body.channels[channelName].occupied).toBe(true); client1.connection.bind('disconnected', () => { client2.disconnect(); }); client2.connection.bind('disconnected', () => { backend.get({ path: '/channels' }).then(res => res.json()).then(body => { // TODO: Expect // expect(body.channels[channelName]).toBeUndefined(); done(); }); }); client1.disconnect(); }); }); }); }); }); }); }); }); }); Utils.shouldRun(Utils.adapterIs('redis'))('get api channel with redis adapter', done => { Utils.newServer({ port: 6001 }, (server1: Server) => { Utils.newClonedServer(server1, { port: 6002 }, (server2: Server) => { let client1 = Utils.newClient(); let backend = Utils.newBackend(); let channelName = Utils.randomChannelName(); client1.connection.bind('connected', () => { let channel = client1.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { backend.get({ path: '/channels/' + channelName }).then(res => res.json()).then(body => { expect(body.subscription_count).toBe(1); expect(body.occupied).toBe(true); let client2 = Utils.newClient(); client2.connection.bind('connected', () => { let channel = client2.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { backend.get({ path: '/channels/' + channelName }).then(res => res.json()).then(body => { expect(body.subscription_count).toBe(2); expect(body.occupied).toBe(true); client1.connection.bind('disconnected', () => { client2.disconnect(); }); client2.connection.bind('disconnected', () => { backend.get({ path: '/channels/' + channelName }).then(res => res.json()).then(body => { expect(body.subscription_count).toBe(0); expect(body.occupied).toBe(false); done(); }); }); client1.disconnect(); }); }); }); }); }); }); }); }); }); Utils.shouldRun(Utils.adapterIs('redis'))('get api presence channel with redis adapter', done => { let user1 = { user_id: 1, user_info: { id: 1, name: 'John', }, }; let user2 = { user_id: 2, user_info: { id: 2, name: 'Alice', }, }; Utils.newServer({ port: 6001 }, (server1: Server) => { Utils.newClonedServer(server1, { port: 6002 }, (server2: Server) => { let client1 = Utils.newClientForPresenceUser(user1); let backend = Utils.newBackend(); let channelName = `presence-${Utils.randomChannelName()}`; client1.connection.bind('connected', () => { let channel = client1.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { backend.get({ path: '/channels/' + channelName }).then(res => res.json()).then(body => { expect(body.subscription_count).toBe(1); expect(body.occupied).toBe(true); let client2 = Utils.newClientForPresenceUser(user2, {}, 6002); client2.connection.bind('connected', () => { let channel = client2.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { backend.get({ path: '/channels/' + channelName }).then(res => res.json()).then(body => { expect(body.subscription_count).toBe(2); expect(body.user_count).toBe(2); expect(body.occupied).toBe(true); client1.connection.bind('disconnected', () => { client2.disconnect(); }); client2.connection.bind('disconnected', () => { backend.get({ path: '/channels/' + channelName }).then(res => res.json()).then(body => { expect(body.subscription_count).toBe(0); expect(body.user_count).toBe(0); expect(body.occupied).toBe(false); done(); }); }); client1.disconnect(); }); }); }); }); }); }); }); }); }); Utils.shouldRun(Utils.adapterIs('redis'))('get api presence users with redis adapter', done => { let user1 = { user_id: 1, user_info: { id: 1, name: 'John', }, }; let user2 = { user_id: 2, user_info: { id: 2, name: 'Alice', }, }; Utils.newServer({ port: 6001 }, (server1: Server) => { Utils.newClonedServer(server1, { port: 6002 }, (server2: Server) => { let client1 = Utils.newClientForPresenceUser(user1); let backend = Utils.newBackend(); let channelName = `presence-${Utils.randomChannelName()}`; client1.connection.bind('connected', () => { let channel = client1.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => { expect(body.users.length).toBe(1); let client2 = Utils.newClientForPresenceUser(user2, {}, 6002); client2.connection.bind('connected', () => { let channel = client2.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => { expect(body.users.length).toBe(2); client1.connection.bind('disconnected', () => { client2.disconnect(); }); client2.connection.bind('disconnected', () => { backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => { expect(body.users.length).toBe(0); done(); }); }); client1.disconnect(); }); }); }); }); }); }); }); }); }); Utils.shouldRun(Utils.adapterIs('redis'))('presence channel users should count only once for same-user multiple connections with redis adapter', done => { let user = { user_id: 1, user_info: { id: 1, name: 'John', }, }; Utils.newServer({ port: 6001 }, (server1: Server) => { Utils.newClonedServer(server1, { port: 6002 }, (server2: Server) => { let client1 = Utils.newClientForPresenceUser(user); let backend = Utils.newBackend(); let channelName = `presence-${Utils.randomChannelName()}`; client1.connection.bind('connected', () => { let channel = client1.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => { expect(body.users.length).toBe(1); let client2 = Utils.newClientForPresenceUser(user, {}, 6002); client2.connection.bind('connected', () => { let channel = client2.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => { expect(body.users.length).toBe(1); client1.connection.bind('disconnected', () => { client2.disconnect(); }); client2.connection.bind('disconnected', () => { backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => { expect(body.users.length).toBe(0); done(); }); }); client1.disconnect(); }); }); }); }); }); }); }); }); }); Utils.shouldRun(Utils.adapterIs('redis') && Utils.appManagerIs('array'))('signin after connection with termination call for redis', done => { Utils.newServer({ 'appManager.array.apps.0.enableUserAuthentication': true, 'userAuthenticationTimeout': 5_000 }, (server1: Server) => { Utils.newClonedServer(server1, { port: 6002, 'appManager.array.apps.0.enableUserAuthentication': true, 'userAuthenticationTimeout': 5_000 }, (server2: Server) => { let client1 = Utils.newClientForPrivateChannel({}, 6001, 'app-key', { id: 1 }); let client2; let backend = Utils.newBackend(); client1.connection.bind('connected', () => { client1.connection.bind('message', (payload) => { if (payload.event === 'pusher:error' && payload.data.code === 4009) { client1.disconnect(); client2.disconnect(); done(); } if (payload.event === 'pusher:signin_success') { client2 = Utils.newClientForPrivateChannel({}, 6002, 'app-key', { id: 2 }); client2.connection.bind('connected', () => { client2.connection.bind('message', (payload) => { if (payload.event === 'pusher:signin_success') { backend.terminateUserConnections('1'); } }); client2.signin(); }); } }); client1.signin(); }); }); }); }); Utils.shouldRun(Utils.adapterIs('redis') && Utils.appManagerIs('array'))('broadcast to user for redis', done => { Utils.newServer({ 'appManager.array.apps.0.enableUserAuthentication': true, 'userAuthenticationTimeout': 5_000 }, (server1: Server) => { Utils.newClonedServer(server1, { 'port': 6002, 'appManager.array.apps.0.enableUserAuthentication': true, 'userAuthenticationTimeout': 5_000 }, (server2: Server) => { let client1 = Utils.newClientForPrivateChannel({}, 6001, 'app-key', { id: 1 }); let client2; let backend = Utils.newBackend(); client1.connection.bind('connected', () => { client1.connection.bind('message', (message) => { if (message.event === 'pusher:signin_success') { client2 = Utils.newClientForPrivateChannel({}, 6002, 'app-key', { id: 2 }); client2.connection.bind('connected', () => { client2.connection.bind('message', (payload) => { if (payload.event === 'pusher:signin_success') { backend.sendToUser('1', 'my-event', { works: true }); } }); client2.signin(); }); } if (message.event === 'my-event') { client1.disconnect(); client2.disconnect(); done(); } }); client1.signin(); }); }); }); }); }); ================================================ FILE: tests/http-api.test.ts ================================================ import axios from 'axios'; import { Server } from './../src/server'; import { Utils } from './utils'; jest.retryTimes(parseInt(process.env.RETRY_TIMES || '1')); describe('http api test', () => { beforeEach(() => { jest.resetModules(); return Utils.waitForPortsToFreeUp(); }); afterEach(() => { return Utils.flushServers(); }); test('health checks', done => { Utils.newServer({}, (server: Server) => { axios.get('http://127.0.0.1:6001').then(res => { done(); }).catch(() => { throw new Error('Healthchecks failed'); }); }); }); test('usage endpoint', done => { Utils.newServer({}, (server: Server) => { axios.get('http://127.0.0.1:9601/usage').then(res => { done(); }).catch(() => { throw new Error('Usage endpoint failed'); }); }); }); test('get api channels', done => { Utils.newServer({}, (server: Server) => { let client1 = Utils.newClient(); let backend = Utils.newBackend(); let channelName = Utils.randomChannelName(); client1.connection.bind('connected', () => { let channel = client1.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { backend.get({ path: '/channels' }).then(res => res.json()).then(body => { expect(body.channels[channelName]).toBeDefined(); expect(body.channels[channelName].subscription_count).toBe(1); expect(body.channels[channelName].occupied).toBe(true); let client2 = Utils.newClient(); client2.connection.bind('connected', () => { let channel = client2.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { backend.get({ path: '/channels' }).then(res => res.json()).then(body => { expect(body.channels[channelName]).toBeDefined(); expect(body.channels[channelName].subscription_count).toBe(2); expect(body.channels[channelName].occupied).toBe(true); client1.connection.bind('disconnected', () => { client2.disconnect(); }); client2.connection.bind('disconnected', () => { backend.get({ path: '/channels' }).then(res => res.json()).then(body => { expect(body.channels[channelName]).toBeUndefined(); done(); }); }); client1.disconnect(); }); }); }); }); }); }); }); }); test('get api channel', done => { Utils.newServer({}, (server: Server) => { let client1 = Utils.newClient(); let backend = Utils.newBackend(); let channelName = Utils.randomChannelName(); client1.connection.bind('connected', () => { let channel = client1.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { backend.get({ path: '/channels/' + channelName }).then(res => res.json()).then(body => { expect(body.subscription_count).toBe(1); expect(body.occupied).toBe(true); let client2 = Utils.newClient(); client2.connection.bind('connected', () => { let channel = client2.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { backend.get({ path: '/channels/' + channelName }).then(res => res.json()).then(body => { expect(body.subscription_count).toBe(2); expect(body.occupied).toBe(true); client1.connection.bind('disconnected', () => { client2.disconnect(); }); client2.connection.bind('disconnected', () => { backend.get({ path: '/channels/' + channelName }).then(res => res.json()).then(body => { expect(body.subscription_count).toBe(0); expect(body.occupied).toBe(false); done(); }); }); client1.disconnect(); }); }); }); }); }); }); }); }); test('get api presence channel', done => { let user1 = { user_id: 1, user_info: { id: 1, name: 'John', }, }; let user2 = { user_id: 2, user_info: { id: 2, name: 'Alice', }, }; Utils.newServer({}, (server: Server) => { let client1 = Utils.newClientForPresenceUser(user1); let backend = Utils.newBackend(); let channelName = `presence-${Utils.randomChannelName()}`; client1.connection.bind('connected', () => { let channel = client1.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { backend.get({ path: '/channels/' + channelName }).then(res => res.json()).then(body => { expect(body.subscription_count).toBe(1); expect(body.occupied).toBe(true); let client2 = Utils.newClientForPresenceUser(user2); client2.connection.bind('connected', () => { let channel = client2.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { backend.get({ path: '/channels/' + channelName }).then(res => res.json()).then(body => { expect(body.subscription_count).toBe(2); expect(body.user_count).toBe(2); expect(body.occupied).toBe(true); client1.connection.bind('disconnected', () => { client2.disconnect(); }); client2.connection.bind('disconnected', () => { backend.get({ path: '/channels/' + channelName }).then(res => res.json()).then(body => { expect(body.subscription_count).toBe(0); expect(body.user_count).toBe(0); expect(body.occupied).toBe(false); done(); }); }); client1.disconnect(); }); }); }); }); }); }); }); }); test('get api presence users', done => { let user1 = { user_id: 1, user_info: { id: 1, name: 'John', }, }; let user2 = { user_id: 2, user_info: { id: 2, name: 'Alice', }, }; Utils.newServer({}, (server: Server) => { let client1 = Utils.newClientForPresenceUser(user1); let backend = Utils.newBackend(); let channelName = `presence-${Utils.randomChannelName()}`; client1.connection.bind('connected', () => { let channel = client1.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => { expect(body.users.length).toBe(1); let client2 = Utils.newClientForPresenceUser(user2); client2.connection.bind('connected', () => { let channel = client2.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => { expect(body.users.length).toBe(2); client1.connection.bind('disconnected', () => { client2.disconnect(); }); client2.connection.bind('disconnected', () => { backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => { expect(body.users.length).toBe(0); done(); }); }); client1.disconnect(); }); }); }); }); }); }); }); }); test('presence channel users should count only once for same-user multiple connections', done => { let user = { user_id: 1, user_info: { id: 1, name: 'John', }, }; Utils.newServer({}, (server: Server) => { let client1 = Utils.newClientForPresenceUser(user); let backend = Utils.newBackend(); let channelName = `presence-${Utils.randomChannelName()}`; client1.connection.bind('connected', () => { let channel = client1.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => { expect(body.users.length).toBe(1); let client2 = Utils.newClientForPresenceUser(user); client2.connection.bind('connected', () => { let channel = client2.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => { expect(body.users.length).toBe(1); client1.connection.bind('disconnected', () => { client2.disconnect(); }); client2.connection.bind('disconnected', () => { backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => { expect(body.users.length).toBe(0); done(); }); }); client1.disconnect(); }); }); }); }); }); }); }); }); test('sends batch events', done => { Utils.newServer({}, (server: Server) => { let client = Utils.newClient(); let backend = Utils.newBackend(); let channelName = Utils.randomChannelName(); client.connection.bind('connected', () => { let channel = client.subscribe(channelName); let receivedMessages = 0; channel.bind('greeting', e => { expect(e.message).toBe('hello'); expect(e.weirdVariable).toBe('abc/d'); receivedMessages++; if (receivedMessages === 3) { client.disconnect(); done(); } }); channel.bind('pusher:subscription_succeeded', () => { backend.triggerBatch([ { name: 'greeting', channel: channelName, data: { message: 'hello', weirdVariable: 'abc/d' } }, { name: 'greeting', channel: channelName, data: { message: 'hello', weirdVariable: 'abc/d' } }, { name: 'greeting', channel: channelName, data: { message: 'hello', weirdVariable: 'abc/d' } }, ]).catch(error => { throw new Error(error); }); }); }); }); }); test('passing an inexistent app id will return 404', done => { Utils.newServer({}, (server: Server) => { let backend = Utils.newBackend('inexistent-app-id'); backend.get({ path: '/channels' }).then(res => res.json()).then(body => { expect(body.error).toBeDefined(); expect(body.code).toBe(404); done(); }); }); }); test('a non-presence channel cannot read users', done => { Utils.newServer({}, (server: Server) => { let client = Utils.newClient(); let channelName = Utils.randomChannelName(); let backend = Utils.newBackend(); client.connection.bind('connected', () => { let channel = client.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { backend.get({ path: '/channels/' + channelName + '/users' }).then(res => res.json()).then(body => { expect(body.error).toBeDefined(); expect(body.code).toBe(400); client.disconnect(); done(); }); }); }); }); }); test('throw error when credentials dont match', done => { Utils.newServer({}, (server: Server) => { let client = Utils.newClient(); let channelName = Utils.randomChannelName(); let goodBackend = Utils.newBackend(); let badBackend = Utils.newBackend('app-id', 'app-key', 'invalidSecret'); client.connection.bind('connected', () => { let channel = client.subscribe(channelName); channel.bind('greeting-from-bad', e => { // throw the test if the bad backend can emit // meaning that the security does not work expect(true).toBeFalsy(); done(); }); channel.bind('greeting-from-good', e => { client.disconnect(); done(); }); channel.bind('pusher:subscription_succeeded', () => { badBackend.trigger(channelName, 'greeting-from-bad', { message: 'hello', array: ['we', 'support', 'array'], objects: { works: true }, }).catch(error => { throw new Error(error); }); goodBackend.trigger(channelName, 'greeting-from-good', { message: 'hello', array: ['we', 'support', 'array'], objects: { works: true }, }).catch(error => { throw new Error(error); }); }); }); }); }); test('should check for eventLimits.maxChannelsAtOnce', done => { Utils.newServer({ 'eventLimits.maxChannelsAtOnce': 1 }, (server: Server) => { let backend = Utils.newBackend(); backend.trigger(['ch1', 'ch2'], 'greeting', { message: 'hello' }) .then(res => res.json()) .then(res => { expect(res.error).toBeDefined(); expect(res.code).toBe(400); done(); }) .catch(error => { throw new Error(error); }); }); }); test('should check for eventLimits.maxNameLength', done => { Utils.newServer({ 'eventLimits.maxNameLength': 7 }, (server: Server) => { let backend = Utils.newBackend(); backend.trigger('ch1', 'greeting', { message: 'hello' }) .then(res => res.json()) .then(res => { expect(res.error).toBeDefined(); expect(res.code).toBe(400); done(); }) .catch(error => { throw new Error(error); }); }); }); test('should check for eventLimits.maxPayloadInKb', done => { Utils.newServer({ 'eventLimits.maxPayloadInKb': 1/1024 }, (server: Server) => { let backend = Utils.newBackend(); backend.trigger('ch1', 'greeting', { message: 'hello' }) .then(res => res.json()) .then(res => { expect(res.error).toBeDefined(); expect(res.code).toBe(413); done(); }) .catch(error => { throw new Error(error); }); }); }); test('should check for httpApi.requestLimitInMb', done => { Utils.newServer({ 'httpApi.requestLimitInMb': 1/1024/1024 }, (server: Server) => { let backend = Utils.newBackend(); backend.trigger('ch1', 'greeting', { message: 'hello' }) .catch(err => { expect(err.body).toBeDefined(); expect(err.status).toBe(413); done(); }) .then(res => { if (res && res.json()) { throw new Error('The request limit did not work.'); } }); }); }); test('non existent route must return 404', done => { Utils.newServer({}, (server: Server) => { axios.get('http://127.0.0.1:6001/favicon.ico').then(res => { throw new Error('Status must be 404'); },(e) => { if (e.response.status !== 404) { throw new Error('Status must be 404'); } done(); }); }); }); test('check server can handle a numeric app id', done => { Utils.newServer({ 'appManager.array.apps.0.id': 40000 }, (server: Server) => { // Don't test database configs, because the APP-ID is hard coded (therefore this will always fail). if (process.env.TEST_APP_MANAGER != 'array') { done(); } let client = Utils.newClient(); let backend = Utils.newBackend("40000"); let channelName = Utils.randomChannelName(); client.connection.bind('connected', () => { let channel = client.subscribe(channelName); channel.bind('greeting', e => { expect(e.message).toBe('hello'); expect(e.weirdVariable).toBe('abc/d'); client.disconnect(); done(); }); channel.bind('pusher:subscription_succeeded', () => { backend.trigger(channelName, 'greeting', { message: 'hello', weirdVariable: 'abc/d' }) .catch(error => { throw new Error(error); }); }); }); }); }); Utils.shouldRun(Utils.appManagerIs('array'))('signin after connection with termination call', done => { Utils.newServer({ 'appManager.array.apps.0.enableUserAuthentication': true, 'userAuthenticationTimeout': 5_000 }, (server: Server) => { let client = Utils.newClientForPrivateChannel({}, 6001, 'app-key', { id: 1 }); let backend = Utils.newBackend(); client.connection.bind('connected', () => { client.connection.bind('message', (payload) => { if (payload.event === 'pusher:error' && payload.data.code === 4009) { client.disconnect(); done(); } if (payload.event === 'pusher:signin_success') { backend.terminateUserConnections('1'); } }); client.signin(); }); }); }); Utils.shouldRun(Utils.appManagerIs('array'))('broadcast to user', done => { Utils.newServer({ 'appManager.array.apps.0.enableUserAuthentication': true, 'userAuthenticationTimeout': 5_000 }, (server: Server) => { let client = Utils.newClientForPrivateChannel({}, 6001, 'app-key', { id: 1 }); let backend = Utils.newBackend(); client.connection.bind('connected', () => { client.connection.bind('message', (message) => { if (message.event === 'my-event') { client.disconnect(); done(); } if (message.event === 'pusher:signin_success') { backend.sendToUser('1', 'my-event', { works: true }); } }); client.signin(); }); }); }); test('get api presence channel with filter_by_prefix', done => { let user1 = { user_id: 1, user_info: { id: 1, name: 'John', }, }; Utils.newServer({}, (server: Server) => { let presenceClient = Utils.newClientForPresenceUser(user1); let backend = Utils.newBackend(); let presenceChannelName = `presence-${Utils.randomChannelName()}`; presenceClient.connection.bind('connected', () => { let presenceChannel = presenceClient.subscribe(presenceChannelName); presenceChannel.bind('pusher:subscription_succeeded', () => { let privateClient = Utils.newClientForPrivateChannel(); let privateChannelName = `private-${Utils.randomChannelName()}`; privateClient.connection.bind('connected', () => { let privateChannel = privateClient.subscribe(privateChannelName); privateChannel.bind('pusher:subscription_succeeded', () => { backend.get({ path: '/channels', params: { filter_by_prefix: `presence-` } }).then(res => res.json()).then(body => { expect(body.channels[presenceChannelName]).toBeDefined(); expect(body.channels[privateChannelName]).toBeUndefined(); expect(body.channels[presenceChannelName].subscription_count).toBe(1); presenceClient.disconnect(); privateClient.disconnect(); done(); }); }); }); }); }); }); }); }); ================================================ FILE: tests/presence.cluster-adapter.test.ts ================================================ import { Server } from './../src/server'; import { Utils } from './utils'; jest.retryTimes(parseInt(process.env.RETRY_TIMES || '1')); describe('presence channel test for cluster adapter', () => { beforeEach(() => { jest.resetModules(); return Utils.waitForPortsToFreeUp(); }); afterEach(() => { return Utils.flushServers(); }); Utils.shouldRun(Utils.adapterIs('cluster'))('handles joins and leaves for cluster adapter', done => { Utils.newServer({ port: 6001 }, (server1: Server) => { Utils.newClonedServer(server1, { port: 6002 }, (server2: Server) => { let john = { user_id: 1, user_info: { id: 1, name: 'John', }, }; let alice = { user_id: 2, user_info: { id: 2, name: 'Alice', }, }; let johnClient = Utils.newClientForPresenceUser(john); let channelName = `presence-${Utils.randomChannelName()}`; johnClient.connection.bind('connected', () => { let johnChannel = johnClient.subscribe(channelName); johnChannel.bind('pusher:subscription_succeeded', (data) => { expect(data.count).toBe(1); expect(data.me.id).toBe(1); expect(data.members['1'].id).toBe(1); expect(data.me.info.name).toBe('John'); let aliceClient = Utils.newClientForPresenceUser(alice, {}, 6002); aliceClient.connection.bind('connected', () => { Utils.wait(3000).then(() => { let aliceChannel = aliceClient.subscribe(channelName); aliceChannel.bind('pusher:subscription_succeeded', (data) => { expect(data.count).toBe(2); expect(data.me.id).toBe(2); expect(data.members['1'].id).toBe(1); expect(data.members['2'].id).toBe(2); expect(data.me.info.name).toBe('Alice'); aliceClient.disconnect(); }); }); }); }); johnChannel.bind('pusher:member_added', data => { expect(data.id).toBe(2); expect(data.info.name).toBe('Alice'); }); johnChannel.bind('pusher:member_removed', data => { expect(data.id).toBe(2); expect(data.info.name).toBe('Alice'); johnClient.disconnect(); done(); }); }); }); }); }); }); ================================================ FILE: tests/presence.nats-adapter.test.ts ================================================ import { Server } from './../src/server'; import { Utils } from './utils'; jest.retryTimes(parseInt(process.env.RETRY_TIMES || '1')); describe('presence channel test for nats adapter', () => { beforeEach(() => { jest.resetModules(); return Utils.waitForPortsToFreeUp(); }); afterEach(() => { return Utils.flushServers(); }); Utils.shouldRun(Utils.adapterIs('nats'))('handles joins and leaves for nats adapter', done => { Utils.newServer({ port: 6001 }, (server1: Server) => { Utils.newClonedServer(server1, { port: 6002 }, (server2: Server) => { let john = { user_id: 1, user_info: { id: 1, name: 'John', }, }; let alice = { user_id: 2, user_info: { id: 2, name: 'Alice', }, }; let johnClient = Utils.newClientForPresenceUser(john); let channelName = `presence-${Utils.randomChannelName()}`; johnClient.connection.bind('connected', () => { let johnChannel = johnClient.subscribe(channelName); johnChannel.bind('pusher:subscription_succeeded', (data) => { expect(data.count).toBe(1); expect(data.me.id).toBe(1); expect(data.members['1'].id).toBe(1); expect(data.me.info.name).toBe('John'); let aliceClient = Utils.newClientForPresenceUser(alice, {}, 6002); aliceClient.connection.bind('connected', () => { Utils.wait(3000).then(() => { let aliceChannel = aliceClient.subscribe(channelName); aliceChannel.bind('pusher:subscription_succeeded', (data) => { expect(data.count).toBe(2); expect(data.me.id).toBe(2); expect(data.members['1'].id).toBe(1); expect(data.members['2'].id).toBe(2); expect(data.me.info.name).toBe('Alice'); aliceClient.disconnect(); }); }); }); }); johnChannel.bind('pusher:member_added', data => { expect(data.id).toBe(2); expect(data.info.name).toBe('Alice'); }); johnChannel.bind('pusher:member_removed', data => { expect(data.id).toBe(2); expect(data.info.name).toBe('Alice'); johnClient.disconnect(); done(); }); }); }); }); }); }); ================================================ FILE: tests/presence.redis-adapter.test.ts ================================================ import { Server } from './../src/server'; import { Utils } from './utils'; jest.retryTimes(parseInt(process.env.RETRY_TIMES || '1')); describe('presence channel test for redis adapter', () => { beforeEach(() => { jest.resetModules(); return Utils.waitForPortsToFreeUp(); }); afterEach(() => { return Utils.flushServers(); }); Utils.shouldRun(Utils.adapterIs('redis'))('handles joins and leaves for redis adapter', done => { Utils.newServer({ port: 6001 }, (server1: Server) => { Utils.newClonedServer(server1, { port: 6002 }, (server2: Server) => { let john = { user_id: 1, user_info: { id: 1, name: 'John', }, }; let alice = { user_id: 2, user_info: { id: 2, name: 'Alice', }, }; let johnClient = Utils.newClientForPresenceUser(john); let channelName = `presence-${Utils.randomChannelName()}`; johnClient.connection.bind('connected', () => { let johnChannel = johnClient.subscribe(channelName); johnChannel.bind('pusher:subscription_succeeded', (data) => { expect(data.count).toBe(1); expect(data.me.id).toBe(1); expect(data.members['1'].id).toBe(1); expect(data.me.info.name).toBe('John'); let aliceClient = Utils.newClientForPresenceUser(alice, {}, 6002); aliceClient.connection.bind('connected', () => { let aliceChannel = aliceClient.subscribe(channelName); aliceChannel.bind('pusher:subscription_succeeded', (data) => { expect(data.count).toBe(2); expect(data.me.id).toBe(2); expect(data.members['1'].id).toBe(1); expect(data.members['2'].id).toBe(2); expect(data.me.info.name).toBe('Alice'); aliceClient.disconnect(); }); }); }); johnChannel.bind('pusher:member_added', data => { expect(data.id).toBe(2); expect(data.info.name).toBe('Alice'); }); johnChannel.bind('pusher:member_removed', data => { expect(data.id).toBe(2); expect(data.info.name).toBe('Alice'); johnClient.disconnect(); done(); }); }); }); }); }); }); ================================================ FILE: tests/presence.test.ts ================================================ import { Server } from './../src/server'; import { Utils } from './utils'; jest.retryTimes(parseInt(process.env.RETRY_TIMES || '1')); describe('presence channel test', () => { beforeEach(() => { jest.resetModules(); return Utils.waitForPortsToFreeUp(); }); afterEach(() => { return Utils.flushServers(); }); test('connects to presence channel', done => { Utils.newServer({}, (server: Server) => { let user = { user_id: 1, user_info: { id: 1, name: 'John', }, }; let client = Utils.newClientForPresenceUser(user); let backend = Utils.newBackend(); let channelName = `presence-${Utils.randomChannelName()}`; client.connection.bind('connected', () => { let channel = client.subscribe(channelName); channel.bind('greeting', (e) => { expect(e.message).toBe('hello'); client.disconnect(); done(); }); channel.bind('pusher:subscription_succeeded', (data) => { expect(data.count).toBe(1); expect(data.me.id).toBe(1); expect(data.members['1'].id).toBe(1); expect(data.me.info.name).toBe('John'); backend.trigger(channelName, 'greeting', { message: 'hello' }) .catch(error => { throw new Error(error); }); }); }); }); }); test('handles joins and leaves', done => { Utils.newServer({}, (server: Server) => { let john = { user_id: 1, user_info: { id: 1, name: 'John', }, }; let alice = { user_id: 2, user_info: { id: 2, name: 'Alice', }, }; let johnClient = Utils.newClientForPresenceUser(john); let channelName = `presence-${Utils.randomChannelName()}`; johnClient.connection.bind('connected', () => { let johnChannel = johnClient.subscribe(channelName); johnChannel.bind('pusher:subscription_succeeded', (data) => { expect(data.count).toBe(1); expect(data.me.id).toBe(1); expect(data.members['1'].id).toBe(1); expect(data.me.info.name).toBe('John'); let aliceClient = Utils.newClientForPresenceUser(alice); aliceClient.connection.bind('connected', () => { let aliceChannel = aliceClient.subscribe(channelName); aliceChannel.bind('pusher:subscription_succeeded', (data) => { expect(data.count).toBe(2); expect(data.me.id).toBe(2); expect(data.members['1'].id).toBe(1); expect(data.members['2'].id).toBe(2); expect(data.me.info.name).toBe('Alice'); aliceClient.disconnect(); }); }); }); johnChannel.bind('pusher:member_added', data => { expect(data.id).toBe(2); expect(data.info.name).toBe('Alice'); }); johnChannel.bind('pusher:member_removed', data => { expect(data.id).toBe(2); expect(data.info.name).toBe('Alice'); johnClient.disconnect(); done(); }); }); }); }); test('cannot connect to presence channel with wrong authentication', done => { Utils.newServer({}, (server: Server) => { let user = { user_id: 1, user_info: { id: 1, name: 'John', }, }; let client = Utils.newClientForPresenceUser(user, { authorizer: (channel, options) => ({ authorize: (socketId, callback) => { callback(false, { auth: 'incorrect_token', channel_data: JSON.stringify(user), }); }, }), }); let channelName = `presence-${Utils.randomChannelName()}`; client.connection.bind('message', ({ event, channel, data }) => { if (event === 'pusher:subscription_error' && channel === channelName) { expect(data.type).toBe('AuthError'); expect(data.status).toBe(401); client.disconnect(); done(); } }); client.connection.bind('connected', () => { client.subscribe(channelName); }); }); }); test('connects and disconnects to presence channel and does not leak memory', done => { Utils.newServer({}, (server: Server) => { let user = { user_id: 1, user_info: { id: 1, name: 'John', }, }; let client = Utils.newClientForPresenceUser(user); let backend = Utils.newBackend(); let channelName = `presence-${Utils.randomChannelName()}`; client.connection.bind('disconnected', () => { Utils.wait(3000).then(() => { let namespace = server.adapter.getNamespace('app-id'); expect(namespace.sockets.size).toBe(0); expect(namespace.channels.size).toBe(0); done(); }); }); client.connection.bind('connected', () => { let channel = client.subscribe(channelName); channel.bind('greeting', (e) => { expect(e.message).toBe('hello'); client.unsubscribe(channelName); Utils.wait(3000).then(() => { let namespace = server.adapter.getNamespace('app-id'); let socket = namespace.sockets.get(namespace.sockets.keys().next().value); expect(namespace.channels.size).toBe(0); expect(namespace.sockets.size).toBe(1); expect(socket.subscribedChannels.size).toBe(0); expect(socket.presence.size).toBe(0); client.disconnect(); }); }); channel.bind('pusher:subscription_succeeded', (data) => { backend.trigger(channelName, 'greeting', { message: 'hello' }); }); }); }); }); test('sudden close connection in presence channel and does not leak memory', done => { Utils.newServer({}, (server: Server) => { let user = { user_id: 1, user_info: { id: 1, name: 'John', }, }; let client = Utils.newClientForPresenceUser(user); let backend = Utils.newBackend(); let channelName = `presence-${Utils.randomChannelName()}`; client.connection.bind('disconnected', () => { Utils.wait(3000).then(() => { let namespace = server.adapter.getNamespace('app-id'); expect(namespace.sockets.size).toBe(0); expect(namespace.channels.size).toBe(0); done(); }); }); client.connection.bind('connected', () => { let channel = client.subscribe(channelName); channel.bind('greeting', (e) => { expect(e.message).toBe('hello'); client.disconnect(); }); channel.bind('pusher:subscription_succeeded', (data) => { backend.trigger(channelName, 'greeting', { message: 'hello' }); }); }); }); }); test('connecting to the channel twice with same user does not trigger member_added twice', done => { Utils.newServer({}, (server: Server) => { let john = { user_id: 1, user_info: { id: 1, name: 'John', }, }; let alice = { user_id: 2, user_info: { id: 2, name: 'Alice', }, }; let johnClient = Utils.newClientForPresenceUser(john); let channelName = `presence-${Utils.randomChannelName()}`; johnClient.connection.bind('connected', () => { let johnChannel = johnClient.subscribe(channelName); johnChannel.bind('pusher:subscription_succeeded', (data) => { let aliceClient = Utils.newClientForPresenceUser(alice); aliceClient.connection.bind('connected', () => { let aliceChannel = aliceClient.subscribe(channelName); aliceChannel.bind('pusher:member_added', data => { throw new Error('Did not expect John to be added again.'); }); aliceChannel.bind('pusher:member_removed', data => { server.adapter.getChannelMembers('app-id', channelName).then(members => { if (members.size === 1) { done(); aliceClient.disconnect(); } else { throw new Error('The member_removed got triggered but John did not left.'); } }); }); aliceChannel.bind('pusher:subscription_succeeded', (data) => { expect(data.count).toBe(2); let anotherJohnClient = Utils.newClientForPresenceUser(john); anotherJohnClient.connection.bind('connected', () => { let anotherJohnChannel = anotherJohnClient.subscribe(channelName); anotherJohnChannel.bind('pusher:subscription_succeeded', (data) => { expect(data.count).toBe(2); anotherJohnClient.disconnect(); johnClient.disconnect(); }); }); }); }); }); }); }); }); test('cached presence channels work', done => { Utils.newServer({}, (server: Server) => { let john = { user_id: 1, user_info: { id: 1, name: 'John', }, }; let alice = { user_id: 2, user_info: { id: 2, name: 'Alice', }, }; let client1 = Utils.newClientForPresenceUser(john); let backend = Utils.newBackend(); let channelName = `presence-cache-${Utils.randomChannelName()}`; client1.connection.bind('connected', () => { let channel = client1.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { channel.bind('pusher:cache_miss', (data) => { expect(data).toBe(undefined); channel.bind('greeting', e => { expect(e.message).toBe('hello'); let client2 = Utils.newClientForPresenceUser(alice); client2.connection.bind('connected', () => { let channel = client2.subscribe(channelName); channel.bind('greeting', e => { expect(e.message).toBe('hello'); done() }) channel.bind('pusher:cache_miss', () => { throw new Error('Did not expect cache_miss to be invoked.'); }); }); }); }); backend.trigger(channelName, 'greeting', { message: 'hello' }).catch(error => { throw new Error(error); }); }); }); }); }); Utils.shouldRun(Utils.appManagerIs('array'))('user authentication works if conn immediately joins a presence channel', (done) => { Utils.newServer({ 'appManager.array.apps.0.enableUserAuthentication': true, 'userAuthenticationTimeout': 5_000 }, (server: Server) => { let user = { user_id: 1, user_info: { id: 1, name: 'John', }, }; let client = Utils.newClientForPresenceUser(user); let channelName = `presence-${Utils.randomChannelName()}`; client.connection.bind('connected', () => { let channel = client.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { // After subscription, wait 10 seconds to make sure it isn't disconnected setTimeout(() => { client.disconnect(); done(); }, 10_000); }); }); }); }); }); ================================================ FILE: tests/private.test.ts ================================================ import { Server } from './../src/server'; import { Utils } from './utils'; jest.retryTimes(parseInt(process.env.RETRY_TIMES || '1')); describe('private channel test', () => { beforeEach(() => { jest.resetModules(); return Utils.waitForPortsToFreeUp(); }); afterEach(() => { return Utils.flushServers(); }); test('connects to private channel', done => { Utils.newServer({}, (server: Server) => { let client = Utils.newClientForPrivateChannel(); let backend = Utils.newBackend(); let channelName = `private-${Utils.randomChannelName()}`; client.connection.bind('connected', () => { let channel = client.subscribe(channelName); channel.bind('greeting', e => { expect(e.message).toBe('hello'); client.disconnect(); done(); }); channel.bind('pusher:subscription_succeeded', () => { backend.trigger(channelName, 'greeting', { message: 'hello' }) .catch(error => { throw new Error(error); }); }); }); }); }); test('cannot connect to private channel with wrong authentication', done => { Utils.newServer({}, (server: Server) => { let client = Utils.newClientForPrivateChannel({ authorizer: (channel, options) => ({ authorize: (socketId, callback) => { callback(false, { auth: 'incorrect_token', channel_data: null, }); }, }), }); let channelName = `private-${Utils.randomChannelName()}`; client.connection.bind('message', ({ event, channel, data }) => { if (event === 'pusher:subscription_error' && channel === channelName) { expect(data.type).toBe('AuthError'); expect(data.status).toBe(401); client.disconnect(); done(); } }); client.connection.bind('connected', () => { client.subscribe(channelName); }); }); }); test('connects and disconnects to private channel and does not leak memory', done => { Utils.newServer({}, (server: Server) => { let client = Utils.newClientForPrivateChannel(); let backend = Utils.newBackend(); let channelName = `private-${Utils.randomChannelName()}`; client.connection.bind('disconnected', () => { Utils.wait(3000).then(() => { let namespace = server.adapter.getNamespace('app-id'); expect(namespace.sockets.size).toBe(0); expect(namespace.channels.size).toBe(0); done(); }); }); client.connection.bind('connected', () => { let channel = client.subscribe(channelName); channel.bind('greeting', e => { expect(e.message).toBe('hello'); client.unsubscribe(channelName); Utils.wait(3000).then(() => { let namespace = server.adapter.getNamespace('app-id'); let socket = namespace.sockets.get(namespace.sockets.keys().next().value); expect(namespace.channels.size).toBe(0); expect(namespace.sockets.size).toBe(1); expect(socket.subscribedChannels.size).toBe(0); expect(socket.presence.size).toBe(0); client.disconnect(); }); }); channel.bind('pusher:subscription_succeeded', () => { backend.trigger(channelName, 'greeting', { message: 'hello' }); }); }); }); }); test('sudden close connection in private channel and does not leak memory', done => { Utils.newServer({}, (server: Server) => { let client = Utils.newClientForPrivateChannel(); let backend = Utils.newBackend(); let channelName = `private-${Utils.randomChannelName()}`; client.connection.bind('disconnected', () => { Utils.wait(3000).then(() => { let namespace = server.adapter.getNamespace('app-id'); expect(namespace.sockets.size).toBe(0); expect(namespace.channels.size).toBe(0); done(); }); }); client.connection.bind('connected', () => { let channel = client.subscribe(channelName); channel.bind('greeting', e => { expect(e.message).toBe('hello'); client.disconnect(); }); channel.bind('pusher:subscription_succeeded', () => { backend.trigger(channelName, 'greeting', { message: 'hello' }); }); }); }); }); test('cached private channels work', done => { Utils.newServer({}, (server: Server) => { let client1 = Utils.newClientForPrivateChannel(); let backend = Utils.newBackend(); let channelName = `private-cache-${Utils.randomChannelName()}`; client1.connection.bind('connected', () => { let channel = client1.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { channel.bind('pusher:cache_miss', (data) => { expect(data).toBe(undefined); channel.bind('greeting', e => { expect(e.message).toBe('hello'); let client2 = Utils.newClientForPrivateChannel(); client2.connection.bind('connected', () => { let channel = client2.subscribe(channelName); channel.bind('pusher:cache_miss', () => { throw new Error('Did not expect cache_miss to be invoked.'); }); channel.bind('greeting', e => { expect(e.message).toBe('hello'); done() }) }); }); }); backend.trigger(channelName, 'greeting', { message: 'hello' }).catch(error => { throw new Error(error); }); }); }); }); }); Utils.shouldRun(Utils.appManagerIs('array'))('user authentication works if conn immediately joins a private channel', (done) => { Utils.newServer({ 'appManager.array.apps.0.enableUserAuthentication': true, 'userAuthenticationTimeout': 5_000 }, (server: Server) => { let client = Utils.newClientForPrivateChannel(); let channelName = `private-${Utils.randomChannelName()}`; client.connection.bind('connected', () => { let channel = client.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { // After subscription, wait 10 seconds to make sure it isn't disconnected setTimeout(() => { client.disconnect(); done(); }, 10_000); }); }); }); }); }); ================================================ FILE: tests/public.test.ts ================================================ import { Server } from './../src/server'; import { Utils } from './utils'; describe('public channel test', () => { beforeEach(() => { jest.resetModules(); return Utils.waitForPortsToFreeUp(); }); afterEach(() => { return Utils.flushServers(); }); test('connects to public channel', done => { Utils.newServer({}, (server: Server) => { let client = Utils.newClient(); let backend = Utils.newBackend(); let channelName = Utils.randomChannelName(); client.connection.bind('connected', () => { let channel = client.subscribe(channelName); channel.bind('greeting', e => { expect(e.message).toBe('hello'); expect(e.weirdVariable).toBe('abc/d'); client.disconnect(); done(); }); channel.bind('pusher:subscription_succeeded', () => { backend.trigger(channelName, 'greeting', { message: 'hello', weirdVariable: 'abc/d' }) .catch(error => { throw new Error(error); }); }); }); }); }); test('connects and disconnected to public channel does not leak memory', done => { Utils.newServer({}, (server: Server) => { let client = Utils.newClient(); let backend = Utils.newBackend(); let channelName = Utils.randomChannelName(); client.connection.bind('disconnected', () => { Utils.wait(3000).then(() => { let namespace = server.adapter.getNamespace('app-id'); expect(namespace.sockets.size).toBe(0); expect(namespace.channels.size).toBe(0); done(); }); }); client.connection.bind('connected', () => { let channel = client.subscribe(channelName); channel.bind('greeting', e => { expect(e.message).toBe('hello'); client.unsubscribe(channelName); Utils.wait(3000).then(() => { let namespace = server.adapter.getNamespace('app-id'); let socket = namespace.sockets.get(namespace.sockets.keys().next().value); expect(namespace.channels.size).toBe(0); expect(namespace.sockets.size).toBe(1); expect(socket.subscribedChannels.size).toBe(0); expect(socket.presence.size).toBe(0); client.disconnect(); }); }); channel.bind('pusher:subscription_succeeded', () => { backend.trigger(channelName, 'greeting', { message: 'hello' }); }); }); }); }); test('sudden close connection in public channel does not leak memory', done => { Utils.newServer({}, (server: Server) => { let client = Utils.newClient(); let backend = Utils.newBackend(); let channelName = Utils.randomChannelName(); client.connection.bind('disconnected', () => { Utils.wait(3000).then(() => { let namespace = server.adapter.getNamespace('app-id'); expect(namespace.sockets.size).toBe(0); expect(namespace.channels.size).toBe(0); done(); }); }); client.connection.bind('connected', () => { let channel = client.subscribe(channelName); channel.bind('greeting', e => { expect(e.message).toBe('hello'); client.disconnect(); }); channel.bind('pusher:subscription_succeeded', () => { backend.trigger(channelName, 'greeting', { message: 'hello' }); }); }); }); }); test('cached public channels work', done => { Utils.newServer({}, (server: Server) => { let client1 = Utils.newClient(); let backend = Utils.newBackend(); let channelName = `cache-${Utils.randomChannelName()}`; client1.connection.bind('connected', () => { let channel = client1.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { channel.bind('pusher:cache_miss', (data) => { expect(data).toBe(undefined); channel.bind('greeting', e => { expect(e.message).toBe('hello'); let client2 = Utils.newClient(); client2.connection.bind('connected', () => { let channel = client2.subscribe(channelName); channel.bind('pusher:cache_miss', () => { throw new Error('Did not expect cache_miss to be invoked.'); }); channel.bind('greeting', e => { expect(e.message).toBe('hello'); done() }) }); }); }); backend.trigger(channelName, 'greeting', { message: 'hello' }).catch(error => { throw new Error(error); }); }); }); }); }); }); ================================================ FILE: tests/utils.ts ================================================ import async from 'async'; import { Log } from '../src/log'; import { PusherApiMessage } from '../src/message'; import { Server } from './../src/server'; import { v4 as uuidv4 } from 'uuid'; const bodyParser = require('body-parser'); const express = require('express'); const Pusher = require('pusher'); const PusherJS = require('pusher-js'); const tcpPortUsed = require('tcp-port-used'); export class Utils { public static wsServers: Server[] = []; public static httpServers: any[] = []; static appManagerIs(manager: string): boolean { return (process.env.TEST_APP_MANAGER || 'array') === manager; } static adapterIs(adapter: string) { return (process.env.TEST_ADAPTER || 'local') === adapter; } static queueDriverIs(queueDriver: string) { return (process.env.TEST_QUEUE_DRIVER || 'sync') === queueDriver; } static waitForPortsToFreeUp(): Promise { return Promise.all([ tcpPortUsed.waitUntilFree(6001, 500, 5 * 1000), tcpPortUsed.waitUntilFree(6002, 500, 5 * 1000), tcpPortUsed.waitUntilFree(3001, 500, 5 * 1000), tcpPortUsed.waitUntilFree(9601, 500, 5 * 1000), tcpPortUsed.waitUntilFree(11002, 500, 5 * 1000), ]); } static newServer(options = {}, callback): any { options = { 'cluster.prefix': uuidv4(), 'adapter.redis.prefix': uuidv4(), 'adapter.nats.prefix': uuidv4(), 'appManager.array.apps.0.maxBackendEventsPerSecond': 200, 'appManager.array.apps.0.maxClientEventsPerSecond': 200, 'appManager.array.apps.0.maxReadRequestsPerSecond': 200, 'metrics.enabled': true, 'appManager.mysql.useMysql2': true, 'cluster.port': parseInt((Math.random() * (20000 - 10000) + 10000).toString()), // random: 10000-20000 'appManager.dynamodb.endpoint': 'http://127.0.0.1:8000', 'cluster.ignoreProcess': false, 'webhooks.batching.enabled': false, // TODO: Find out why batching works but fails tests 'webhooks.batching.duration': 1, 'appManager.cache.enabled': true, 'appManager.cache.ttl': -1, ...options, 'adapter.driver': process.env.TEST_ADAPTER || 'local', 'cache.driver': process.env.TEST_CACHE_DRIVER || 'memory', 'appManager.driver': process.env.TEST_APP_MANAGER || 'array', 'queue.driver': process.env.TEST_QUEUE_DRIVER || 'sync', 'rateLimiter.driver': process.env.TEST_RATE_LIMITER || 'local', 'database.mysql.user': process.env.TEST_MYSQL_USER || 'testing', 'database.mysql.password': process.env.TEST_MYSQL_PASSWORD || 'testing', 'database.mysql.database': process.env.TEST_MYSQL_DATABASE || 'testing', 'database.postgres.user': process.env.TEST_POSTGRES_USER || 'testing', 'database.postgres.password': process.env.TEST_POSTGRES_PASSWORD || 'testing', 'database.postgres.database': process.env.TEST_POSTGRES_DATABASE || 'testing', 'queue.sqs.queueUrl': process.env.TEST_SQS_URL || 'http://localhost:4566/000000000000/test.fifo', 'debug': process.env.TEST_DEBUG || false, 'shutdownGracePeriod': 1_000, }; return (new Server(options)).start((server: Server) => { this.wsServers.push(server); if (server.options.cache.driver === 'redis') { server.cacheManager.driver.redisConnection.flushdb().then(() => { callback(server); }); } else { callback(server); } }); } static newClonedServer(server: Server, options = {}, callback): any { return this.newServer({ // Make sure the same prefixes exists so that they can communicate 'adapter.redis.prefix': server.options.adapter.redis.prefix, 'adapter.nats.prefix': server.options.adapter.nats.prefix, 'cluster.prefix': server.options.cluster.prefix, 'cluster.port': server.options.cluster.port, ...options, }, callback); } static newWebhookServer(requestHandler: CallableFunction, onReadyCallback: CallableFunction): any { let webhooksApp = express(); webhooksApp.use(bodyParser.json()); webhooksApp.use((req, res, next) => { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Methods', '*'); res.header('Access-Control-Allow-Headers', '*'); next(); }); webhooksApp.post('*', requestHandler); let server = webhooksApp.listen(3001, () => { Log.successTitle('🎉 Webhook Server is up and running!'); server.on('error', err => { console.log('Websocket server error', err); }); this.httpServers.push(server); onReadyCallback(server); }); } static flushWsServers(): Promise { if (this.wsServers.length === 0) { return Promise.resolve(); } return async.each(this.wsServers, (server: Server, serverCallback) => { server.stop().then(() => { serverCallback(); }); }).then(() => { this.wsServers = []; }); } static flushHttpServers(): Promise { if (this.httpServers.length === 0) { return Promise.resolve(); } return async.each(this.httpServers, (server: any, serverCallback) => { server.close(() => { serverCallback(); }); }).then(() => { this.httpServers = []; }); } static flushServers(): Promise { return Promise.all([ this.flushWsServers(), this.flushHttpServers(), ]); } static newClient(options = {}, port = 6001, key = 'app-key', withStateChange = true): any { let client = new PusherJS(key, { wsHost: '127.0.0.1', httpHost: '127.0.0.1', wsPort: port, wssPort: port, httpPort: port, httpsPort: port, forceTLS: false, encrypted: true, disableStats: true, enabledTransports: ['ws'], ignoreNullOrigin: true, encryptionMasterKeyBase64: 'nxzvbGF+f8FGhk/jOaZvgMle1tqxzF/VfUZLBLhhaH0=', ...options, }); if (withStateChange) { client.connection.bind('state_change', ({ current }) => { if (current === 'unavailable') { console.log('The connection could not be made. Status: ' + current); } }); } return client; } static newBackend(appId = 'app-id', key = 'app-key', secret = 'app-secret', port = 6001): any { return new Pusher({ appId, key, secret, host: '127.0.0.1', port, encryptionMasterKeyBase64: 'nxzvbGF+f8FGhk/jOaZvgMle1tqxzF/VfUZLBLhhaH0=', }); } static newClientForPrivateChannel(clientOptions = {}, port = 6001, key = 'app-key', userData = {}): any { return this.newClient({ authorizer: (channel, options) => ({ authorize: (socketId, callback) => { callback(false, { auth: this.signTokenForPrivateChannel(socketId, channel), channel_data: null, }); }, }), userAuthentication: { customHandler: ({ socketId }, callback) => { callback(false, { auth: this.signTokenForUserAuthentication(socketId, JSON.stringify(userData), key), user_data: JSON.stringify(userData), }); }, }, ...clientOptions, }, port, key); } static newClientForEncryptedPrivateChannel(clientOptions = {}, port = 6001, key = 'app-key', userData = {}): any { return this.newClient({ authorizer: (channel, options) => ({ authorize: (socketId, callback) => { callback(false, { auth: this.signTokenForPrivateChannel(socketId, channel, key), channel_data: null, shared_secret: this.newBackend().channelSharedSecret(channel.name).toString('base64'), }); }, }), userAuthentication: { customHandler: ({ socketId }, callback) => { callback(false, { auth: this.signTokenForUserAuthentication(socketId, JSON.stringify(userData), key), user_data: JSON.stringify(userData), }); }, }, ...clientOptions, }, port, key); } static newClientForPresenceUser(user: any, clientOptions = {}, port = 6001, key = 'app-key', userData = {}): any { return this.newClient({ authorizer: (channel, options) => ({ authorize: (socketId, callback) => { callback(false, { auth: this.signTokenForPresenceChannel(socketId, channel, user, key), channel_data: JSON.stringify(user), }); }, }), userAuthentication: { customHandler: ({ socketId }, callback) => { callback(false, { auth: this.signTokenForUserAuthentication(socketId, JSON.stringify(userData), key), user_data: JSON.stringify(userData), }); }, }, ...clientOptions, }, port, key); } static signTokenForPrivateChannel( socketId: string, channel: any, key = 'app-key', secret = 'app-secret' ): string { let token = new Pusher.Token(key, secret); return key + ':' + token.sign(`${socketId}:${channel.name}`); } static signTokenForPresenceChannel( socketId: string, channel: any, channelData: any, key = 'app-key', secret = 'app-secret' ): string { let token = new Pusher.Token(key, secret); return key + ':' + token.sign(`${socketId}:${channel.name}:${JSON.stringify(channelData)}`); } static signTokenForUserAuthentication( socketId: string, userData: string, key = 'app-key', secret = 'app-secret' ): string { let token = new Pusher.Token(key, secret); return key + ':' + token.sign(`${socketId}::user::${userData}`); } static wait(ms): Promise { return new Promise(resolve => setTimeout(resolve, ms)); } static randomChannelName(): string { return `channel-${Math.floor(Math.random() * 10000000)}`; } static shouldRun(condition): jest.It { return condition ? it : it.skip; } } ================================================ FILE: tests/webhooks.test.ts ================================================ import { App } from '../src/app'; import { Server } from '../src/server'; import { Utils } from './utils'; import { createWebhookHmac } from "../src/webhook-sender"; jest.retryTimes(parseInt(process.env.RETRY_TIMES || '1')); describe('webhooks test', () => { beforeEach(() => { jest.resetModules(); return Utils.waitForPortsToFreeUp(); }); afterEach(() => { return Utils.flushServers(); }); Utils.shouldRun(Utils.appManagerIs('array'))('webhooks from client events', done => { let webhooks = [{ event_types: ['client_event'], url: 'http://127.0.0.1:3001/webhook', }]; let channelName = `private-${Utils.randomChannelName()}`; let client1; let client2; Utils.newServer({ 'appManager.array.apps.0.enableClientMessages': true, 'appManager.array.apps.0.webhooks': webhooks, 'database.redis.keyPrefix': 'client-event-webhook', }, (server: Server) => { Utils.newWebhookServer((req, res) => { let app = new App(server.options.appManager.array.apps[0], server); let rightSignature = createWebhookHmac(JSON.stringify(req.body), app.secret); expect(req.headers['x-pusher-key']).toBe('app-key'); expect(req.headers['x-pusher-signature']).toBe(rightSignature); expect(req.body.time_ms).toBeDefined(); expect(req.body.events).toBeDefined(); expect(req.body.events.length).toBe(1); const webhookEvent = req.body.events[0]; expect(webhookEvent.name).toBe('client_event'); expect(webhookEvent.channel).toBe(channelName); expect(webhookEvent.event).toBe('client-greeting'); expect(webhookEvent.data.message).toBe('hello'); expect(webhookEvent.socket_id).toBeDefined(); res.json({ ok: true }); client1.disconnect(); client2.disconnect(); done(); }, (activeHttpServer) => { client1 = Utils.newClientForPrivateChannel(); client1.connection.bind('connected', () => { let channel = client1.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { client2 = Utils.newClientForPrivateChannel(); client2.connection.bind('connected', () => { let channel = client2.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { channel.trigger('client-greeting', { message: 'hello', }); }); }); }); }); }); }); }, 60 * 1000); Utils.shouldRun(Utils.appManagerIs('array'))('webhooks from channel_occupied and channel_vacated', done => { let webhooks = [{ event_types: ['channel_occupied', 'channel_vacated'], url: 'http://127.0.0.1:3001/webhook', }]; let channelName = `private-${Utils.randomChannelName()}`; let client = Utils.newClientForPrivateChannel(); Utils.newServer({ 'appManager.array.apps.0.webhooks': webhooks, 'database.redis.keyPrefix': 'channel-webhooks', }, (server: Server) => { Utils.newWebhookServer((req, res) => { let app = new App(server.options.appManager.array.apps[0], server); let rightSignature = createWebhookHmac(JSON.stringify(req.body), app.secret); expect(req.headers['x-pusher-key']).toBe('app-key'); expect(req.headers['x-pusher-signature']).toBe(rightSignature); expect(req.body.time_ms).toBeDefined(); expect(req.body.events).toBeDefined(); expect(req.body.events.length).toBe(1); const webhookEvent = req.body.events[0]; if (webhookEvent.name === 'channel_occupied') { expect(webhookEvent.channel).toBe(channelName); } res.json({ ok: true }); if (webhookEvent.name === 'channel_vacated') { expect(webhookEvent.channel).toBe(channelName); client.disconnect(); done(); } }, (activeHttpServer) => { client.connection.bind('connected', () => { let channel = client.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { client.unsubscribe(channelName); }); }); }); }); }, 60 * 1000); Utils.shouldRun(Utils.appManagerIs('array'))('webhooks from member_added and member_removed', done => { let webhooks = [{ event_types: ['member_added', 'member_removed'], url: 'http://127.0.0.1:3001/webhook', }]; let john = { user_id: 1, user_info: { id: 1, name: 'John', }, }; let alice = { user_id: 2, user_info: { id: 2, name: 'Alice', }, }; let channelName = `presence-${Utils.randomChannelName()}`; let johnClient; let aliceClient; Utils.newServer({ 'appManager.array.apps.0.webhooks': webhooks, 'database.redis.keyPrefix': 'presence-webhooks', }, (server: Server) => { Utils.newWebhookServer((req, res) => { let app = new App(server.options.appManager.array.apps[0], server); let rightSignature = createWebhookHmac(JSON.stringify(req.body), app.secret); expect(req.headers['x-pusher-key']).toBe('app-key'); expect(req.headers['x-pusher-signature']).toBe(rightSignature); expect(req.body.time_ms).toBeDefined(); expect(req.body.events).toBeDefined(); expect(req.body.events.length).toBe(1); const webhookEvent = req.body.events[0]; if (req.body.name === 'member_added') { expect(webhookEvent.channel).toBe(channelName); expect(webhookEvent.user_id).toBe(2); expect([1, 2].includes(webhookEvent.user_id)).toBe(true); } res.json({ ok: true }); if (webhookEvent.name === 'member_removed') { expect(webhookEvent.channel).toBe(channelName); expect(webhookEvent.user_id).toBe(2); johnClient.disconnect(); done(); } }, (activeHttpServer) => { johnClient = Utils.newClientForPresenceUser(john); johnClient.connection.bind('connected', () => { let johnChannel = johnClient.subscribe(channelName); johnChannel.bind('pusher:subscription_succeeded', (data) => { expect(data.count).toBe(1); expect(data.me.id).toBe(1); expect(data.members['1'].id).toBe(1); expect(data.me.info.name).toBe('John'); aliceClient = Utils.newClientForPresenceUser(alice); aliceClient.connection.bind('connected', () => { let aliceChannel = aliceClient.subscribe(channelName); aliceChannel.bind('pusher:subscription_succeeded', (data) => { expect(data.count).toBe(2); expect(data.me.id).toBe(2); expect(data.members['1'].id).toBe(1); expect(data.members['2'].id).toBe(2); expect(data.me.info.name).toBe('Alice'); aliceClient.disconnect(); }); }); }); johnChannel.bind('pusher:member_added', data => { expect(data.id).toBe(2); expect(data.info.name).toBe('Alice'); }); johnChannel.bind('pusher:member_removed', data => { expect(data.id).toBe(2); expect(data.info.name).toBe('Alice'); }); }); }); }); }, 60 * 1000); Utils.shouldRun(Utils.appManagerIs('array'))('webhooks from member_added and member_removed alongside filtering', done => { let channelName = `presence-${Utils.randomChannelName()}`; let webhooks = [ { event_types: ['member_added'], url: 'http://127.0.0.1:3001/webhook', filter: { channel_name_starts_with: channelName, }, }, { event_types: ['member_removed'], url: 'http://127.0.0.1:3001/webhook', filter: { channel_name_starts_with: channelName, }, }, ]; let john = { user_id: 1, user_info: { id: 1, name: 'John', }, }; let alice = { user_id: 2, user_info: { id: 2, name: 'Alice', }, }; let johnClient; let aliceClient; Utils.newServer({ 'appManager.array.apps.0.webhooks': webhooks, 'database.redis.keyPrefix': 'presence-webhooks', }, (server: Server) => { Utils.newWebhookServer((req, res) => { let app = new App(server.options.appManager.array.apps[0], server); let rightSignature = createWebhookHmac(JSON.stringify(req.body), app.secret); expect(req.headers['x-pusher-key']).toBe('app-key'); expect(req.headers['x-pusher-signature']).toBe(rightSignature); expect(req.body.time_ms).toBeDefined(); expect(req.body.events).toBeDefined(); expect(req.body.events.length).toBe(1); const webhookEvent = req.body.events[0]; if (req.body.name === 'member_added') { expect(webhookEvent.channel).toBe(channelName); expect(webhookEvent.user_id).toBe(2); expect([1, 2].includes(webhookEvent.user_id)).toBe(true); } res.json({ ok: true }); if (webhookEvent.name === 'member_removed') { expect(webhookEvent.channel).toBe(channelName); expect(webhookEvent.user_id).toBe(2); johnClient.disconnect(); done(); } }, (activeHttpServer) => { johnClient = Utils.newClientForPresenceUser(john); johnClient.connection.bind('connected', () => { let johnChannel = johnClient.subscribe(channelName); johnChannel.bind('pusher:subscription_succeeded', (data) => { expect(data.count).toBe(1); expect(data.me.id).toBe(1); expect(data.members['1'].id).toBe(1); expect(data.me.info.name).toBe('John'); aliceClient = Utils.newClientForPresenceUser(alice); aliceClient.connection.bind('connected', () => { let aliceChannel = aliceClient.subscribe(channelName); aliceChannel.bind('pusher:subscription_succeeded', (data) => { expect(data.count).toBe(2); expect(data.me.id).toBe(2); expect(data.members['1'].id).toBe(1); expect(data.members['2'].id).toBe(2); expect(data.me.info.name).toBe('Alice'); aliceClient.disconnect(); }); }); }); johnChannel.bind('pusher:member_added', data => { expect(data.id).toBe(2); expect(data.info.name).toBe('Alice'); }); johnChannel.bind('pusher:member_removed', data => { expect(data.id).toBe(2); expect(data.info.name).toBe('Alice'); }); }); }); }); }, 60 * 1000); Utils.shouldRun(Utils.appManagerIs('array'))('lambda webhooks', done => { let webhooks = [{ event_types: ['client_event'], lambda_function: 'some-lambda-function', lambda: { client_options: { endpoint: 'http://127.0.0.1:3001', }, }, }]; let channelName = `private-${Utils.randomChannelName()}`; let client1; let client2; Utils.newServer({ 'appManager.array.apps.0.enableClientMessages': true, 'appManager.array.apps.0.webhooks': webhooks, 'database.redis.keyPrefix': 'client-event-webhook', }, (server: Server) => { Utils.newWebhookServer((req, res) => { // Mocking the AWS endpoint as our webhook so that we can test // the fact that the AWS client sends the webhook through Lambda. expect(req.originalUrl).toBe('/2015-03-31/functions/some-lambda-function/invocations'); res.json({ ok: true }); client1.disconnect(); client2.disconnect(); done(); }, (activeHttpServer) => { client1 = Utils.newClientForPrivateChannel(); client1.connection.bind('connected', () => { let channel = client1.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { client2 = Utils.newClientForPrivateChannel(); client2.connection.bind('connected', () => { let channel = client2.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { channel.trigger('client-greeting', { message: 'hello', }); }); }); }); }); }); }); }, 60 * 1000); Utils.shouldRun(Utils.appManagerIs('array'))('webhooks filtered by channel name', done => { const sharedWebhookConfig = { event_types: ['channel_occupied'], url: 'http://127.0.0.1:3001/webhook', }; const webhooks = [ { ...sharedWebhookConfig, filter: { channel_name_starts_with: 'private-', }, }, { ...sharedWebhookConfig, filter: { channel_name_starts_with: 'private-', channel_name_ends_with: '-foo', }, }, { ...sharedWebhookConfig, filter: { channel_name_ends_with: '-bar', }, }, ]; // We expect the webhook to be called 1 time for these channels const matchedChannels = [ `private-${Utils.randomChannelName()}`, `private-${Utils.randomChannelName()}-foo`, `${Utils.randomChannelName()}-bar`, ]; // We don't expect any webhooks to be called for these channels const unmatchedChannels = [ `public-${Utils.randomChannelName()}`, `public-${Utils.randomChannelName()}-foo`, `${Utils.randomChannelName()}-foo`, ]; let client = Utils.newClientForPrivateChannel(); Utils.newServer({ 'appManager.array.apps.0.webhooks': webhooks, 'database.redis.keyPrefix': 'channel-webhooks', }, (server: Server) => { let receivedWebhookRequests = 0; Utils.newWebhookServer((req, res) => { let app = new App(server.options.appManager.array.apps[0], server); let rightSignature = createWebhookHmac(JSON.stringify(req.body), app.secret); expect(req.headers['x-pusher-key']).toBe('app-key'); expect(req.headers['x-pusher-signature']).toBe(rightSignature); expect(req.body.time_ms).toBeDefined(); expect(req.body.events).toBeDefined(); expect(req.body.events.length).toBe(1); req.body.events.forEach(webhookEvent => { if (matchedChannels.includes(webhookEvent.channel)) { receivedWebhookRequests += 1; } if (receivedWebhookRequests >= matchedChannels.length) { done(); client.disconnect(); } }); res.json({ ok: true }); }, (activeHttpServer) => { client.connection.bind('connected', () => { [...unmatchedChannels, ...matchedChannels].forEach(channelName => client.subscribe(channelName)); }); }); }); }, 60 * 1000); Utils.shouldRun(Utils.appManagerIs('array'))('webhooks can have custom headers', done => { const webhooks = [{ event_types: ['channel_occupied'], url: 'http://127.0.0.1:3001/webhook', headers: { 'X-Custom-Header': 'custom-value', // These headers below should not be sent with `custom-value` 'X-Pusher-Key': 'custom-value', 'X-Pusher-Signature': 'custom-value', }, }]; const channelName = `private-${Utils.randomChannelName()}`; let client = Utils.newClientForPrivateChannel(); Utils.newServer({ 'appManager.array.apps.0.webhooks': webhooks, 'database.redis.keyPrefix': 'channel-webhooks', }, (server: Server) => { Utils.newWebhookServer((req, res) => { let app = new App(server.options.appManager.array.apps[0], server); let rightSignature = createWebhookHmac(JSON.stringify(req.body), app.secret); expect(req.headers['x-pusher-key']).toBe('app-key'); expect(req.headers['x-pusher-signature']).toBe(rightSignature); expect(req.headers['x-custom-header']).toBe('custom-value'); expect(req.body.time_ms).toBeDefined(); expect(req.body.events).toBeDefined(); expect(req.body.events.length).toBe(1); res.json({ ok: true }); client.disconnect(); done(); }, (activeHttpServer) => { client.connection.bind('connected', () => { client.subscribe(channelName); }); }); }); }, 60 * 1000); Utils.shouldRun(Utils.appManagerIs('array') && Utils.queueDriverIs('sqs'))('sqs batching', done => { let webhooks = [{ event_types: ['client_event'], url: 'http://127.0.0.1:3001/webhook', }]; let channelName = `private-${Utils.randomChannelName()}`; let client1; let client2; Utils.newServer({ 'appManager.array.apps.0.enableClientMessages': true, 'appManager.array.apps.0.webhooks': webhooks, 'database.redis.keyPrefix': 'client-event-webhook', 'queue.sqs.processBatch': true, 'queue.sqs.batchSize': 2, 'queue.sqs.pollingWaitTimeMs': 1000, }, (server: Server) => { Utils.newWebhookServer((req, res) => { let app = new App(server.options.appManager.array.apps[0], server); let rightSignature = createWebhookHmac(JSON.stringify(req.body), app.secret); expect(req.headers['x-pusher-key']).toBe('app-key'); expect(req.headers['x-pusher-signature']).toBe(rightSignature); expect(req.body.time_ms).toBeDefined(); expect(req.body.events).toBeDefined(); expect(req.body.events.length).toBe(1); const webhookEvent = req.body.events[0]; expect(webhookEvent.name).toBe('client_event'); expect(webhookEvent.channel).toBe(channelName); expect(webhookEvent.event).toBe('client-greeting'); expect(webhookEvent.data.message).toBe('hello'); expect(webhookEvent.socket_id).toBeDefined(); res.json({ ok: true }); client1.disconnect(); client2.disconnect(); done(); }, (activeHttpServer) => { client1 = Utils.newClientForPrivateChannel(); client1.connection.bind('connected', () => { let channel = client1.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { client2 = Utils.newClientForPrivateChannel(); client2.connection.bind('connected', () => { let channel = client2.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { channel.trigger('client-greeting', { message: 'hello', }); }); }); }); }); }); }); }, 60 * 1000); Utils.shouldRun(Utils.appManagerIs('array'))('webhooks from cache_miss', done => { let webhooks = [{ event_types: ['cache_miss'], url: 'http://127.0.0.1:3001/webhook', }]; let channelName = `private-cache-${Utils.randomChannelName()}`; let client = Utils.newClientForPrivateChannel(); Utils.newServer({ 'appManager.array.apps.0.webhooks': webhooks, 'database.redis.keyPrefix': 'client-event-cache-miss', }, (server: Server) => { Utils.newWebhookServer((req, res) => { let app = new App(server.options.appManager.array.apps[0], server); let rightSignature = createWebhookHmac(JSON.stringify(req.body), app.secret); expect(req.headers['x-pusher-key']).toBe('app-key'); expect(req.headers['x-pusher-signature']).toBe(rightSignature); expect(req.body.time_ms).toBeDefined(); expect(req.body.events).toBeDefined(); expect(req.body.events.length).toBe(1); const webhookEvent = req.body.events[0]; if (webhookEvent.name === 'cache_miss') { expect(webhookEvent.channel).toBe(channelName); client.disconnect(); done(); } res.json({ ok: true }); }, (activeHttpServer) => { client.connection.bind('connected', () => { client.subscribe(channelName); }); }); }); }, 20_000); }); ================================================ FILE: tests/ws.cluster-adapter.test.ts ================================================ import { Server } from './../src/server'; import { Utils } from './utils'; jest.retryTimes(parseInt(process.env.RETRY_TIMES || '1')); describe('ws test for cluster adapter', () => { beforeEach(() => { jest.resetModules(); return Utils.waitForPortsToFreeUp(); }); afterEach(() => { return Utils.flushServers(); }); Utils.shouldRun(Utils.adapterIs('cluster') && Utils.appManagerIs('array'))('client events with cluster adapter', done => { Utils.newServer({ 'appManager.array.apps.0.enableClientMessages': true }, (server1: Server) => { Utils.newClonedServer(server1, { 'appManager.array.apps.0.enableClientMessages': true, port: 6002 }, (server2: Server) => { let client1 = Utils.newClientForPrivateChannel(); let client2; let channelName = `private-${Utils.randomChannelName()}`; client1.connection.bind('connected', () => { client1.connection.bind('message', ({ event, channel, data }) => { if (event === 'client-greeting' && channel === channelName) { expect(data.message).toBe('hello'); client1.disconnect(); client2.disconnect(); done(); } }); let channel = client1.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { Utils.wait(3000).then(() => { client2 = Utils.newClientForPrivateChannel({}, 6002); client2.connection.bind('connected', () => { let channel = client2.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { channel.trigger('client-greeting', { message: 'hello', }); }); }); }); }); }); }); }); }); Utils.shouldRun(Utils.adapterIs('cluster') && Utils.appManagerIs('array'))('client events dont get emitted when client messaging is disabled with cluster adapter', done => { Utils.newServer({ 'appManager.array.apps.0.enableClientMessages': false }, (server1: Server) => { Utils.newClonedServer(server1, { 'appManager.array.apps.0.enableClientMessages': false, port: 6002 }, (server2: Server) => { let client1 = Utils.newClientForPrivateChannel(); let channelName = `private-${Utils.randomChannelName()}`; client1.connection.bind('connected', () => { client1.connection.bind('message', ({ event, channel, data }) => { if (event === 'client-greeting' && channel === channelName) { throw new Error('The message was actually sent.'); } }); let channel = client1.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { Utils.wait(3000).then(() => { let client2 = Utils.newClientForPrivateChannel({}, 6002); client2.connection.bind('connected', () => { let channel = client2.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { channel.bind('pusher:error', (error) => { expect(error.code).toBe(4301); client1.disconnect(); client2.disconnect(); done(); }); channel.trigger('client-greeting', { message: 'hello', }); }); }); }); }); }); }); }); }); Utils.shouldRun(Utils.adapterIs('cluster') && Utils.appManagerIs('array'))('client events dont get emitted when event name is big with cluster adapter', done => { Utils.newServer({ 'appManager.array.apps.0.enableClientMessages': true, 'eventLimits.maxNameLength': 25 }, (server1: Server) => { Utils.newClonedServer(server1, { 'appManager.array.apps.0.enableClientMessages': true, 'eventLimits.maxNameLength': 25, port: 6002 }, (server2: Server) => { let client1 = Utils.newClientForPrivateChannel(); let channelName = `private-${Utils.randomChannelName()}`; let eventName = 'client-a8hsuNFXUhfStiWE02R'; // 26 characters client1.connection.bind('connected', () => { client1.connection.bind('message', ({ event, channel, data }) => { if (event === eventName && channel === channelName) { throw new Error('The message was actually sent.'); } }); let channel = client1.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { Utils.wait(3000).then(() => { let client2 = Utils.newClientForPrivateChannel({}, 6002); client2.connection.bind('connected', () => { let channel = client2.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { channel.bind('pusher:error', (error) => { expect(error.code).toBe(4301); client1.disconnect(); client2.disconnect(); done(); }); channel.trigger(eventName, { message: 'hello', }); }); }); }); }); }); }); }); }); Utils.shouldRun(Utils.adapterIs('cluster') && Utils.appManagerIs('array'))('client events dont get emitted when event payload is big with cluster adapter', done => { Utils.newServer({ 'appManager.array.apps.0.enableClientMessages': true, 'eventLimits.maxPayloadInKb': 1/1024/1024 }, (server1: Server) => { Utils.newClonedServer(server1, { 'appManager.array.apps.0.enableClientMessages': true, 'eventLimits.maxPayloadInKb': 1/1024/1024, port: 6002 }, (server2: Server) => { let client1 = Utils.newClientForPrivateChannel(); let channelName = `private-${Utils.randomChannelName()}`; client1.connection.bind('connected', () => { client1.connection.bind('message', ({ event, channel, data }) => { if (event === 'client-greeting' && channel === channelName) { throw new Error('The message was actually sent.'); } }); let channel = client1.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { Utils.wait(3000).then(() => { let client2 = Utils.newClientForPrivateChannel({}, 6002); client2.connection.bind('connected', () => { let channel = client2.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { channel.bind('pusher:error', (error) => { expect(error.code).toBe(4301); client1.disconnect(); client2.disconnect(); done(); }); channel.trigger('client-greeting', { message: 'hello', }); }); }); }); }); }); }); }); }); Utils.shouldRun(Utils.adapterIs('cluster') && Utils.appManagerIs('array'))('throw over quota error if reached connection limit for cluster adapter', done => { Utils.newServer({ 'appManager.array.apps.0.maxConnections': 1, port: 6001 }, (server1: Server) => { Utils.newClonedServer(server1, { 'appManager.array.apps.0.maxConnections': 1, port: 6002 }, (server2: Server) => { let client1 = Utils.newClient({}, 6001, 'app-key', false); client1.connection.bind('connected', () => { Utils.wait(3000).then(() => { let client2 = Utils.newClient({}, 6002, 'app-key', false); client2.connection.bind('state_change', ({ current }) => { if (current === 'failed') { client1.disconnect(); done(); } else { throw new Error(`${current} is not an expected state.`); } }); }); }); }); }); }); Utils.shouldRun(Utils.adapterIs('cluster'))('should check for presence.maxMembersPerChannel for cluster adapter', done => { Utils.newServer({ 'presence.maxMembersPerChannel': 1, port: 6001 }, (server1: Server) => { Utils.newClonedServer(server1, { 'presence.maxMembersPerChannel': 1, port: 6002 }, (server2: Server) => { let user1 = { user_id: 1, user_info: { id: 1, name: 'John', }, }; let user2 = { user_id: 2, user_info: { id: 2, name: 'Alice', }, }; let client1 = Utils.newClientForPresenceUser(user1); let client2 = Utils.newClientForPresenceUser(user2, {}, 6002); let channelName = `presence-${Utils.randomChannelName()}`; client1.connection.bind('connected', () => { let channel1 = client1.subscribe(channelName); channel1.bind('pusher:subscription_succeeded', () => { Utils.wait(3000).then(() => { client2.connection.bind('message', ({ event, channel, data }) => { if (event === 'pusher:subscription_error' && channel === channelName) { expect(data.type).toBe('LimitReached'); expect(data.status).toBe(4100); expect(data.error).toBeDefined(); client1.disconnect(); client2.disconnect(); done(); } }); client2.subscribe(channelName); }); }); }); }); }); }); Utils.shouldRun(Utils.adapterIs('cluster'))('adapter getSockets works with cluster adapter', done => { Utils.newServer({}, (server1: Server) => { Utils.newClonedServer(server1, { port: 6002 }, (server2: Server) => { let client1 = Utils.newClient(); client1.connection.bind('connected', () => { Utils.wait(3000).then(() => { server1.adapter.getSockets('app-id').then(sockets => { expect(sockets.size).toBe(1); let client2 = Utils.newClient({}, 6002); client2.connection.bind('connected', () => { server1.adapter.getSockets('app-id').then(sockets => { expect(sockets.size).toBe(2); client1.disconnect(); client2.disconnect(); done(); }); }); }); }); }); }); }); }); Utils.shouldRun(Utils.adapterIs('cluster'))('adapter getChannelSockets works with cluster adapter', done => { Utils.newServer({}, (server1: Server) => { Utils.newClonedServer(server1, { port: 6002 }, (server2: Server) => { let client1 = Utils.newClient(); let channelName = Utils.randomChannelName(); client1.connection.bind('connected', () => { server1.adapter.getChannelSockets('app-id', channelName).then(sockets => { expect(sockets.size).toBe(0); let channel1 = client1.subscribe(channelName); channel1.bind('pusher:subscription_succeeded', () => { Utils.wait(3000).then(() => { server1.adapter.getChannelSockets('app-id', channelName).then(sockets => { expect(sockets.size).toBe(1); let client2 = Utils.newClient({}, 6002); client2.connection.bind('connected', () => { let channel2 = client2.subscribe(channelName); channel2.bind('pusher:subscription_succeeded', () => { Utils.wait(3000).then(() => { server1.adapter.getChannelSockets('app-id', channelName).then(sockets => { expect(sockets.size).toBe(2); client2.unsubscribe(channelName); Utils.wait(3000).then(() => { server1.adapter.getChannelSockets('app-id', channelName).then(sockets => { expect(sockets.size).toBe(1); client1.disconnect(); client2.disconnect(); done(); }); }); }); }); }); }); }); }); }); }); }); }); }); }); }); ================================================ FILE: tests/ws.nats-adapter.test.ts ================================================ import { Server } from './../src/server'; import { Utils } from './utils'; jest.retryTimes(parseInt(process.env.RETRY_TIMES || '1')); describe('ws test for nats adapter', () => { beforeEach(() => { jest.resetModules(); return Utils.waitForPortsToFreeUp(); }); afterEach(() => { return Utils.flushServers(); }); Utils.shouldRun(Utils.adapterIs('nats') && Utils.appManagerIs('array'))('client events with nats adapter', done => { Utils.newServer({ 'appManager.array.apps.0.enableClientMessages': true }, (server1: Server) => { Utils.newClonedServer(server1, { 'appManager.array.apps.0.enableClientMessages': true, port: 6002 }, (server2: Server) => { let client1 = Utils.newClientForPrivateChannel(); let client2; let channelName = `private-${Utils.randomChannelName()}`; client1.connection.bind('connected', () => { client1.connection.bind('message', ({ event, channel, data }) => { if (event === 'client-greeting' && channel === channelName) { expect(data.message).toBe('hello'); client1.disconnect(); client2.disconnect(); done(); } }); let channel = client1.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { Utils.wait(3000).then(() => { client2 = Utils.newClientForPrivateChannel({}, 6002); client2.connection.bind('connected', () => { let channel = client2.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { channel.trigger('client-greeting', { message: 'hello', }); }); }); }); }); }); }); }); }); Utils.shouldRun(Utils.adapterIs('nats') && Utils.appManagerIs('array'))('client events dont get emitted when client messaging is disabled with nats adapter', done => { Utils.newServer({ 'appManager.array.apps.0.enableClientMessages': false }, (server1: Server) => { Utils.newClonedServer(server1, { 'appManager.array.apps.0.enableClientMessages': false, port: 6002 }, (server2: Server) => { let client1 = Utils.newClientForPrivateChannel(); let channelName = `private-${Utils.randomChannelName()}`; client1.connection.bind('connected', () => { client1.connection.bind('message', ({ event, channel, data }) => { if (event === 'client-greeting' && channel === channelName) { throw new Error('The message was actually sent.'); } }); let channel = client1.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { Utils.wait(3000).then(() => { let client2 = Utils.newClientForPrivateChannel({}, 6002); client2.connection.bind('connected', () => { let channel = client2.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { channel.bind('pusher:error', (error) => { expect(error.code).toBe(4301); client1.disconnect(); client2.disconnect(); done(); }); channel.trigger('client-greeting', { message: 'hello', }); }); }); }); }); }); }); }); }); Utils.shouldRun(Utils.adapterIs('nats') && Utils.appManagerIs('array'))('client events dont get emitted when event name is big with nats adapter', done => { Utils.newServer({ 'appManager.array.apps.0.enableClientMessages': true, 'eventLimits.maxNameLength': 25 }, (server1: Server) => { Utils.newClonedServer(server1, { 'appManager.array.apps.0.enableClientMessages': true, 'eventLimits.maxNameLength': 25, port: 6002 }, (server2: Server) => { let client1 = Utils.newClientForPrivateChannel(); let channelName = `private-${Utils.randomChannelName()}`; let eventName = 'client-a8hsuNFXUhfStiWE02R'; // 26 characters client1.connection.bind('connected', () => { client1.connection.bind('message', ({ event, channel, data }) => { if (event === eventName && channel === channelName) { throw new Error('The message was actually sent.'); } }); let channel = client1.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { Utils.wait(3000).then(() => { let client2 = Utils.newClientForPrivateChannel({}, 6002); client2.connection.bind('connected', () => { let channel = client2.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { channel.bind('pusher:error', (error) => { expect(error.code).toBe(4301); client1.disconnect(); client2.disconnect(); done(); }); channel.trigger(eventName, { message: 'hello', }); }); }); }); }); }); }); }); }); Utils.shouldRun(Utils.adapterIs('nats') && Utils.appManagerIs('array'))('client events dont get emitted when event payload is big with nats adapter', done => { Utils.newServer({ 'appManager.array.apps.0.enableClientMessages': true, 'eventLimits.maxPayloadInKb': 1/1024/1024 }, (server1: Server) => { Utils.newClonedServer(server1, { 'appManager.array.apps.0.enableClientMessages': true, 'eventLimits.maxPayloadInKb': 1/1024/1024, port: 6002 }, (server2: Server) => { let client1 = Utils.newClientForPrivateChannel(); let channelName = `private-${Utils.randomChannelName()}`; client1.connection.bind('connected', () => { client1.connection.bind('message', ({ event, channel, data }) => { if (event === 'client-greeting' && channel === channelName) { throw new Error('The message was actually sent.'); } }); let channel = client1.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { Utils.wait(3000).then(() => { let client2 = Utils.newClientForPrivateChannel({}, 6002); client2.connection.bind('connected', () => { let channel = client2.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { channel.bind('pusher:error', (error) => { expect(error.code).toBe(4301); client1.disconnect(); client2.disconnect(); done(); }); channel.trigger('client-greeting', { message: 'hello', }); }); }); }); }); }); }); }); }); Utils.shouldRun(Utils.adapterIs('nats') && Utils.appManagerIs('array'))('throw over quota error if reached connection limit for nats adapter', done => { Utils.newServer({ 'appManager.array.apps.0.maxConnections': 1, port: 6001 }, (server1: Server) => { Utils.newClonedServer(server1, { 'appManager.array.apps.0.maxConnections': 1, port: 6002 }, (server2: Server) => { let client1 = Utils.newClient({}, 6001, 'app-key', false); client1.connection.bind('connected', () => { Utils.wait(3000).then(() => { let client2 = Utils.newClient({}, 6002, 'app-key', false); client2.connection.bind('state_change', ({ current }) => { if (current === 'failed') { client1.disconnect(); done(); } else { throw new Error(`${current} is not an expected state.`); } }); }); }); }); }); }); Utils.shouldRun(Utils.adapterIs('nats'))('should check for presence.maxMembersPerChannel for nats adapter', done => { Utils.newServer({ 'presence.maxMembersPerChannel': 1, port: 6001 }, (server1: Server) => { Utils.newClonedServer(server1, { 'presence.maxMembersPerChannel': 1, port: 6002 }, (server2: Server) => { let user1 = { user_id: 1, user_info: { id: 1, name: 'John', }, }; let user2 = { user_id: 2, user_info: { id: 2, name: 'Alice', }, }; let client1 = Utils.newClientForPresenceUser(user1); let client2 = Utils.newClientForPresenceUser(user2, {}, 6002); let channelName = `presence-${Utils.randomChannelName()}`; client1.connection.bind('connected', () => { let channel1 = client1.subscribe(channelName); channel1.bind('pusher:subscription_succeeded', () => { Utils.wait(3000).then(() => { client2.connection.bind('message', ({ event, channel, data }) => { if (event === 'pusher:subscription_error' && channel === channelName) { expect(data.type).toBe('LimitReached'); expect(data.status).toBe(4100); expect(data.error).toBeDefined(); client1.disconnect(); client2.disconnect(); done(); } }); client2.subscribe(channelName); }); }); }); }); }); }); Utils.shouldRun(Utils.adapterIs('nats'))('adapter getSockets works with nats adapter', done => { Utils.newServer({}, (server1: Server) => { Utils.newClonedServer(server1, { port: 6002 }, (server2: Server) => { let client1 = Utils.newClient(); client1.connection.bind('connected', () => { Utils.wait(3000).then(() => { server1.adapter.getSockets('app-id').then(sockets => { expect(sockets.size).toBe(1); let client2 = Utils.newClient({}, 6002); client2.connection.bind('connected', () => { server1.adapter.getSockets('app-id').then(sockets => { expect(sockets.size).toBe(2); client1.disconnect(); client2.disconnect(); done(); }); }); }); }); }); }); }); }); Utils.shouldRun(Utils.adapterIs('nats'))('adapter getChannelSockets works with nats adapter', done => { Utils.newServer({}, (server1: Server) => { Utils.newClonedServer(server1, { port: 6002 }, (server2: Server) => { let client1 = Utils.newClient(); let channelName = Utils.randomChannelName(); client1.connection.bind('connected', () => { server1.adapter.getChannelSockets('app-id', channelName).then(sockets => { expect(sockets.size).toBe(0); let channel1 = client1.subscribe(channelName); channel1.bind('pusher:subscription_succeeded', () => { Utils.wait(3000).then(() => { server1.adapter.getChannelSockets('app-id', channelName).then(sockets => { expect(sockets.size).toBe(1); let client2 = Utils.newClient({}, 6002); client2.connection.bind('connected', () => { let channel2 = client2.subscribe(channelName); channel2.bind('pusher:subscription_succeeded', () => { Utils.wait(3000).then(() => { server1.adapter.getChannelSockets('app-id', channelName).then(sockets => { expect(sockets.size).toBe(2); client2.unsubscribe(channelName); Utils.wait(3000).then(() => { server1.adapter.getChannelSockets('app-id', channelName).then(sockets => { expect(sockets.size).toBe(1); client1.disconnect(); client2.disconnect(); done(); }); }); }); }); }); }); }); }); }); }); }); }); }); }); }); ================================================ FILE: tests/ws.redis-adapter.test.ts ================================================ import { Server } from './../src/server'; import { Utils } from './utils'; jest.retryTimes(parseInt(process.env.RETRY_TIMES || '1')); describe('ws test for redis adapter', () => { beforeEach(() => { jest.resetModules(); return Utils.waitForPortsToFreeUp(); }); afterEach(() => { return Utils.flushServers(); }); Utils.shouldRun(Utils.adapterIs('redis') && Utils.appManagerIs('array'))('client events with redis adapter', done => { Utils.newServer({ 'appManager.array.apps.0.enableClientMessages': true }, (server1: Server) => { Utils.newClonedServer(server1, { 'appManager.array.apps.0.enableClientMessages': true, port: 6002 }, (server2: Server) => { let client1 = Utils.newClientForPrivateChannel(); let client2; let channelName = `private-${Utils.randomChannelName()}`; client1.connection.bind('connected', () => { client1.connection.bind('message', ({ event, channel, data }) => { if (event === 'client-greeting' && channel === channelName) { expect(data.message).toBe('hello'); client1.disconnect(); client2.disconnect(); done(); } }); let channel = client1.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { client2 = Utils.newClientForPrivateChannel({}, 6002); client2.connection.bind('connected', () => { let channel = client2.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { channel.trigger('client-greeting', { message: 'hello', }); }); }); }); }); }); }); }); Utils.shouldRun(Utils.adapterIs('redis') && Utils.appManagerIs('array'))('client events dont get emitted when client messaging is disabled with redis adapter', done => { Utils.newServer({ 'appManager.array.apps.0.enableClientMessages': false }, (server1: Server) => { Utils.newClonedServer(server1, { 'appManager.array.apps.0.enableClientMessages': false, port: 6002 }, (server2: Server) => { let client1 = Utils.newClientForPrivateChannel(); let channelName = `private-${Utils.randomChannelName()}`; client1.connection.bind('connected', () => { client1.connection.bind('message', ({ event, channel, data }) => { if (event === 'client-greeting' && channel === channelName) { throw new Error('The message was actually sent.'); } }); let channel = client1.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { let client2 = Utils.newClientForPrivateChannel({}, 6002); client2.connection.bind('connected', () => { let channel = client2.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { channel.bind('pusher:error', (error) => { expect(error.code).toBe(4301); client1.disconnect(); client2.disconnect(); done(); }); channel.trigger('client-greeting', { message: 'hello', }); }); }); }); }); }); }); }); Utils.shouldRun(Utils.adapterIs('redis') && Utils.appManagerIs('array'))('client events dont get emitted when event name is big with redis adapter', done => { Utils.newServer({ 'appManager.array.apps.0.enableClientMessages': true, 'eventLimits.maxNameLength': 25 }, (server1: Server) => { Utils.newClonedServer(server1, { 'appManager.array.apps.0.enableClientMessages': true, 'eventLimits.maxNameLength': 25, port: 6002 }, (server2: Server) => { let client1 = Utils.newClientForPrivateChannel(); let channelName = `private-${Utils.randomChannelName()}`; let eventName = 'client-a8hsuNFXUhfStiWE02R'; // 26 characters client1.connection.bind('connected', () => { client1.connection.bind('message', ({ event, channel, data }) => { if (event === eventName && channel === channelName) { throw new Error('The message was actually sent.'); } }); let channel = client1.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { let client2 = Utils.newClientForPrivateChannel({}, 6002); client2.connection.bind('connected', () => { let channel = client2.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { channel.bind('pusher:error', (error) => { expect(error.code).toBe(4301); client1.disconnect(); client2.disconnect(); done(); }); channel.trigger(eventName, { message: 'hello', }); }); }); }); }); }); }); }); Utils.shouldRun(Utils.adapterIs('redis') && Utils.appManagerIs('array'))('client events dont get emitted when event payload is big with redis adapter', done => { Utils.newServer({ 'appManager.array.apps.0.enableClientMessages': true, 'eventLimits.maxPayloadInKb': 1/1024/1024 }, (server1: Server) => { Utils.newClonedServer(server1, { 'appManager.array.apps.0.enableClientMessages': true, 'eventLimits.maxPayloadInKb': 1/1024/1024, port: 6002 }, (server2: Server) => { let client1 = Utils.newClientForPrivateChannel(); let channelName = `private-${Utils.randomChannelName()}`; client1.connection.bind('connected', () => { client1.connection.bind('message', ({ event, channel, data }) => { if (event === 'client-greeting' && channel === channelName) { throw new Error('The message was actually sent.'); } }); let channel = client1.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { let client2 = Utils.newClientForPrivateChannel({}, 6002); client2.connection.bind('connected', () => { let channel = client2.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { channel.bind('pusher:error', (error) => { expect(error.code).toBe(4301); client1.disconnect(); client2.disconnect(); done(); }); channel.trigger('client-greeting', { message: 'hello', }); }); }); }); }); }); }); }); Utils.shouldRun(Utils.adapterIs('redis') && Utils.appManagerIs('array'))('throw over quota error if reached connection limit for redis adapter', done => { Utils.newServer({ 'appManager.array.apps.0.maxConnections': 1, port: 6001 }, (server1: Server) => { Utils.newClonedServer(server1, { 'appManager.array.apps.0.maxConnections': 1, port: 6002 }, (server2: Server) => { let client1 = Utils.newClient({}, 6001, 'app-key', false); client1.connection.bind('connected', () => { let client2 = Utils.newClient({}, 6002, 'app-key', false); client2.connection.bind('state_change', ({ current }) => { if (current === 'failed') { client1.disconnect(); done(); } else { throw new Error(`${current} is not an expected state.`); } }); }); }); }); }); Utils.shouldRun(Utils.adapterIs('redis'))('should check for presence.maxMembersPerChannel for redis adapter', done => { Utils.newServer({ 'presence.maxMembersPerChannel': 1, port: 6001 }, (server1: Server) => { Utils.newClonedServer(server1, { 'presence.maxMembersPerChannel': 1, port: 6002 }, (server2: Server) => { let user1 = { user_id: 1, user_info: { id: 1, name: 'John', }, }; let user2 = { user_id: 2, user_info: { id: 2, name: 'Alice', }, }; let client1 = Utils.newClientForPresenceUser(user1); let client2 = Utils.newClientForPresenceUser(user2, {}, 6002); let channelName = `presence-${Utils.randomChannelName()}`; client1.connection.bind('connected', () => { let channel1 = client1.subscribe(channelName); channel1.bind('pusher:subscription_succeeded', () => { client2.connection.bind('message', ({ event, channel, data }) => { if (event === 'pusher:subscription_error' && channel === channelName) { expect(data.type).toBe('LimitReached'); expect(data.status).toBe(4100); expect(data.error).toBeDefined(); client1.disconnect(); client2.disconnect(); done(); } }); client2.subscribe(channelName); }); }); }); }); }); Utils.shouldRun(Utils.adapterIs('redis'))('adapter getSockets works with redis adapter', done => { Utils.newServer({}, (server1: Server) => { Utils.newClonedServer(server1, { port: 6002 }, (server2: Server) => { let client1 = Utils.newClient(); client1.connection.bind('connected', () => { server1.adapter.getSockets('app-id').then(sockets => { expect(sockets.size).toBe(1); let client2 = Utils.newClient({}, 6002); client2.connection.bind('connected', () => { server1.adapter.getSockets('app-id').then(sockets => { expect(sockets.size).toBe(2); client1.disconnect(); client2.disconnect(); done(); }); }); }) }); }); }); }); Utils.shouldRun(Utils.adapterIs('redis'))('adapter getChannelSockets works with redis adapter', done => { Utils.newServer({}, (server1: Server) => { Utils.newClonedServer(server1, { port: 6002 }, (server2: Server) => { let client1 = Utils.newClient(); let channelName = Utils.randomChannelName(); client1.connection.bind('connected', () => { server1.adapter.getChannelSockets('app-id', channelName).then(sockets => { expect(sockets.size).toBe(0); let channel1 = client1.subscribe(channelName); channel1.bind('pusher:subscription_succeeded', () => { server1.adapter.getChannelSockets('app-id', channelName).then(sockets => { expect(sockets.size).toBe(1); let client2 = Utils.newClient({}, 6002); client2.connection.bind('connected', () => { let channel2 = client2.subscribe(channelName); channel2.bind('pusher:subscription_succeeded', () => { server1.adapter.getChannelSockets('app-id', channelName).then(sockets => { expect(sockets.size).toBe(2); client2.unsubscribe(channelName); Utils.wait(3000).then(() => { server1.adapter.getChannelSockets('app-id', channelName).then(sockets => { expect(sockets.size).toBe(1); client1.disconnect(); client2.disconnect(); done(); }); }); }); }); }); }); }); }); }); }); }); }); }); ================================================ FILE: tests/ws.test.ts ================================================ import { Server } from './../src/server'; import { Utils } from './utils'; jest.retryTimes(parseInt(process.env.RETRY_TIMES || '1')); describe('ws test', () => { beforeEach(() => { jest.resetModules(); return Utils.waitForPortsToFreeUp(); }); afterEach(() => { return Utils.flushServers(); }); Utils.shouldRun(Utils.appManagerIs('array'))('client events', done => { Utils.newServer({ 'appManager.array.apps.0.enableClientMessages': true }, (server: Server) => { let client1 = Utils.newClientForPrivateChannel(); let client2; let channelName = `private-${Utils.randomChannelName()}`; client1.connection.bind('connected', () => { client1.connection.bind('message', ({ event, channel, data }) => { if (event === 'client-greeting' && channel === channelName) { expect(data.message).toBe('hello'); client1.disconnect(); client2.disconnect(); done(); } }); let channel = client1.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { client2 = Utils.newClientForPrivateChannel(); client2.connection.bind('connected', () => { let channel = client2.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { channel.trigger('client-greeting', { message: 'hello', }); }); }); }); }); }); }); Utils.shouldRun(Utils.appManagerIs('array') && !Utils.adapterIs('nats'))('client events for presence channels', done => { Utils.newServer({ 'appManager.array.apps.0.enableClientMessages': true }, (server: Server) => { let user1 = { user_id: 1, user_info: { id: 1, name: 'John', }, }; let user2 = { user_id: 2, user_info: { id: 2, name: 'Alice', }, }; let client1 = Utils.newClientForPresenceUser(user1); let channelName = `presence-${Utils.randomChannelName()}`; client1.connection.bind('connected', () => { let client2 = Utils.newClientForPresenceUser(user2); let channel = client1.subscribe(channelName); channel.bind('client-greeting', (data, metadata) => { expect(data.message).toBe('hello'); expect(metadata.user_id).toBe(2); client1.disconnect(); client2.disconnect(); done(); }); channel.bind('pusher:subscription_succeeded', () => { client2.connection.bind('connected', () => { let channel = client2.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { channel.trigger('client-greeting', { message: 'hello' }); }); }); }); }); }); }, 60_000); Utils.shouldRun(Utils.appManagerIs('array'))('client events dont get emitted when client messaging is disabled', done => { Utils.newServer({ 'appManager.array.apps.0.enableClientMessages': false }, (server: Server) => { let client1 = Utils.newClientForPrivateChannel(); let channelName = `private-${Utils.randomChannelName()}`; client1.connection.bind('connected', () => { client1.connection.bind('message', ({ event, channel, data }) => { if (event === 'client-greeting' && channel === channelName) { throw new Error('The message was actually sent.'); } }); let channel = client1.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { let client2 = Utils.newClientForPrivateChannel(); client2.connection.bind('connected', () => { let channel = client2.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { channel.bind('pusher:error', (error) => { expect(error.code).toBe(4301); client1.disconnect(); client2.disconnect(); done(); }); channel.trigger('client-greeting', { message: 'hello', }); }); }); }); }); }); }); Utils.shouldRun(Utils.appManagerIs('array'))('client events dont get emitted when event name is big', done => { Utils.newServer({ 'appManager.array.apps.0.enableClientMessages': true, 'eventLimits.maxNameLength': 25 }, (server: Server) => { let client1 = Utils.newClientForPrivateChannel(); let channelName = `private-${Utils.randomChannelName()}`; let eventName = 'client-a8hsuNFXUhfStiWE02R'; // 26 characters client1.connection.bind('connected', () => { client1.connection.bind('message', ({ event, channel, data }) => { if (event === eventName && channel === channelName) { throw new Error('The message was actually sent.'); } }); let channel = client1.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { let client2 = Utils.newClientForPrivateChannel(); client2.connection.bind('connected', () => { let channel = client2.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { channel.bind('pusher:error', (error) => { expect(error.code).toBe(4301); client1.disconnect(); client2.disconnect(); done(); }); channel.trigger(eventName, { message: 'hello', }); }); }); }); }); }); }); Utils.shouldRun(Utils.appManagerIs('array'))('client events dont get emitted when event payload is big', done => { Utils.newServer({ 'appManager.array.apps.0.enableClientMessages': true, 'eventLimits.maxPayloadInKb': 1/1024/1024 }, (server: Server) => { let client1 = Utils.newClientForPrivateChannel(); let channelName = `private-${Utils.randomChannelName()}`; client1.connection.bind('connected', () => { client1.connection.bind('message', ({ event, channel, data }) => { if (event === 'client-greeting' && channel === channelName) { throw new Error('The message was actually sent.'); } }); let channel = client1.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { let client2 = Utils.newClientForPrivateChannel({}); client2.connection.bind('connected', () => { let channel = client2.subscribe(channelName); channel.bind('pusher:subscription_succeeded', () => { channel.bind('pusher:error', (error) => { expect(error.code).toBe(4301); client1.disconnect(); client2.disconnect(); done(); }); channel.trigger('client-greeting', { message: 'hello', }); }); }); }); }); }); }); test('cannot connect using invalid app key', done => { Utils.newServer({}, (server: Server) => { let client = Utils.newClient({}, 6001, 'invalid-key', false); client.connection.bind('state_change', ({ current }) => { if (['unavailable', 'failed', 'disconnected'].includes(current)) { done(); } else { throw new Error(`${current} is not an expected state.`); } }); }); }); Utils.shouldRun(Utils.appManagerIs('array'))('throw over quota error if reached connection limit', done => { Utils.newServer({ 'appManager.array.apps.0.maxConnections': 1 }, (server: Server) => { let client1 = Utils.newClient({}, 6001, 'app-key', false); client1.connection.bind('connected', () => { let client2 = Utils.newClient({}, 6001, 'app-key', false); client2.connection.bind('state_change', ({ current }) => { if (['unavailable', 'failed', 'disconnected'].includes(current)) { client1.disconnect(); done(); } else { throw new Error(`${current} is not an expected state.`); } }); }); }); }); Utils.shouldRun(Utils.appManagerIs('array'))('throw invalid app error if app is deactivated', done => { Utils.newServer({ 'appManager.array.apps.0.enabled': false }, (server: Server) => { let client = Utils.newClient(); client.connection.bind('state_change', ({ current }) => { if (['unavailable', 'failed', 'disconnected'].includes(current)) { done(); } else { throw new Error(`${current} is not an expected state.`); } }); }); }); test('should check for channelLimits.maxNameLength', done => { Utils.newServer({ 'channelLimits.maxNameLength': 25 }, (server: Server) => { let client = Utils.newClient(); client.connection.bind('connected', () => { let channelName = 'a8hsuNFXUhfS1zoyvtDtiWE02Ra'; // 26 characters client.subscribe(channelName); client.connection.bind('message', ({ event, channel, data }) => { if (event === 'pusher:subscription_error' && channel === channelName) { expect(data.type).toBe('LimitReached'); expect(data.status).toBe(4009); expect(data.error).toBeDefined(); client.disconnect(); done(); } }); }); }); }); test('should check for presence.maxMemberSizeInKb', done => { Utils.newServer({ 'presence.maxMemberSizeInKb': 1/1024/1024 }, (server: Server) => { let user = { user_id: 1, user_info: { id: 1, name: 'John', }, }; let client = Utils.newClientForPresenceUser(user); let channelName = `presence-${Utils.randomChannelName()}`; client.connection.bind('connected', () => { client.subscribe(channelName); client.connection.bind('message', ({ event, channel, data }) => { if (event === 'pusher:subscription_error' && channel === channelName) { expect(data.type).toBe('LimitReached'); expect(data.status).toBe(4301); expect(data.error).toBeDefined(); client.disconnect(); done(); } }); }); }); }); test('should check for presence.maxMembersPerChannel', done => { Utils.newServer({ 'presence.maxMembersPerChannel': 1 }, (server: Server) => { let user1 = { user_id: 1, user_info: { id: 1, name: 'John', }, }; let user2 = { user_id: 2, user_info: { id: 2, name: 'Alice', }, }; let client1 = Utils.newClientForPresenceUser(user1); let client2 = Utils.newClientForPresenceUser(user2); let channelName = `presence-${Utils.randomChannelName()}`; client1.connection.bind('connected', () => { let channel1 = client1.subscribe(channelName); channel1.bind('pusher:subscription_succeeded', () => { client2.connection.bind('message', ({ event, channel, data }) => { if (event === 'pusher:subscription_error' && channel === channelName) { expect(data.type).toBe('LimitReached'); expect(data.status).toBe(4100); expect(data.error).toBeDefined(); client1.disconnect(); client2.disconnect(); done(); } }); client2.subscribe(channelName); }); }); }); }); test('adapter getSockets works', done => { Utils.newServer({}, (server: Server) => { let client1 = Utils.newClient(); client1.connection.bind('connected', () => { server.adapter.getSockets('app-id').then(sockets => { expect(sockets.size).toBe(1); let client2 = Utils.newClient(); client2.connection.bind('connected', () => { server.adapter.getSockets('app-id').then(sockets => { expect(sockets.size).toBe(2); client1.disconnect(); client2.disconnect(); done(); }); }); }) }); }); }); test('adapter getChannelSockets works', done => { Utils.newServer({}, (server: Server) => { let client1 = Utils.newClient(); let channelName = Utils.randomChannelName(); client1.connection.bind('connected', () => { server.adapter.getChannelSockets('app-id', channelName).then(sockets => { expect(sockets.size).toBe(0); let client1 = Utils.newClient(); let channel1 = client1.subscribe(channelName); channel1.bind('pusher:subscription_succeeded', () => { server.adapter.getChannelSockets('app-id', channelName).then(sockets => { expect(sockets.size).toBe(1); let client2 = Utils.newClient(); client2.connection.bind('connected', () => { let channel2 = client2.subscribe(channelName); channel2.bind('pusher:subscription_succeeded', () => { server.adapter.getChannelSockets('app-id', channelName).then(sockets => { expect(sockets.size).toBe(2); client2.unsubscribe(channelName); Utils.wait(3000).then(() => { server.adapter.getChannelSockets('app-id', channelName).then(sockets => { expect(sockets.size).toBe(1); client1.disconnect(); client2.disconnect(); done(); }); }); }); }); }); }); }); }); }); }); }); Utils.shouldRun(Utils.appManagerIs('array'))('signin after connection', done => { Utils.newServer({ 'appManager.array.apps.0.enableUserAuthentication': true, 'userAuthenticationTimeout': 5_000 }, (server: Server) => { let client = Utils.newClientForPrivateChannel({}, 6001, 'app-key', { id: 1 }); client.connection.bind('connected', () => { client.connection.bind('message', ({ event }) => { if (event === 'pusher:signin_success') { // After subscription, wait 10 seconds to make sure it isn't disconnected setTimeout(() => { client.disconnect(); done(); }, 10_000); } }); client.signin(); }); }); }); Utils.shouldRun(Utils.appManagerIs('array'))('not calling signin after connection throws right error code', done => { Utils.newServer({ 'appManager.array.apps.0.enableUserAuthentication': true, 'userAuthenticationTimeout': 5_000 }, (server: Server) => { let client = Utils.newClientForPrivateChannel({}, 6001, 'app-key', { id: 1 }); client.connection.bind('connected', () => { client.connection.bind('message', (error) => { if (error.event === 'pusher:error') { expect(error.data.code).toBe(4009); client.disconnect(); done(); } }); }); }); }); Utils.shouldRun(Utils.appManagerIs('array'))('not having user id throws an error', done => { Utils.newServer({ 'appManager.array.apps.0.enableUserAuthentication': true, 'userAuthenticationTimeout': 5_000 }, (server: Server) => { let client = Utils.newClientForPrivateChannel({}, 6001, 'app-key', { name: 'John' }); client.connection.bind('connected', () => { client.connection.bind('message', (error) => { if (error.event === 'pusher:error') { expect(error.data.code).toBe(4009); client.disconnect(); done(); } }); }); }); }); Utils.shouldRun(Utils.appManagerIs('array'))('sending wrong user data token throws error', done => { Utils.newServer({ 'appManager.array.apps.0.enableUserAuthentication': true, 'userAuthenticationTimeout': 5_000 }, (server: Server) => { let client = Utils.newClientForPrivateChannel({ userAuthentication: { customHandler: ({ socketId }, callback) => { callback(false, { auth: 'fail-on-purpose', user_data: JSON.stringify({ id: 1 }), }); }, }, }, 6001, 'app-key', { id: 1 }); client.connection.bind('connected', () => { client.connection.bind('message', (error) => { if (error.event === 'pusher:error') { expect(error.data.code).toBe(4009); client.disconnect(); done(); } }); }); }); }); }); ================================================ FILE: tsconfig.json ================================================ { "compilerOptions": { "allowSyntheticDefaultImports": true, "module": "commonjs", "moduleResolution": "node", "outDir": "./dist", "sourceMap": false, "target": "es2019", "noImplicitAny": false, "preserveConstEnums": true, "removeComments": true, "typeRoots": [ "node_modules/@types" ], "lib": [ "es2019", "dom" ], "types": [ "jest", "node" ] }, "include": [ "./typings/**/*.ts", "./src/**/*.ts" ], "exclude": [ "node_modules" ] }