Showing preview only (608K chars total). Download the full file or copy to clipboard to get everything.
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
---
<!---
NOTICE: Keep in mind that bugs that state simple usage disfunctionalities (i.e. message did not get sent) are more likely to be your fault for not using the Pusher properly.
After enabling debugging with SOKETI_DEBUG=1, make sure to read the console to see if the message is actually being sent to the server.
-->
**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 <open-source@soketi.app>"
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 <open-source@soketi.app>"
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 <open-source@soketi.app>"
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. <https://fsf.org/>
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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 <https://www.gnu.org/licenses/>.
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
<https://www.gnu.org/licenses/>.
================================================
FILE: README.md
================================================
# soketi
<img src="assets/logo.png" width="120" />

[](https://codecov.io/gh/soketi/soketi/branch/master)
[](https://www.npmjs.com/package/@soketi/soketi)
[](https://www.npmjs.com/package/@soketi/soketi)
[](https://www.npmjs.com/package/@soketi/soketi)
[](https://artifacthub.io/packages/search?repo=soketi)
[](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)**
<p align="center">
<a href="https://github.com/sponsors/rennokki">
<img src='https://cdn.jsdelivr.net/gh/rennokki/sponsorkit-assets@main/assets/sponsors.svg' alt="Logos from Sponsors" />
</a>
</p>
## 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.
[](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
<?php
require __DIR__ . '/vendor/autoload.php';
use Carbon\Carbon;
use Pusher\Pusher;
use React\EventLoop\Loop;
use Toolkit\PFlag\Flags;
use Toolkit\PFlag\FlagType;
$loop = Loop::get();
$flags = array_shift($argv);
$fs = Flags::new();
$fs->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<string, Namespace>;
/**
* The list of nodes in the current private network.
*/
driver?: AdapterInterface;
/**
* Initialize the adapter.
*/
init(): Promise<AdapterInterface>;
/**
* Get the app namespace.
*/
getNamespace(appId: string): Namespace;
/**
* Get all namespaces.
*/
getNamespaces(): Map<string, Namespace>;
/**
* Add a new socket to the namespace.
*/
addSocket(appId: string, ws: WebSocket): Promise<boolean>;
/**
* Remove a socket from the namespace.
*/
removeSocket(appId: string, wsId: string): Promise<boolean>;
/**
* 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<number>;
/**
* 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<number|void>;
/**
* 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<void>;
/**
* Clear the namespace from the local adapter.
*/
clearNamespace(namespaceId: string): Promise<void>;
/**
* Clear all namespaces from the local adapter.
*/
clearNamespaces(): Promise<void>;
/**
* Get all sockets from the namespace.
*/
getSockets(appId: string, onlyLocal?: boolean): Promise<Map<string, WebSocket>>;
/**
* Get total sockets count.
*/
getSocketsCount(appId: string, onlyLocal?: boolean): Promise<number>;
/**
* Get the list of channels with the websocket IDs.
*/
getChannels(appId: string, onlyLocal?: boolean): Promise<Map<string, Set<string>>>;
/**
* Get the list of channels with the websockets count.
*/
getChannelsWithSocketsCount(appId: string, onlyLocal?: boolean): Promise<Map<string, number>>;
/**
* Get all the channel sockets associated with a namespace.
*/
getChannelSockets(appId: string, channel: string, onlyLocal?: boolean): Promise<Map<string, WebSocket>>;
/**
* Get a given channel's total sockets count.
*/
getChannelSocketsCount(appId: string, channel: string, onlyLocal?: boolean): Promise<number>;
/**
* Get a given presence channel's members.
*/
getChannelMembers(appId: string, channel: string, onlyLocal?: boolean): Promise<Map<string, PresenceMemberInfo>>;
/**
* Get a given presence channel's members count
*/
getChannelMembersCount(appId: string, channel: string, onlyLocal?: boolean): Promise<number>;
/**
* Check if a given connection ID exists in a channel.
*/
isInChannel(appId: string, channel: string, wsId: string, onlyLocal?: boolean): Promise<boolean>;
/**
* Add to the users list the associated socket connection ID.
*/
addUser(ws: WebSocket): Promise<void>;
/**
* Remove the user associated with the connection ID.
*/
removeUser(ws: WebSocket): Promise<void>;
/**
* Get the sockets associated with an user.
*/
getUserSockets(appId: string, userId: string|number): Promise<Set<WebSocket>>;
}
================================================
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<AdapterInterface> {
return await this.driver.init();
}
/**
* Get the app namespace.
*/
getNamespace(appId: string): Namespace {
return this.driver.getNamespace(appId);
}
/**
* Get all namespaces.
*/
getNamespaces(): Map<string, Namespace> {
return this.driver.getNamespaces();
}
/**
* Add a new socket to the namespace.
*/
async addSocket(appId: string, ws: WebSocket): Promise<boolean> {
return this.driver.addSocket(appId, ws);
}
/**
* Remove a socket from the namespace.
*/
async removeSocket(appId: string, wsId: string): Promise<boolean> {
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<number> {
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<number|void> {
return this.driver.removeFromChannel(appId, channel, wsId);
}
/**
* Get all sockets from the namespace.
*/
async getSockets(appId: string, onlyLocal = false): Promise<Map<string, WebSocket>> {
return this.driver.getSockets(appId, onlyLocal);
}
/**
* Get total sockets count.
*/
async getSocketsCount(appId: string, onlyLocal?: boolean): Promise<number> {
return this.driver.getSocketsCount(appId, onlyLocal);
}
/**
* Get the list of channels with the websocket IDs.
*/
async getChannels(appId: string, onlyLocal = false): Promise<Map<string, Set<string>>> {
return this.driver.getChannels(appId, onlyLocal);
}
/**
* Get the list of channels with the websockets count.
*/
async getChannelsWithSocketsCount(appId: string, onlyLocal = false): Promise<Map<string, number>> {
return this.driver.getChannelsWithSocketsCount(appId, onlyLocal);
}
/**
* Get all the channel sockets associated with a namespace.
*/
async getChannelSockets(appId: string, channel: string, onlyLocal = false): Promise<Map<string, WebSocket>> {
return this.driver.getChannelSockets(appId, channel, onlyLocal);
}
/**
* Get a given channel's total sockets count.
*/
async getChannelSocketsCount(appId: string, channel: string, onlyLocal?: boolean): Promise<number> {
return this.driver.getChannelSocketsCount(appId, channel, onlyLocal);
}
/**
* Get a given presence channel's members.
*/
async getChannelMembers(appId: string, channel: string, onlyLocal = false): Promise<Map<string, PresenceMemberInfo>> {
return this.driver.getChannelMembers(appId, channel, onlyLocal);
}
/**
* Get a given presence channel's members count
*/
async getChannelMembersCount(appId: string, channel: string, onlyLocal?: boolean): Promise<number> {
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<boolean> {
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<void> {
return this.driver.addUser(ws);
}
/**
* Remove the user associated with the connection ID.
*/
removeUser(ws: WebSocket): Promise<void> {
return this.driver.removeUser(ws);
}
/**
* Get the sockets associated with an user.
*/
getUserSockets(appId: string, userId: string|number): Promise<Set<WebSocket>> {
return this.driver.getUserSockets(appId, userId);
}
/**
* Clear the namespace from the local adapter.
*/
clearNamespace(namespaceId: string): Promise<void> {
return this.driver.clearNamespace(namespaceId);
}
/**
* Clear all namespaces from the local adapter.
*/
clearNamespaces(): Promise<void> {
return this.driver.clearNamespaces();
}
/**
* Clear the connections.
*/
disconnect(): Promise<void> {
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<AdapterInterface> {
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<number> {
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<string, any>;
members?: Map<string, PresenceMemberInfo>;
channels?: Map<string, Set<string>>;
channelsWithSocketsCount?: Map<string, number>;
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<string, WebSocket>;
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<string, Request> = 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<number>;
/**
* 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<Map<string, WebSocket>> {
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<number> {
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<Map<string, Set<string>>> {
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<Map<string, number>> {
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<Map<string, WebSocket>> {
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<number> {
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<Map<string, PresenceMemberInfo>> {
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<number> {
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<boolean> {
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<string, Namespace> = new Map<string, Namespace>();
/**
* Initialize the adapter.
*/
constructor(protected server: Server) {
//
}
/**
* Initialize the adapter.
*/
async init(): Promise<AdapterInterface> {
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<string, Namespace> {
return this.namespaces;
}
/**
* Add a new socket to the namespace.
*/
async addSocket(appId: string, ws: WebSocket): Promise<boolean> {
return this.getNamespace(appId).addSocket(ws);
}
/**
* Remove a socket from the namespace.
*/
async removeSocket(appId: string, wsId: string): Promise<boolean> {
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<number> {
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<number|void> {
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<Map<string, WebSocket>> {
return this.getNamespace(appId).getSockets();
}
/**
* Get total sockets count.
*/
async getSocketsCount(appId: string, onlyLocal?: boolean): Promise<number> {
return this.getNamespace(appId).getSockets().then(sockets => {
return sockets.size;
});
}
/**
* Get all sockets from the namespace.
*/
async getChannels(appId: string, onlyLocal = false): Promise<Map<string, Set<string>>> {
return this.getNamespace(appId).getChannels();
}
/**
* Get channels with total sockets count.
*/
async getChannelsWithSocketsCount(appId: string, onlyLocal?: boolean): Promise<Map<string, number>> {
return this.getNamespace(appId).getChannelsWithSocketsCount();
}
/**
* Get all the channel sockets associated with a namespace.
*/
async getChannelSockets(appId: string, channel: string, onlyLocal = false): Promise<Map<string, WebSocket>> {
return this.getNamespace(appId).getChannelSockets(channel);
}
/**
* Get a given channel's total sockets count.
*/
async getChannelSocketsCount(appId: string, channel: string, onlyLocal?: boolean): Promise<number> {
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<Map<string, PresenceMemberInfo>> {
return this.getNamespace(appId).getChannelMembers(channel);
}
/**
* Get a given presence channel's members count
*/
async getChannelMembersCount(appId: string, channel: string, onlyLocal?: boolean): Promise<number> {
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<boolean> {
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<void> {
return this.getNamespace(ws.app.id).addUser(ws);
}
/**
* Remove the user associated with the connection ID.
*/
removeUser(ws: WebSocket): Promise<void> {
return this.getNamespace(ws.app.id).removeUser(ws);
}
/**
* Get the sockets associated with an user.
*/
getUserSockets(appId: string, userId: number|string): Promise<Set<WebSocket>> {
return this.getNamespace(appId).getUserSockets(userId);
}
/**
* Clear the connections.
*/
disconnect(): Promise<void> {
return Promise.resolve();
}
/**
* Clear the namespace from the local adapter.
*/
clearNamespace(namespaceId: string): Promise<void> {
this.namespaces.set(namespaceId, new Namespace(namespaceId));
return Promise.resolve();
}
/**
* Clear all namespaces from the local adapter.
*/
clearNamespaces(): Promise<void> {
this.namespaces = new Map<string, Namespace>();
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<AdapterInterface> {
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<number> {
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<void> {
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<AdapterInterface> {
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<number> {
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<void> {
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<App|null>;
/**
* Find an app by given key.
*/
findByKey(key: string): Promise<App|null>;
/**
* Get the app secret by ID.
*/
getAppSecret(id: string): Promise<string|null>;
}
================================================
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<App|null> {
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<App|null> {
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<string|null> {
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<App|null> {
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<App|null> {
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<App|null> {
return Promise.resolve(null);
}
/**
* Find an app by given key.
*/
findByKey(key: string): Promise<App|null> {
return Promise.resolve(null);
}
/**
* Get the app secret by ID.
*/
getAppSecret(id: string): Promise<string|null> {
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<App|null> {
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<App|null> {
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<App|null> {
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<App|null> {
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<App[]> {
return this.connection<App>(this.appsTableName())
.where('id', id)
.select('*');
}
/**
* Make a Knex selection for the app key.
*/
protected selectByKey(key: string): Promise<App[]> {
return this.connection<App>(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<boolean>;
/**
* Check if the given key exists in cache.
* Returns false-returning value if cache does not exist.
*/
get(key: string): Promise<any>;
/**
* Set or overwrite the value in the cache.
*/
set(key: string, value: any, ttlSeconds: number): Promise<any>;
/**
* Disconnect the manager's made connections.
*/
disconnect(): Promise<void>;
}
================================================
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<boolean> {
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<any> {
return this.driver.get(key);
}
/**
* Set or overwrite the value in the cache.
*/
set(key: string, value: any, ttlSeconds: number): Promise<any> {
return this.driver.set(key, value, ttlSeconds);
}
/**
* Disconnect the manager's made connections.
*/
disconnect(): Promise<void> {
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<boolean> {
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<any> {
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<any> {
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<void> {
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<boolean> {
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<any> {
return this.redisConnection.get(key);
}
/**
* Set or overwrite the value in the cache.
*/
set(key: string, value: any, ttlSeconds = -1): Promise<any> {
return ttlSeconds > 0
? this.redisConnection.set(key, value, 'EX', ttlSeconds)
: this.redisConnection.set(key, value);
}
/**
* Disconnect the manager's made connections.
*/
disconnect(): Promise<void> {
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<JoinResponse> {
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);
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
SYMBOL INDEX (470 symbols across 53 files)
FILE: src/adapters/adapter-interface.ts
type AdapterInterface (line 7) | interface AdapterInterface {
FILE: src/adapters/adapter.ts
class Adapter (line 12) | class Adapter implements AdapterInterface {
method constructor (line 21) | constructor(server: Server) {
method init (line 38) | async init(): Promise<AdapterInterface> {
method getNamespace (line 45) | getNamespace(appId: string): Namespace {
method getNamespaces (line 52) | getNamespaces(): Map<string, Namespace> {
method addSocket (line 59) | async addSocket(appId: string, ws: WebSocket): Promise<boolean> {
method removeSocket (line 66) | async removeSocket(appId: string, wsId: string): Promise<boolean> {
method addToChannel (line 74) | async addToChannel(appId: string, channel: string, ws: WebSocket): Pro...
method removeFromChannel (line 82) | async removeFromChannel(appId: string, channel: string|string[], wsId:...
method getSockets (line 89) | async getSockets(appId: string, onlyLocal = false): Promise<Map<string...
method getSocketsCount (line 96) | async getSocketsCount(appId: string, onlyLocal?: boolean): Promise<num...
method getChannels (line 103) | async getChannels(appId: string, onlyLocal = false): Promise<Map<strin...
method getChannelsWithSocketsCount (line 110) | async getChannelsWithSocketsCount(appId: string, onlyLocal = false): P...
method getChannelSockets (line 117) | async getChannelSockets(appId: string, channel: string, onlyLocal = fa...
method getChannelSocketsCount (line 124) | async getChannelSocketsCount(appId: string, channel: string, onlyLocal...
method getChannelMembers (line 131) | async getChannelMembers(appId: string, channel: string, onlyLocal = fa...
method getChannelMembersCount (line 138) | async getChannelMembersCount(appId: string, channel: string, onlyLocal...
method isInChannel (line 145) | async isInChannel(appId: string, channel: string, wsId: string, onlyLo...
method send (line 152) | send(appId: string, channel: string, data: string, exceptingId: string...
method terminateUserConnections (line 159) | terminateUserConnections(appId: string, userId: number|string): void {
method addUser (line 166) | addUser(ws: WebSocket): Promise<void> {
method removeUser (line 173) | removeUser(ws: WebSocket): Promise<void> {
method getUserSockets (line 180) | getUserSockets(appId: string, userId: string|number): Promise<Set<WebS...
method clearNamespace (line 187) | clearNamespace(namespaceId: string): Promise<void> {
method clearNamespaces (line 194) | clearNamespaces(): Promise<void> {
method disconnect (line 201) | disconnect(): Promise<void> {
FILE: src/adapters/cluster-adapter.ts
class ClusterAdapter (line 5) | class ClusterAdapter extends HorizontalAdapter {
method constructor (line 14) | constructor(server: Server) {
method init (line 26) | async init(): Promise<AdapterInterface> {
method onRequest (line 37) | protected onRequest(msg: any): void {
method onResponse (line 48) | protected onResponse(msg: any): void {
method onMessage (line 60) | protected onMessage(msg: any): void {
method broadcastToChannel (line 79) | protected broadcastToChannel(channel: string, data: string): void {
method getNumSub (line 86) | protected getNumSub(): Promise<number> {
FILE: src/adapters/horizontal-adapter.ts
type RequestType (line 15) | enum RequestType {
type RequestExtra (line 28) | interface RequestExtra {
type Request (line 38) | interface Request extends RequestExtra {
type RequestOptions (line 48) | interface RequestOptions {
type RequestBody (line 52) | interface RequestBody extends RequestOptions {
type Response (line 58) | interface Response {
type PubsubBroadcastedMessage (line 68) | interface PubsubBroadcastedMessage {
method sendToResponseChannel (line 241) | protected sendToResponseChannel(data: string): void {
method sendToRequestChannel (line 248) | protected sendToRequestChannel(data: string): void {
method send (line 255) | send(appId: string, channel: string, data: string, exceptingId: string|n...
method sendLocally (line 270) | sendLocally(appId: string, channel: string, data: string, exceptingId: s...
method terminateUserConnections (line 277) | terminateUserConnections(appId: string, userId: number|string): void {
method terminateLocalUserConnections (line 303) | terminateLocalUserConnections(appId: string, userId: number|string): void {
method getSockets (line 310) | async getSockets(appId: string, onlyLocal = false): Promise<Map<string, ...
method getSocketsCount (line 337) | async getSocketsCount(appId: string, onlyLocal?: boolean): Promise<numbe...
method getChannels (line 364) | async getChannels(appId: string, onlyLocal = false): Promise<Map<string,...
method getChannelsWithSocketsCount (line 391) | async getChannelsWithSocketsCount(appId: string, onlyLocal?: boolean): P...
method getChannelSockets (line 418) | async getChannelSockets(appId: string, channel: string, onlyLocal = fals...
method getChannelSocketsCount (line 446) | async getChannelSocketsCount(appId: string, channel: string, onlyLocal?:...
method getChannelMembers (line 474) | async getChannelMembers(appId: string, channel: string, onlyLocal = fals...
method getChannelMembersCount (line 502) | async getChannelMembersCount(appId: string, channel: string, onlyLocal?:...
method isInChannel (line 530) | async isInChannel(appId: string, channel: string, wsId: string, onlyLoca...
method onRequest (line 558) | protected onRequest(channel: string, msg: string): void {
method onResponse (line 676) | protected onResponse(channel: string, msg: string): void {
method sendRequest (line 709) | protected sendRequest(
method processRequestFromAnotherInstance (line 767) | protected processRequestFromAnotherInstance(request: RequestBody, callba...
method processReceivedResponse (line 792) | protected processReceivedResponse(
FILE: src/adapters/local-adapter.ts
class LocalAdapter (line 7) | class LocalAdapter implements AdapterInterface {
method constructor (line 19) | constructor(protected server: Server) {
method init (line 26) | async init(): Promise<AdapterInterface> {
method getNamespace (line 33) | getNamespace(appId: string): Namespace {
method getNamespaces (line 44) | getNamespaces(): Map<string, Namespace> {
method addSocket (line 51) | async addSocket(appId: string, ws: WebSocket): Promise<boolean> {
method removeSocket (line 58) | async removeSocket(appId: string, wsId: string): Promise<boolean> {
method addToChannel (line 66) | async addToChannel(appId: string, channel: string, ws: WebSocket): Pro...
method removeFromChannel (line 76) | async removeFromChannel(appId: string, channel: string|string[], wsId:...
method getSockets (line 89) | async getSockets(appId: string, onlyLocal = false): Promise<Map<string...
method getSocketsCount (line 96) | async getSocketsCount(appId: string, onlyLocal?: boolean): Promise<num...
method getChannels (line 105) | async getChannels(appId: string, onlyLocal = false): Promise<Map<strin...
method getChannelsWithSocketsCount (line 112) | async getChannelsWithSocketsCount(appId: string, onlyLocal?: boolean):...
method getChannelSockets (line 119) | async getChannelSockets(appId: string, channel: string, onlyLocal = fa...
method getChannelSocketsCount (line 126) | async getChannelSocketsCount(appId: string, channel: string, onlyLocal...
method getChannelMembers (line 135) | async getChannelMembers(appId: string, channel: string, onlyLocal = fa...
method getChannelMembersCount (line 142) | async getChannelMembersCount(appId: string, channel: string, onlyLocal...
method isInChannel (line 151) | async isInChannel(appId: string, channel: string, wsId: string, onlyLo...
method send (line 158) | send(appId: string, channel: string, data: string, exceptingId: string...
method terminateUserConnections (line 191) | terminateUserConnections(appId: string, userId: number|string): void {
method addUser (line 198) | addUser(ws: WebSocket): Promise<void> {
method removeUser (line 205) | removeUser(ws: WebSocket): Promise<void> {
method getUserSockets (line 212) | getUserSockets(appId: string, userId: number|string): Promise<Set<WebS...
method disconnect (line 219) | disconnect(): Promise<void> {
method clearNamespace (line 226) | clearNamespace(namespaceId: string): Promise<void> {
method clearNamespaces (line 235) | clearNamespaces(): Promise<void> {
FILE: src/adapters/nats-adapter.ts
class NatsAdapter (line 7) | class NatsAdapter extends HorizontalAdapter {
method constructor (line 31) | constructor(server: Server) {
method init (line 50) | async init(): Promise<AdapterInterface> {
method onRequest (line 75) | protected onRequest(msg: any): void {
method onResponse (line 82) | protected onResponse(msg: any): void {
method onMessage (line 90) | protected onMessage(msg: any): void {
method broadcastToChannel (line 105) | protected broadcastToChannel(channel: string, data: string): void {
method getNumSub (line 112) | protected async getNumSub(): Promise<number> {
method disconnect (line 144) | disconnect(): Promise<void> {
FILE: src/adapters/redis-adapter.ts
class RedisAdapter (line 7) | class RedisAdapter extends HorizontalAdapter {
method constructor (line 26) | constructor(server: Server) {
method init (line 42) | async init(): Promise<AdapterInterface> {
method broadcastToChannel (line 79) | protected broadcastToChannel(channel: string, data: string): void {
method processMessage (line 86) | protected processMessage(redisChannel: string, msg: Buffer|string): vo...
method onMessage (line 101) | protected onMessage(pattern: string, redisChannel: string, msg: Buffer...
method getNumSub (line 129) | protected getNumSub(): Promise<number> {
method disconnect (line 175) | disconnect(): Promise<void> {
FILE: src/app-managers/app-manager-interface.ts
type AppManagerInterface (line 3) | interface AppManagerInterface {
FILE: src/app-managers/app-manager.ts
class AppManager (line 13) | class AppManager implements AppManagerInterface {
method constructor (line 22) | constructor(protected server: Server) {
method findById (line 39) | findById(id: string): Promise<App|null> {
method findByKey (line 60) | findByKey(key: string): Promise<App|null> {
method getAppSecret (line 81) | getAppSecret(id: string): Promise<string|null> {
FILE: src/app-managers/array-app-manager.ts
class ArrayAppManager (line 6) | class ArrayAppManager extends BaseAppManager {
method constructor (line 10) | constructor(protected server: Server) {
method findById (line 17) | findById(id: string): Promise<App|null> {
method findByKey (line 36) | findByKey(key: string): Promise<App|null> {
FILE: src/app-managers/base-app-manager.ts
class BaseAppManager (line 4) | class BaseAppManager implements AppManagerInterface {
method findById (line 8) | findById(id: string): Promise<App|null> {
method findByKey (line 15) | findByKey(key: string): Promise<App|null> {
method getAppSecret (line 22) | getAppSecret(id: string): Promise<string|null> {
FILE: src/app-managers/dynamodb-app-manager.ts
class DynamoDbAppManager (line 9) | class DynamoDbAppManager extends BaseAppManager {
method constructor (line 18) | constructor(protected server: Server) {
method findById (line 31) | findById(id: string): Promise<App|null> {
method findByKey (line 62) | findByKey(key: string): Promise<App|null> {
method unmarshallItem (line 97) | protected unmarshallItem(item: AttributeMap): { [key: string]: any; } {
FILE: src/app-managers/mysql-app-manager.ts
class MysqlAppManager (line 3) | class MysqlAppManager extends SqlAppManager {
method knexClientName (line 7) | protected knexClientName(): string {
method knexConnectionDetails (line 16) | protected knexConnectionDetails(): { [key: string]: any; } {
method knexVersion (line 26) | protected knexVersion(): string {
method supportsPooling (line 34) | protected supportsPooling(): boolean {
method appsTableName (line 41) | protected appsTableName(): string {
FILE: src/app-managers/postgres-app-manager.ts
class PostgresAppManager (line 3) | class PostgresAppManager extends SqlAppManager {
method knexClientName (line 7) | protected knexClientName(): string {
method knexConnectionDetails (line 14) | protected knexConnectionDetails(): { [key: string]: any; } {
method knexVersion (line 24) | protected knexVersion(): string {
method supportsPooling (line 32) | protected supportsPooling(): boolean {
method appsTableName (line 39) | protected appsTableName(): string {
FILE: src/app-managers/sql-app-manager.ts
method constructor (line 18) | constructor(protected server: Server) {
method findById (line 45) | findById(id: string): Promise<App|null> {
method findByKey (line 62) | findByKey(key: string): Promise<App|null> {
method selectById (line 79) | protected selectById(id: string): Promise<App[]> {
method selectByKey (line 88) | protected selectByKey(key: string): Promise<App[]> {
FILE: src/app.ts
type AppInterface (line 8) | interface AppInterface {
type WebhookInterface (line 34) | interface WebhookInterface {
class App (line 52) | class App implements AppInterface {
method constructor (line 183) | constructor(public initialApp: { [key: string]: any; }, protected serv...
method toObject (line 214) | toObject(): AppInterface {
method toJson (line 240) | toJson(): string {
method forWebSocket (line 248) | forWebSocket(): App {
method signingTokenFromRequest (line 262) | signingTokenFromRequest(res: HttpResponse): string {
method signingToken (line 290) | protected signingToken(method: string, path: string, params: string): ...
method extractFromPassedKeys (line 304) | protected extractFromPassedKeys(app: { [key: string]: any; }, paramete...
method transformPotentialJsonToArray (line 320) | protected transformPotentialJsonToArray(potentialJson: any): any {
FILE: src/cache-managers/cache-manager-interface.ts
type CacheManagerInterface (line 3) | interface CacheManagerInterface {
FILE: src/cache-managers/cache-manager.ts
class CacheManager (line 7) | class CacheManager implements CacheManagerInterface {
method constructor (line 16) | constructor(protected server: Server) {
method has (line 29) | has(key: string): Promise<boolean> {
method get (line 37) | get(key: string): Promise<any> {
method set (line 44) | set(key: string, value: any, ttlSeconds: number): Promise<any> {
method disconnect (line 51) | disconnect(): Promise<void> {
FILE: src/cache-managers/memory-cache-manager.ts
type Memory (line 4) | interface Memory {
class MemoryCacheManager (line 12) | class MemoryCacheManager implements CacheManagerInterface {
method constructor (line 23) | constructor(protected server: Server) {
method has (line 38) | has(key: string): Promise<boolean> {
method get (line 46) | get(key: string): Promise<any> {
method set (line 53) | set(key: string, value: any, ttlSeconds = -1): Promise<any> {
method disconnect (line 66) | disconnect(): Promise<void> {
FILE: src/cache-managers/redis-cache-manager.ts
class RedisCacheManager (line 5) | class RedisCacheManager implements CacheManagerInterface {
method constructor (line 14) | constructor(protected server: Server) {
method has (line 31) | has(key: string): Promise<boolean> {
method get (line 41) | get(key: string): Promise<any> {
method set (line 48) | set(key: string, value: any, ttlSeconds = -1): Promise<any> {
method disconnect (line 57) | disconnect(): Promise<void> {
FILE: src/channels/encrypted-private-channel-manager.ts
class EncryptedPrivateChannelManager (line 3) | class EncryptedPrivateChannelManager extends PrivateChannelManager {
FILE: src/channels/presence-channel-manager.ts
type PresenceMemberInfo (line 8) | interface PresenceMemberInfo {
type PresenceMember (line 12) | interface PresenceMember {
class PresenceChannelManager (line 18) | class PresenceChannelManager extends PrivateChannelManager {
method join (line 22) | join(ws: WebSocket, channel: string, message?: PusherMessage): Promise...
method leave (line 76) | leave(ws: WebSocket, channel: string): Promise<LeaveResponse> {
method getDataToSignForSignature (line 90) | protected getDataToSignForSignature(socketId: string, message: PusherM...
FILE: src/channels/private-channel-manager.ts
class PrivateChannelManager (line 8) | class PrivateChannelManager extends PublicChannelManager {
method join (line 12) | join(ws: WebSocket, channel: string, message?: PusherMessage): Promise...
method signatureIsValid (line 42) | protected signatureIsValid(app: App, socketId: string, message: Pusher...
method getExpectedSignature (line 51) | protected getExpectedSignature(app: App, socketId: string, message: Pu...
method getDataToSignForSignature (line 64) | protected getDataToSignForSignature(socketId: string, message: PusherM...
FILE: src/channels/public-channel-manager.ts
type JoinResponse (line 7) | interface JoinResponse {
type LeaveResponse (line 18) | interface LeaveResponse {
class PublicChannelManager (line 24) | class PublicChannelManager {
method constructor (line 25) | constructor(protected server: Server) {
method join (line 32) | join(ws: WebSocket, channel: string, message?: PusherMessage): Promise...
method leave (line 63) | leave(ws: WebSocket, channel: string): Promise<LeaveResponse> {
FILE: src/cli/cli.ts
class Cli (line 5) | class Cli {
method constructor (line 137) | constructor(protected pm2 = false) {
method overwriteOptionsFromEnv (line 145) | protected overwriteOptionsFromEnv(): void {
method overwriteOptionsFromConfig (line 178) | protected overwriteOptionsFromConfig(path?: string): void {
method start (line 202) | static async start(cliArgs: any): Promise<any> {
method startWithPm2 (line 209) | static async startWithPm2(cliArgs: any): Promise<any> {
method start (line 216) | async start(cliArgs: any): Promise<any> {
FILE: src/http-handler.ts
type ChannelResponse (line 11) | interface ChannelResponse {
type MessageCheckError (line 17) | interface MessageCheckError {
class HttpHandler (line 22) | class HttpHandler {
method constructor (line 26) | constructor(protected server: Server) {
method ready (line 30) | ready(res: HttpResponse) {
method acceptTraffic (line 43) | acceptTraffic(res: HttpResponse) {
method healthCheck (line 78) | healthCheck(res: HttpResponse) {
method usage (line 87) | usage(res: HttpResponse) {
method metrics (line 115) | metrics(res: HttpResponse) {
method channels (line 142) | channels(res: HttpResponse) {
method channel (line 184) | channel(res: HttpResponse) {
method channelUsers (line 238) | channelUsers(res: HttpResponse) {
method events (line 266) | events(res: HttpResponse) {
method batchEvents (line 289) | batchEvents(res: HttpResponse) {
method terminateUserConnections (line 318) | terminateUserConnections(res: HttpResponse) {
method checkMessageToBroadcast (line 330) | protected checkMessageToBroadcast(message: PusherApiMessage, app: App)...
method broadcastMessage (line 377) | protected broadcastMessage(message: PusherApiMessage, appId: string): ...
method notFound (line 397) | notFound(res: HttpResponse) {
method badResponse (line 413) | protected badResponse(res: HttpResponse, error: string) {
method notFoundResponse (line 417) | protected notFoundResponse(res: HttpResponse, error: string) {
method unauthorizedResponse (line 421) | protected unauthorizedResponse(res: HttpResponse, error: string) {
method entityTooLargeResponse (line 425) | protected entityTooLargeResponse(res: HttpResponse, error: string) {
method tooManyRequestsResponse (line 429) | protected tooManyRequestsResponse(res: HttpResponse) {
method serverErrorResponse (line 433) | protected serverErrorResponse(res: HttpResponse, error: string) {
method jsonBodyMiddleware (line 437) | protected jsonBodyMiddleware(res: HttpResponse, next: CallableFunction...
method corkMiddleware (line 454) | protected corkMiddleware(res: HttpResponse, next: CallableFunction): a...
method corsMiddleware (line 458) | protected corsMiddleware(res: HttpResponse, next: CallableFunction): a...
method appMiddleware (line 466) | protected appMiddleware(res: HttpResponse, next: CallableFunction): any {
method authMiddleware (line 478) | protected authMiddleware(res: HttpResponse, next: CallableFunction): a...
method readRateLimitingMiddleware (line 488) | protected readRateLimitingMiddleware(res: HttpResponse, next: Callable...
method broadcastEventRateLimitingMiddleware (line 502) | protected broadcastEventRateLimitingMiddleware(res: HttpResponse, next...
method broadcastBatchEventsRateLimitingMiddleware (line 518) | protected broadcastBatchEventsRateLimitingMiddleware(res: HttpResponse...
method attachMiddleware (line 538) | protected attachMiddleware(res: HttpResponse, functions: any[]): Promi...
method readJson (line 571) | protected readJson(res: HttpResponse, cb: CallableFunction, err: any) {
method signatureIsValid (line 631) | protected signatureIsValid(res: HttpResponse): Promise<boolean> {
method sendJson (line 637) | protected sendJson(res: HttpResponse, data: any, status: RecognizedStr...
method send (line 648) | protected send(res: HttpResponse, data: RecognizedString, status: Reco...
method getSignedToken (line 660) | protected getSignedToken(res: HttpResponse): Promise<string> {
FILE: src/job.ts
class Job (line 3) | class Job {
method constructor (line 7) | constructor(public id: string = uuidv4(), public data: { [key: string]...
FILE: src/log.ts
class Log (line 3) | class Log {
method infoTitle (line 4) | static infoTitle(message: any): void {
method successTitle (line 8) | static successTitle(message: any): void {
method errorTitle (line 12) | static errorTitle(message: any): void {
method warningTitle (line 16) | static warningTitle(message: any): void {
method clusterTitle (line 20) | static clusterTitle(message: any): void {
method httpTitle (line 24) | static httpTitle(message: any): void {
method discoverTitle (line 28) | static discoverTitle(message: any): void {
method websocketTitle (line 32) | static websocketTitle(message: any): void {
method webhookSenderTitle (line 36) | static webhookSenderTitle(message: any): void {
method info (line 40) | static info(message: any): void {
method success (line 44) | static success(message: any): void {
method error (line 48) | static error(message: any): void {
method warning (line 52) | static warning(message: any): void {
method cluster (line 56) | static cluster(message: any): void {
method http (line 60) | static http(message: any): void {
method discover (line 64) | static discover(message: any): void {
method websocket (line 68) | static websocket(message: any): void {
method webhookSender (line 72) | static webhookSender(message: any): void {
method br (line 76) | static br(): void {
method prefixWithTime (line 80) | protected static prefixWithTime(message: any): any {
method log (line 88) | protected static log(message: any, ...styles: string[]): void {
FILE: src/message.ts
type MessageData (line 1) | interface MessageData {
type PusherMessage (line 8) | interface PusherMessage {
type PusherApiMessage (line 15) | interface PusherApiMessage {
type SentPusherMessage (line 23) | interface SentPusherMessage {
type uWebSocketMessage (line 29) | type uWebSocketMessage = ArrayBuffer|PusherMessage;
FILE: src/metrics/metrics-interface.ts
type MetricsInterface (line 4) | interface MetricsInterface {
FILE: src/metrics/metrics.ts
class Metrics (line 8) | class Metrics implements MetricsInterface {
method constructor (line 17) | constructor(protected server: Server) {
method markNewConnection (line 28) | markNewConnection(ws: WebSocket): void {
method markDisconnection (line 37) | markDisconnection(ws: WebSocket): void {
method markApiMessage (line 46) | markApiMessage(appId: string, incomingMessage: any, sentMessage: any):...
method markWsMessageSent (line 55) | markWsMessageSent(appId: string, sentMessage: any): void {
method markWsMessageReceived (line 64) | markWsMessageReceived(appId: string, message: any): void {
method trackHorizontalAdapterResolveTime (line 73) | trackHorizontalAdapterResolveTime(appId: string, time: number): void {
method trackHorizontalAdapterResolvedPromises (line 80) | trackHorizontalAdapterResolvedPromises(appId: string, resolved = true)...
method markHorizontalAdapterRequestSent (line 87) | markHorizontalAdapterRequestSent(appId: string): void {
method markHorizontalAdapterRequestReceived (line 94) | markHorizontalAdapterRequestReceived(appId: string): void {
method markHorizontalAdapterResponseReceived (line 101) | markHorizontalAdapterResponseReceived(appId: string): void {
method getMetricsAsPlaintext (line 108) | getMetricsAsPlaintext(): Promise<string> {
method getMetricsAsJson (line 119) | getMetricsAsJson(): Promise<prom.metric[]|void> {
method clear (line 130) | clear(): Promise<void> {
FILE: src/metrics/prometheus-metrics-driver.ts
type PrometheusMetrics (line 7) | interface PrometheusMetrics {
type InfraMetadata (line 26) | interface InfraMetadata {
type NamespaceTags (line 30) | interface NamespaceTags {
class PrometheusMetricsDriver (line 35) | class PrometheusMetricsDriver implements MetricsInterface {
method constructor (line 64) | constructor(protected server: Server) {
method markNewConnection (line 83) | markNewConnection(ws: WebSocket): void {
method markDisconnection (line 91) | markDisconnection(ws: WebSocket): void {
method markApiMessage (line 99) | markApiMessage(appId: string, incomingMessage: any, sentMessage: any):...
method markWsMessageSent (line 108) | markWsMessageSent(appId: string, sentMessage: any): void {
method markWsMessageReceived (line 116) | markWsMessageReceived(appId: string, message: any): void {
method trackHorizontalAdapterResolveTime (line 124) | trackHorizontalAdapterResolveTime(appId: string, time: number): void {
method trackHorizontalAdapterResolvedPromises (line 131) | trackHorizontalAdapterResolvedPromises(appId: string, resolved = true)...
method markHorizontalAdapterRequestSent (line 142) | markHorizontalAdapterRequestSent(appId: string): void {
method markHorizontalAdapterRequestReceived (line 149) | markHorizontalAdapterRequestReceived(appId: string): void {
method markHorizontalAdapterResponseReceived (line 156) | markHorizontalAdapterResponseReceived(appId: string): void {
method getMetricsAsPlaintext (line 163) | getMetricsAsPlaintext(): Promise<string> {
method getMetricsAsJson (line 170) | getMetricsAsJson(): Promise<prom.metric[]|void> {
method clear (line 177) | clear(): Promise<void> {
method getTags (line 184) | protected getTags(appId: string): NamespaceTags {
method registerMetrics (line 191) | protected registerMetrics(): void {
FILE: src/namespace.ts
class Namespace (line 4) | class Namespace {
method constructor (line 23) | constructor(protected appId: string) {
method getSockets (line 30) | getSockets(): Promise<Map<string, WebSocket>> {
method addSocket (line 37) | addSocket(ws: WebSocket): Promise<boolean> {
method removeSocket (line 47) | async removeSocket(wsId: string): Promise<boolean> {
method addToChannel (line 57) | addToChannel(ws: WebSocket, channel: string): Promise<number> {
method removeFromChannel (line 73) | async removeFromChannel(wsId: string, channel: string|string[]): Promi...
method isInChannel (line 100) | isInChannel(wsId: string, channel: string): Promise<boolean> {
method getChannels (line 113) | getChannels(): Promise<Map<string, Set<string>>> {
method getChannelsWithSocketsCount (line 120) | getChannelsWithSocketsCount(): Promise<Map<string, number>> {
method getChannelSockets (line 135) | getChannelSockets(channel: string): Promise<Map<string, WebSocket>> {
method getChannelMembers (line 158) | getChannelMembers(channel: string): Promise<Map<string, PresenceMember...
method terminateUserConnections (line 175) | terminateUserConnections(userId: number|string): void {
method addUser (line 200) | addUser(ws: WebSocket): Promise<void> {
method removeUser (line 219) | removeUser(ws: WebSocket): Promise<void> {
method getUserSockets (line 238) | getUserSockets(userId: string|number): Promise<Set<WebSocket>> {
FILE: src/node.ts
type Node (line 1) | interface Node {
FILE: src/options.ts
type Redis (line 6) | interface Redis {
type RedisSentinel (line 19) | interface RedisSentinel {
type ClusterNode (line 24) | interface ClusterNode {
type KnexConnection (line 29) | interface KnexConnection {
type Options (line 37) | interface Options {
FILE: src/queues/queue-interface.ts
type QueueInterface (line 3) | interface QueueInterface {
FILE: src/queues/queue.ts
class Queue (line 9) | class Queue implements QueueInterface {
method constructor (line 18) | constructor(protected server: Server) {
method addToQueue (line 33) | addToQueue(queueName: string, data?: JobData): Promise<void> {
method processQueue (line 40) | processQueue(queueName: string, callback: CallableFunction): Promise<v...
method disconnect (line 47) | disconnect(): Promise<void> {
FILE: src/queues/redis-queue-driver.ts
type QueueWithWorker (line 8) | interface QueueWithWorker {
class RedisQueueDriver (line 14) | class RedisQueueDriver implements QueueInterface {
method constructor (line 23) | constructor(protected server: Server) {
method addToQueue (line 30) | addToQueue(queueName: string, data: JobData): Promise<void> {
method processQueue (line 45) | processQueue(queueName: string, callback: CallableFunction): Promise<v...
method disconnect (line 98) | disconnect(): Promise<void> {
FILE: src/queues/sqs-queue-driver.ts
class SqsQueueDriver (line 12) | class SqsQueueDriver implements QueueInterface {
method constructor (line 21) | constructor(protected server: Server) {
method addToQueue (line 28) | addToQueue(queueName: string, data: JobData): Promise<void> {
method processQueue (line 58) | processQueue(queueName: string, callback: CallableFunction): Promise<v...
method disconnect (line 107) | disconnect(): Promise<void> {
method sqsClient (line 119) | protected sqsClient(): SQS {
FILE: src/queues/sync-queue-driver.ts
class SyncQueueDriver (line 7) | class SyncQueueDriver implements QueueInterface {
method constructor (line 16) | constructor(protected server: Server) {
method addToQueue (line 23) | addToQueue(queueName: string, data: JobData): Promise<void> {
method processQueue (line 40) | processQueue(queueName: string, callback: CallableFunction): Promise<v...
method disconnect (line 50) | disconnect(): Promise<void> {
FILE: src/rate-limiters/cluster-rate-limiter.ts
type ConsumptionMessage (line 10) | interface ConsumptionMessage {
class ClusterRateLimiter (line 17) | class ClusterRateLimiter extends LocalRateLimiter {
method constructor (line 21) | constructor(protected server: Server) {
method consume (line 62) | protected consume(app: App, eventKey: string, points: number, maxPoint...
method disconnect (line 77) | disconnect(): Promise<void> {
method sendRateLimiters (line 91) | protected sendRateLimiters(): void {
FILE: src/rate-limiters/local-rate-limiter.ts
class LocalRateLimiter (line 7) | class LocalRateLimiter implements RateLimiterInterface {
method constructor (line 18) | constructor(protected server: Server) {
method consumeBackendEventPoints (line 25) | consumeBackendEventPoints(points: number, app?: App, ws?: WebSocket): ...
method consumeFrontendEventPoints (line 37) | consumeFrontendEventPoints(points: number, app?: App, ws?: WebSocket):...
method consumeReadRequestsPoints (line 49) | consumeReadRequestsPoints(points: number, app?: App, ws?: WebSocket): ...
method createNewRateLimiter (line 61) | createNewRateLimiter(appId: string, maxPoints: number): RateLimiterAbs...
method disconnect (line 72) | disconnect(): Promise<void> {
method initializeRateLimiter (line 79) | protected initializeRateLimiter(appId: string, eventKey: string, maxPo...
method consume (line 97) | protected consume(app: App, eventKey: string, points: number, maxPoint...
FILE: src/rate-limiters/rate-limiter-interface.ts
type ConsumptionResponse (line 5) | interface ConsumptionResponse {
type RateLimiterInterface (line 15) | interface RateLimiterInterface {
FILE: src/rate-limiters/rate-limiter.ts
class RateLimiter (line 11) | class RateLimiter implements RateLimiterInterface {
method constructor (line 20) | constructor(server: Server) {
method consumeBackendEventPoints (line 35) | consumeBackendEventPoints(points: number, app?: App, ws?: WebSocket): ...
method consumeFrontendEventPoints (line 42) | consumeFrontendEventPoints(points: number, app?: App, ws?: WebSocket):...
method consumeReadRequestsPoints (line 49) | consumeReadRequestsPoints(points: number, app?: App, ws?: WebSocket): ...
method createNewRateLimiter (line 56) | createNewRateLimiter(appId: string, maxPoints: number): RateLimiterAbs...
method disconnect (line 63) | disconnect(): Promise<void> {
FILE: src/rate-limiters/redis-rate-limiter.ts
class RedisRateLimiter (line 6) | class RedisRateLimiter extends LocalRateLimiter {
method constructor (line 15) | constructor(protected server: Server) {
method initializeRateLimiter (line 34) | protected initializeRateLimiter(appId: string, eventKey: string, maxPo...
method disconnect (line 48) | disconnect(): Promise<void> {
FILE: src/server.ts
class Server (line 26) | class Server {
method constructor (line 326) | constructor(options = {}) {
method start (line 333) | static async start(options: any = {}, callback?: CallableFunction) {
method start (line 340) | async start(callback?: CallableFunction) {
method stop (line 412) | stop(): Promise<void> {
method setOptions (line 452) | setOptions(options: { [key: string]: any; }): void {
method initializeDrivers (line 468) | initializeDrivers(): Promise<any> {
method setAppManager (line 483) | setAppManager(instance: AppManagerInterface): void {
method setAdapter (line 490) | setAdapter(instance: AdapterInterface): Promise<void> {
method setMetricsManager (line 502) | setMetricsManager(instance: MetricsInterface): Promise<void> {
method setRateLimiter (line 512) | setRateLimiter(instance: RateLimiterInterface): Promise<void> {
method setQueueManager (line 522) | setQueueManager(instance: QueueInterface): Promise<void> {
method setCacheManager (line 532) | setCacheManager(instance: CacheManagerInterface): Promise<void> {
method setWebhookSender (line 542) | setWebhookSender(): Promise<void> {
method url (line 552) | protected url(path: string): string {
method clusterPrefix (line 559) | clusterPrefix(channel: string): string {
method configureDiscovery (line 570) | protected configureDiscovery(): Promise<void> {
method configureWebsockets (line 631) | protected configureWebsockets(server: TemplatedApp): Promise<Templated...
method configureHttp (line 652) | protected configureHttp(server: TemplatedApp): Promise<TemplatedApp> {
method configureMetricsServer (line 726) | protected configureMetricsServer(metricsServer: TemplatedApp): Promise...
method shouldConfigureSsl (line 750) | protected shouldConfigureSsl(): boolean {
method canProcessQueues (line 758) | public canProcessQueues(): boolean {
method canProcessRequests (line 766) | public canProcessRequests(): boolean {
FILE: src/utils.ts
class Utils (line 1) | class Utils {
method dataToBytes (line 37) | static dataToBytes(...data: any): number {
method dataToKilobytes (line 52) | static dataToKilobytes(...data: any): number {
method dataToMegabytes (line 59) | static dataToMegabytes(...data: any): number {
method isPrivateChannel (line 66) | static isPrivateChannel(channel: string): boolean {
method isPresenceChannel (line 83) | static isPresenceChannel(channel: string): boolean {
method isEncryptedPrivateChannel (line 90) | static isEncryptedPrivateChannel(channel: string): boolean {
method isCachingChannel (line 97) | static isCachingChannel(channel: string): boolean {
method isClientEvent (line 114) | static isClientEvent(event: string): boolean {
method restrictedChannelName (line 132) | static restrictedChannelName(name: string) {
FILE: src/webhook-sender.ts
type ClientEventData (line 10) | interface ClientEventData {
type JobData (line 22) | interface JobData {
function createWebhookHmac (line 35) | function createWebhookHmac(data: string, secret: string): string {
class WebhookSender (line 41) | class WebhookSender {
method constructor (line 55) | constructor(protected server: Server) {
method sendClientEvent (line 182) | public sendClientEvent(app: App, channel: string, event: string, data:...
method sendMemberAdded (line 208) | public sendMemberAdded(app: App, channel: string, userId: string): void {
method sendMemberRemoved (line 223) | public sendMemberRemoved(app: App, channel: string, userId: string): v...
method sendChannelVacated (line 238) | public sendChannelVacated(app: App, channel: string): void {
method sendChannelOccupied (line 252) | public sendChannelOccupied(app: App, channel: string): void {
method sendCacheMissed (line 266) | public sendCacheMissed(app: App, channel: string): void {
method send (line 280) | protected send(app: App, data: ClientEventData, queueName: string): vo...
method sendWebhook (line 291) | protected sendWebhook(app: App, data: ClientEventData|ClientEventData[...
method sendWebhookByBatching (line 320) | protected sendWebhookByBatching(app: App, data: ClientEventData, queue...
FILE: src/ws-handler.ts
class WsHandler (line 19) | class WsHandler {
method constructor (line 43) | constructor(protected server: Server) {
method onOpen (line 53) | onOpen(ws: WebSocket): any {
method onMessage (line 161) | onMessage(ws: WebSocket, message: uWebSocketMessage, isBinary: boolean...
method onClose (line 202) | onClose(ws: WebSocket, code: number, message: uWebSocketMessage): any {
method evictSocketFromMemory (line 217) | evictSocketFromMemory(ws: WebSocket): Promise<void> {
method closeAllLocalSockets (line 231) | async closeAllLocalSockets(): Promise<void> {
method handleUpgrade (line 273) | handleUpgrade(res: HttpResponse, req: HttpRequest, context): any {
method handlePong (line 290) | handlePong(ws: WebSocket): any {
method subscribeToChannel (line 314) | subscribeToChannel(ws: WebSocket, message: PusherMessage): any {
method unsubscribeFromChannel (line 468) | unsubscribeFromChannel(ws: WebSocket, channel: string, closing = false...
method unsubscribeFromAllChannels (line 523) | unsubscribeFromAllChannels(ws: WebSocket, closing = true): Promise<voi...
method handleClientEvent (line 541) | handleClientEvent(ws: WebSocket, message: PusherMessage): any {
method handleSignin (line 629) | handleSignin(ws: WebSocket, message: PusherMessage): void {
method sendMissedCacheIfExists (line 698) | sendMissedCacheIfExists(ws: WebSocket, channel: string) {
method getChannelManagerFor (line 714) | getChannelManagerFor(channel: string): PublicChannelManager|PrivateCha...
method checkForValidApp (line 729) | protected checkForValidApp(ws: WebSocket): Promise<App|null> {
method checkIfAppIsEnabled (line 736) | protected checkIfAppIsEnabled(ws: WebSocket): Promise<boolean> {
method checkAppConnectionLimit (line 744) | protected checkAppConnectionLimit(ws: WebSocket): Promise<boolean> {
method signinTokenIsValid (line 762) | signinTokenIsValid(ws: WebSocket, userData: string, signatureToCheck: ...
method signinTokenForUserData (line 771) | protected signinTokenForUserData(ws: WebSocket, userData: string): Pro...
method generateSocketId (line 785) | protected generateSocketId(): string {
method clearTimeout (line 797) | protected clearTimeout(ws: WebSocket): void {
method updateTimeout (line 806) | protected updateTimeout(ws: WebSocket): void {
method setUserAuthenticationTimeout (line 821) | protected setUserAuthenticationTimeout(ws: WebSocket): void {
FILE: tests/fixtures/dynamodb_schema.js
constant AWS (line 1) | const AWS = require('aws-sdk');
FILE: tests/fixtures/mysql_schema.sql
type `apps` (line 1) | CREATE TABLE IF NOT EXISTS `apps` (
FILE: tests/fixtures/postgres_schema.sql
type apps (line 1) | CREATE TABLE IF NOT EXISTS apps (
FILE: tests/utils.ts
class Utils (line 13) | class Utils {
method appManagerIs (line 17) | static appManagerIs(manager: string): boolean {
method adapterIs (line 21) | static adapterIs(adapter: string) {
method queueDriverIs (line 25) | static queueDriverIs(queueDriver: string) {
method waitForPortsToFreeUp (line 29) | static waitForPortsToFreeUp(): Promise<any> {
method newServer (line 39) | static newServer(options = {}, callback): any {
method newClonedServer (line 86) | static newClonedServer(server: Server, options = {}, callback): any {
method newWebhookServer (line 97) | static newWebhookServer(requestHandler: CallableFunction, onReadyCallb...
method flushWsServers (line 124) | static flushWsServers(): Promise<void> {
method flushHttpServers (line 138) | static flushHttpServers(): Promise<void> {
method flushServers (line 152) | static flushServers(): Promise<any> {
method newClient (line 159) | static newClient(options = {}, port = 6001, key = 'app-key', withState...
method newBackend (line 187) | static newBackend(appId = 'app-id', key = 'app-key', secret = 'app-sec...
method newClientForPrivateChannel (line 198) | static newClientForPrivateChannel(clientOptions = {}, port = 6001, key...
method newClientForEncryptedPrivateChannel (line 220) | static newClientForEncryptedPrivateChannel(clientOptions = {}, port = ...
method newClientForPresenceUser (line 243) | static newClientForPresenceUser(user: any, clientOptions = {}, port = ...
method signTokenForPrivateChannel (line 265) | static signTokenForPrivateChannel(
method signTokenForPresenceChannel (line 276) | static signTokenForPresenceChannel(
method signTokenForUserAuthentication (line 288) | static signTokenForUserAuthentication(
method wait (line 299) | static wait(ms): Promise<void> {
method randomChannelName (line 303) | static randomChannelName(): string {
method shouldRun (line 307) | static shouldRun(condition): jest.It {
Condensed preview — 116 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (611K chars).
[
{
"path": ".dockerignore",
"chars": 135,
"preview": ".git/**/*\nassets/**/*\nbenchmark/**/*\nbuild/**/*\ncoverage/**/*\ndist/**/*\nnode_modules/**/*\ntests/**/*\n.env\nnpm-debug.log\n"
},
{
"path": ".editorconfig",
"chars": 225,
"preview": "root = true\n\n[*]\ncharset = utf-8\nend_of_line = lf\ninsert_final_newline = true\nindent_style = space\nindent_size = 4\ntrim_"
},
{
"path": ".eslintrc.js",
"chars": 651,
"preview": "module.exports = {\n root: true,\n env: {\n browser: true,\n jest: true,\n node: true,\n },\n "
},
{
"path": ".gitattributes",
"chars": 217,
"preview": "* text=auto\n\n/.github export-ignore\n/tests export-ignore\n.editorconfig export-ignore\n.gitattributes export-ignore\n.gitig"
},
{
"path": ".github/FUNDING.yml",
"chars": 17,
"preview": "github: rennokki\n"
},
{
"path": ".github/ISSUE_TEMPLATE/bug-report---.md",
"chars": 1321,
"preview": "---\nname: \"Bug Report \\U0001F41E\"\nabout: Report a bug. This is NOT for other versions of Soketi. Use the Discussions boa"
},
{
"path": ".github/ISSUE_TEMPLATE/feature-request-🚀.md",
"chars": 623,
"preview": "---\nname: \"Feature request \\U0001F680\"\nabout: Suggest an idea for this project\ntitle: \"[REQUEST]\"\nlabels: ''\nassignees: "
},
{
"path": ".github/dependabot.yml",
"chars": 1896,
"preview": "version: 2\nregistries:\n quay:\n type: docker-registry\n url: quay.io\n username: ${{ secrets.DOCKER_REGISTRY_USER"
},
{
"path": ".github/stale.yml",
"chars": 594,
"preview": "# Number of days of inactivity before an issue becomes stale\ndaysUntilStale: 29\n# Number of days of inactivity before a "
},
{
"path": ".github/workflows/benchmark.yml",
"chars": 7889,
"preview": "name: Benchmark\n\non:\n workflow_run:\n workflows:\n - \"CI\"\n types:\n - completed\n\njobs:\n build:\n if: \"!"
},
{
"path": ".github/workflows/ci.yml",
"chars": 4193,
"preview": "name: CI\n\non:\n push:\n branches:\n - '*'\n tags:\n - '*'\n paths-ignore:\n - \"**.md\"\n pull_request:\n"
},
{
"path": ".github/workflows/docker-commit.yml",
"chars": 5128,
"preview": "name: Docker Commit\n\non:\n push:\n branches:\n - \"*\"\n pull_request:\n branches:\n - \"*\"\n tags-ignore:\n "
},
{
"path": ".github/workflows/docker-latest-tag.yml",
"chars": 4708,
"preview": "name: Docker Latest - Standard\n\non:\n push:\n branches:\n - master\n tags-ignore:\n - \"*\"\n pull_request:\n "
},
{
"path": ".github/workflows/docker-release-tag.yml",
"chars": 5076,
"preview": "name: Docker Release - Standard\n\non:\n push:\n tags:\n - \"*\"\n\njobs:\n # Alpine build.\n # WARNING: Deprecated, wil"
},
{
"path": ".github/workflows/release-npm.yml",
"chars": 1380,
"preview": "name: NPM Release\n\non:\n push:\n tags:\n - \"*\"\n\njobs:\n build:\n if: \"!contains(github.event.head_commit.message"
},
{
"path": ".gitignore",
"chars": 125,
"preview": "benchmark/vendor/\nbuild/\ncoverage/\ndist/\nnode_modules/\n.env\nbenchmark/composer.lock\nconfig.json\nnpm-debug.log\nyarn.lock\n"
},
{
"path": ".npmignore",
"chars": 12,
"preview": "src/\ntests/\n"
},
{
"path": "CONTRIBUTING.md",
"chars": 2972,
"preview": "# Contributing\n\nContributions are **welcome** and will be fully **credited**.\n\nPlease read and understand the contributi"
},
{
"path": "Dockerfile",
"chars": 1378,
"preview": "ARG VERSION=lts\n\nFROM --platform=$BUILDPLATFORM node:$VERSION-alpine as build\n\nENV PYTHONUNBUFFERED=1\n\nCOPY . /tmp/build"
},
{
"path": "Dockerfile.awslocal",
"chars": 330,
"preview": "FROM python:3-alpine\n\nRUN pip install awscli-local awscli && \\\n mkdir -p ~/.aws && \\\n touch ~/.aws/credentials && "
},
{
"path": "Dockerfile.debian",
"chars": 1138,
"preview": "ARG VERSION=lts\n\nFROM --platform=$BUILDPLATFORM node:$VERSION-bullseye as build\n\nENV PYTHONUNBUFFERED=1\n\nCOPY . /tmp/bui"
},
{
"path": "Dockerfile.distroless",
"chars": 1334,
"preview": "ARG VERSION=16\n\nFROM --platform=$BUILDPLATFORM node:$VERSION-alpine as base\n\nENV PYTHONUNBUFFERED=1\n\nCOPY . /tmp/build\n\n"
},
{
"path": "LICENSE",
"chars": 34523,
"preview": " GNU AFFERO GENERAL PUBLIC LICENSE\n Version 3, 19 November 2007\n\n Copyright (C)"
},
{
"path": "README.md",
"chars": 6368,
"preview": "# soketi\n\n<img src=\"assets/logo.png\" width=\"120\" />\n\n;\n\nprocess.title = 'soketi-server';\n\nCli.startWithPm2("
},
{
"path": "bin/server.js",
"chars": 82,
"preview": "#! /usr/bin/env node\n\nrequire('./../dist/cli');\n\nprocess.title = 'soketi-server';\n"
},
{
"path": "docker-compose.yml",
"chars": 1660,
"preview": "version: \"3\"\n\nnetworks:\n soketi:\n driver: bridge\n\nservices:\n localstack:\n container_name: localstack\n image: "
},
{
"path": "jest.config.js",
"chars": 383,
"preview": "module.exports = {\n transform: {\n '^.+\\\\.tsx?$': 'ts-jest',\n },\n moduleFileExtensions: ['ts', 'tsx', 'js"
},
{
"path": "new-connection.sh",
"chars": 191,
"preview": "#!/bin/bash\n\nwebsocat -t - autoreconnect:ws://127.0.0.1:$1/app/app-key -v --ping-interval=15\n\n# Send this event for test"
},
{
"path": "package.json",
"chars": 2693,
"preview": "{\n \"name\": \"@soketi/soketi\",\n \"version\": \"0.0.0-dev\",\n \"description\": \"Just another simple, fast, and resilient open-"
},
{
"path": "src/adapters/adapter-interface.ts",
"chars": 3941,
"preview": "import { Namespace } from '../namespace';\nimport { PresenceMemberInfo } from '../channels/presence-channel-manager';\nimp"
},
{
"path": "src/adapters/adapter.ts",
"chars": 6355,
"preview": "import { AdapterInterface } from './adapter-interface';\nimport { ClusterAdapter } from './cluster-adapter';\nimport { Loc"
},
{
"path": "src/adapters/cluster-adapter.ts",
"chars": 2482,
"preview": "import { AdapterInterface } from './adapter-interface';\nimport { HorizontalAdapter, PubsubBroadcastedMessage } from './h"
},
{
"path": "src/adapters/horizontal-adapter.ts",
"chars": 27825,
"preview": "import { LocalAdapter } from './local-adapter';\nimport { Log } from '../log';\nimport { PresenceMemberInfo } from '../cha"
},
{
"path": "src/adapters/index.ts",
"chars": 235,
"preview": "export * from './adapter';\nexport * from './adapter-interface';\nexport * from './cluster-adapter';\nexport * from './hori"
},
{
"path": "src/adapters/local-adapter.ts",
"chars": 7264,
"preview": "import { AdapterInterface } from './adapter-interface';\nimport { Namespace } from '../namespace';\nimport { PresenceMembe"
},
{
"path": "src/adapters/nats-adapter.ts",
"chars": 4468,
"preview": "import { AdapterInterface } from './adapter-interface';\nimport { connect, JSONCodec, Msg, NatsConnection, StringCodec } "
},
{
"path": "src/adapters/redis-adapter.ts",
"chars": 5898,
"preview": "import { AdapterInterface } from './adapter-interface';\nimport { HorizontalAdapter, PubsubBroadcastedMessage } from './h"
},
{
"path": "src/app-managers/app-manager-interface.ts",
"chars": 454,
"preview": "import { App } from '../app';\n\nexport interface AppManagerInterface {\n /**\n * The application manager driver.\n "
},
{
"path": "src/app-managers/app-manager.ts",
"chars": 2760,
"preview": "import { App } from './../app';\nimport { AppManagerInterface } from './app-manager-interface';\nimport { ArrayAppManager "
},
{
"path": "src/app-managers/array-app-manager.ts",
"chars": 1408,
"preview": "import { App } from '../app';\nimport { BaseAppManager } from './base-app-manager';\nimport { Log } from '../log';\nimport "
},
{
"path": "src/app-managers/base-app-manager.ts",
"chars": 681,
"preview": "import { App } from '../app';\nimport { AppManagerInterface } from './app-manager-interface';\n\nexport class BaseAppManage"
},
{
"path": "src/app-managers/dynamodb-app-manager.ts",
"chars": 3401,
"preview": "import { App } from '../app';\nimport { AttributeMap } from 'aws-sdk/clients/dynamodb';\nimport { BaseAppManager } from '."
},
{
"path": "src/app-managers/index.ts",
"chars": 297,
"preview": "export * from './app-manager';\nexport * from './app-manager-interface';\nexport * from './array-app-manager';\nexport * fr"
},
{
"path": "src/app-managers/mysql-app-manager.ts",
"chars": 1133,
"preview": "import { SqlAppManager } from './sql-app-manager';\n\nexport class MysqlAppManager extends SqlAppManager {\n /**\n * "
},
{
"path": "src/app-managers/postgres-app-manager.ts",
"chars": 1058,
"preview": "import { SqlAppManager } from './sql-app-manager';\n\nexport class PostgresAppManager extends SqlAppManager {\n /**\n "
},
{
"path": "src/app-managers/sql-app-manager.ts",
"chars": 3127,
"preview": "import { App } from './../app';\nimport { BaseAppManager } from './base-app-manager';\nimport { Log } from '../log';\nimpor"
},
{
"path": "src/app.ts",
"chars": 12297,
"preview": "import { HttpResponse } from 'uWebSockets.js';\nimport { Lambda } from 'aws-sdk';\nimport { Server } from './server';\n\ncon"
},
{
"path": "src/cache-managers/cache-manager-interface.ts",
"chars": 763,
"preview": "import Redis, { Cluster } from 'ioredis';\n\nexport interface CacheManagerInterface {\n /**\n * The cache interface m"
},
{
"path": "src/cache-managers/cache-manager.ts",
"chars": 1534,
"preview": "import { CacheManagerInterface } from './cache-manager-interface';\nimport { Log } from '../log';\nimport { MemoryCacheMan"
},
{
"path": "src/cache-managers/index.ts",
"chars": 155,
"preview": "export * from './cache-manager';\nexport * from './cache-manager-interface';\nexport * from './memory-cache-manager';\nexpo"
},
{
"path": "src/cache-managers/memory-cache-manager.ts",
"chars": 1888,
"preview": "import { CacheManagerInterface } from './cache-manager-interface';\nimport { Server } from '../server';\n\ninterface Memory"
},
{
"path": "src/cache-managers/redis-cache-manager.ts",
"chars": 1769,
"preview": "import { CacheManagerInterface } from './cache-manager-interface';\nimport Redis, { Cluster, ClusterOptions, RedisOptions"
},
{
"path": "src/channels/encrypted-private-channel-manager.ts",
"chars": 153,
"preview": "import { PrivateChannelManager } from './private-channel-manager';\n\nexport class EncryptedPrivateChannelManager extends "
},
{
"path": "src/channels/index.ts",
"chars": 182,
"preview": "export * from './encrypted-private-channel-manager';\nexport * from './presence-channel-manager';\nexport * from './privat"
},
{
"path": "src/channels/presence-channel-manager.ts",
"chars": 3061,
"preview": "import { JoinResponse, LeaveResponse } from './public-channel-manager';\nimport { Log } from '../log';\nimport { PrivateCh"
},
{
"path": "src/channels/private-channel-manager.ts",
"chars": 2423,
"preview": "import { App } from '../app';\nimport { JoinResponse, PublicChannelManager } from './public-channel-manager';\nimport { Pu"
},
{
"path": "src/channels/public-channel-manager.ts",
"chars": 2167,
"preview": "import { PresenceMember } from '../channels/presence-channel-manager';\nimport { PusherMessage } from '../message';\nimpor"
},
{
"path": "src/cli/cli.ts",
"chars": 9642,
"preview": "import { readFileSync } from 'fs';\nimport { Log } from '..';\nimport { Server } from './../server';\n\nexport class Cli {\n "
},
{
"path": "src/cli/index.ts",
"chars": 431,
"preview": "import { Cli } from './cli';\n\nlet yargs = require('yargs')\n .usage('Usage: soketi <command> [options]')\n .command("
},
{
"path": "src/http-handler.ts",
"chars": 22803,
"preview": "import { App } from './app';\nimport async from 'async';\nimport { HttpResponse, RecognizedString } from 'uWebSockets.js';"
},
{
"path": "src/index.ts",
"chars": 272,
"preview": "export * from './app';\nexport * from './http-handler';\nexport * from './job';\nexport * from './log';\nexport * from './na"
},
{
"path": "src/job.ts",
"chars": 217,
"preview": "import { v4 as uuidv4 } from 'uuid';\n\nexport class Job {\n /**\n * Create a new job instance.\n */\n construct"
},
{
"path": "src/log.ts",
"chars": 3350,
"preview": "const colors = require('colors');\n\nexport class Log {\n static infoTitle(message: any): void {\n this.log(messag"
},
{
"path": "src/message.ts",
"chars": 595,
"preview": "export interface MessageData {\n channel_data?: string;\n channel?: string;\n user_data?: string;\n [key: string"
},
{
"path": "src/metrics/index.ts",
"chars": 109,
"preview": "export * from './metrics';\nexport * from './metrics-interface';\nexport * from './prometheus-metrics-driver';\n"
},
{
"path": "src/metrics/metrics-interface.ts",
"chars": 1936,
"preview": "import * as prom from 'prom-client';\nimport { WebSocket } from 'uWebSockets.js';\n\nexport interface MetricsInterface {\n "
},
{
"path": "src/metrics/metrics.ts",
"chars": 3841,
"preview": "import * as prom from 'prom-client';\nimport { WebSocket } from 'uWebSockets.js';\nimport { Log } from './../log';\nimport "
},
{
"path": "src/metrics/prometheus-metrics-driver.ts",
"chars": 11023,
"preview": "import * as prom from 'prom-client';\nimport { WebSocket } from 'uWebSockets.js';\nimport { MetricsInterface } from './met"
},
{
"path": "src/namespace.ts",
"chars": 7126,
"preview": "import { PresenceMember, PresenceMemberInfo } from './channels/presence-channel-manager';\nimport { WebSocket } from 'uWe"
},
{
"path": "src/node.ts",
"chars": 126,
"preview": "export interface Node {\n isMaster: boolean;\n address: string;\n port: number;\n lastSeen: number;\n id: stri"
},
{
"path": "src/options.ts",
"chars": 4526,
"preview": "import { AppInterface } from './app';\nimport { ClusterOptions, RedisOptions } from 'ioredis';\nimport { ConsumerOptions }"
},
{
"path": "src/queues/index.ts",
"chars": 171,
"preview": "export * from './queue-interface';\nexport * from './queue';\nexport * from './redis-queue-driver';\nexport * from './sqs-q"
},
{
"path": "src/queues/queue-interface.ts",
"chars": 530,
"preview": "import { JobData } from '../webhook-sender';\n\nexport interface QueueInterface {\n /**\n * The Queue driver.\n */"
},
{
"path": "src/queues/queue.ts",
"chars": 1535,
"preview": "import { JobData } from '../webhook-sender';\nimport { Log } from '../log';\nimport { QueueInterface } from './queue-inter"
},
{
"path": "src/queues/redis-queue-driver.ts",
"chars": 3999,
"preview": "import async from 'async';\nimport { JobData } from '../webhook-sender';\nimport { Queue, Worker, QueueScheduler } from 'b"
},
{
"path": "src/queues/sqs-queue-driver.ts",
"chars": 4216,
"preview": "import async from 'async';\nimport { Consumer } from 'sqs-consumer';\nimport { createHash } from 'crypto';\nimport { Job } "
},
{
"path": "src/queues/sync-queue-driver.ts",
"chars": 1343,
"preview": "import { Job } from '../job';\nimport { JobData } from '../webhook-sender';\nimport { QueueInterface } from './queue-inter"
},
{
"path": "src/rate-limiters/cluster-rate-limiter.ts",
"chars": 3705,
"preview": "import { App } from './../app';\nimport { ConsumptionResponse } from './rate-limiter-interface';\nimport { LocalRateLimite"
},
{
"path": "src/rate-limiters/index.ts",
"chars": 190,
"preview": "export * from './cluster-rate-limiter';\nexport * from './local-rate-limiter';\nexport * from './rate-limiter-interface';\n"
},
{
"path": "src/rate-limiters/local-rate-limiter.ts",
"chars": 4227,
"preview": "import { App } from './../app';\nimport { ConsumptionResponse, RateLimiterInterface } from './rate-limiter-interface';\nim"
},
{
"path": "src/rate-limiters/rate-limiter-interface.ts",
"chars": 1287,
"preview": "import { App } from './../app';\nimport { RateLimiterAbstract, RateLimiterRes } from 'rate-limiter-flexible';\nimport { We"
},
{
"path": "src/rate-limiters/rate-limiter.ts",
"chars": 2289,
"preview": "import { App } from './../app';\nimport { ClusterRateLimiter } from './cluster-rate-limiter';\nimport { ConsumptionRespons"
},
{
"path": "src/rate-limiters/redis-rate-limiter.ts",
"chars": 1719,
"preview": "import { LocalRateLimiter } from './local-rate-limiter';\nimport { RateLimiterAbstract, RateLimiterRedis } from 'rate-lim"
},
{
"path": "src/server.ts",
"chars": 24636,
"preview": "import * as dot from 'dot-wild';\nimport { Adapter, AdapterInterface } from './adapters';\nimport { AppManager, AppManager"
},
{
"path": "src/utils.ts",
"chars": 3505,
"preview": "export class Utils {\n /**\n * Allowed client events patterns.\n *\n * @type {string[]}\n */\n protected"
},
{
"path": "src/webhook-sender.ts",
"chars": 11995,
"preview": "import { App, WebhookInterface } from './app';\nimport async from 'async';\nimport axios from 'axios';\nimport { createHmac"
},
{
"path": "src/ws-handler.ts",
"chars": 27547,
"preview": "import { App } from './app';\nimport async from 'async';\nimport { EncryptedPrivateChannelManager } from './channels';\nimp"
},
{
"path": "tests/encrypted-private.test.ts",
"chars": 7294,
"preview": "import { Server } from './../src/server';\nimport { Utils } from './utils';\n\njest.retryTimes(parseInt(process.env.RETRY_T"
},
{
"path": "tests/fixtures/dynamodb_schema.js",
"chars": 2972,
"preview": "const AWS = require('aws-sdk');\n\nlet ddb = new AWS.DynamoDB({\n apiVersion: '2012-08-10',\n region: 'us-east-1',\n "
},
{
"path": "tests/fixtures/mysql_schema.sql",
"chars": 1528,
"preview": "CREATE TABLE IF NOT EXISTS `apps` (\n `id` varchar(255) NOT NULL,\n `key` varchar(255) NOT NULL,\n `secret` varcha"
},
{
"path": "tests/fixtures/postgres_schema.sql",
"chars": 1486,
"preview": "CREATE TABLE IF NOT EXISTS apps (\n id varchar(255) PRIMARY KEY,\n \"key\" varchar(255) NOT NULL,\n secret varchar(2"
},
{
"path": "tests/fixtures/sqs.json",
"chars": 255,
"preview": "{\n \"FifoQueue\": \"true\",\n \"ContentBasedDeduplication\": \"true\",\n \"DeduplicationScope\": \"messageGroup\",\n \"FifoThroughpu"
},
{
"path": "tests/http-api.cluster-adapter.test.ts",
"chars": 17241,
"preview": "import { Server } from './../src/server';\nimport { Utils } from './utils';\n\njest.retryTimes(parseInt(process.env.RETRY_T"
},
{
"path": "tests/http-api.nats-adapter.test.ts",
"chars": 17196,
"preview": "import { Server } from './../src/server';\nimport { Utils } from './utils';\n\njest.retryTimes(parseInt(process.env.RETRY_T"
},
{
"path": "tests/http-api.redis-adapter.test.ts",
"chars": 17211,
"preview": "import { Server } from './../src/server';\nimport { Utils } from './utils';\n\njest.retryTimes(parseInt(process.env.RETRY_T"
},
{
"path": "tests/http-api.test.ts",
"chars": 24872,
"preview": "import axios from 'axios';\nimport { Server } from './../src/server';\nimport { Utils } from './utils';\n\njest.retryTimes(p"
},
{
"path": "tests/presence.cluster-adapter.test.ts",
"chars": 3132,
"preview": "import { Server } from './../src/server';\nimport { Utils } from './utils';\n\njest.retryTimes(parseInt(process.env.RETRY_T"
},
{
"path": "tests/presence.nats-adapter.test.ts",
"chars": 3123,
"preview": "import { Server } from './../src/server';\nimport { Utils } from './utils';\n\njest.retryTimes(parseInt(process.env.RETRY_T"
},
{
"path": "tests/presence.redis-adapter.test.ts",
"chars": 3000,
"preview": "import { Server } from './../src/server';\nimport { Utils } from './utils';\n\njest.retryTimes(parseInt(process.env.RETRY_T"
},
{
"path": "tests/presence.test.ts",
"chars": 14461,
"preview": "import { Server } from './../src/server';\nimport { Utils } from './utils';\n\njest.retryTimes(parseInt(process.env.RETRY_T"
},
{
"path": "tests/private.test.ts",
"chars": 7911,
"preview": "import { Server } from './../src/server';\nimport { Utils } from './utils';\n\njest.retryTimes(parseInt(process.env.RETRY_T"
},
{
"path": "tests/public.test.ts",
"chars": 5771,
"preview": "import { Server } from './../src/server';\nimport { Utils } from './utils';\n\ndescribe('public channel test', () => {\n "
},
{
"path": "tests/utils.ts",
"chars": 11317,
"preview": "import async from 'async';\nimport { Log } from '../src/log';\nimport { PusherApiMessage } from '../src/message';\nimport {"
},
{
"path": "tests/webhooks.test.ts",
"chars": 24240,
"preview": "import { App } from '../src/app';\nimport { Server } from '../src/server';\nimport { Utils } from './utils';\nimport { crea"
},
{
"path": "tests/ws.cluster-adapter.test.ts",
"chars": 15972,
"preview": "import { Server } from './../src/server';\nimport { Utils } from './utils';\n\njest.retryTimes(parseInt(process.env.RETRY_T"
},
{
"path": "tests/ws.nats-adapter.test.ts",
"chars": 15921,
"preview": "import { Server } from './../src/server';\nimport { Utils } from './utils';\n\njest.retryTimes(parseInt(process.env.RETRY_T"
},
{
"path": "tests/ws.redis-adapter.test.ts",
"chars": 14691,
"preview": "import { Server } from './../src/server';\nimport { Utils } from './utils';\n\njest.retryTimes(parseInt(process.env.RETRY_T"
},
{
"path": "tests/ws.test.ts",
"chars": 20563,
"preview": "import { Server } from './../src/server';\nimport { Utils } from './utils';\n\njest.retryTimes(parseInt(process.env.RETRY_T"
},
{
"path": "tsconfig.json",
"chars": 545,
"preview": "{\n \"compilerOptions\": {\n \"allowSyntheticDefaultImports\": true,\n \"module\": \"commonjs\",\n \"moduleResolution\": \"no"
}
]
About this extraction
This page contains the full source code of the soketi/pws GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 116 files (573.9 KB), approximately 120.0k tokens, and a symbol index with 470 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.