### Nats Server Startup Source: https://centrifugal.dev/docs/server/engines Example output from starting a Nats server. ```bash $ nats-server [3569] 2020/07/08 20:28:44.324269 [INF] Starting nats-server version 2.1.7 [3569] 2020/07/08 20:28:44.324400 [INF] Git commit [not set] [3569] 2020/07/08 20:28:44.325600 [INF] Listening for client connections on 0.0.0.0:4222 [3569] 2020/07/08 20:28:44.325612 [INF] Server id is NDAM7GEHUXAKS5SGMA3QE6ZSO4IQUJP6EL3G2E2LJYREVMAMIOBE7JT4 [3569] 2020/07/08 20:28:44.325617 [INF] Server is ready ``` -------------------------------- ### Download and install binary Source: https://centrifugal.dev/docs/getting-started/installation Use the installation script to download and unpack the binary for Linux or MacOS. ```bash curl -sSLf https://centrifugal.dev/install.sh | sh ``` -------------------------------- ### Subscription Token Configuration Example Source: https://centrifugal.dev/docs/pro/client_authentication Example configuration showing how to set up JWKS providers for both connection tokens and subscription tokens. ```APIDOC ## Subscription Token JWKS Configuration Example This example demonstrates how to configure JWKS providers for both connection and subscription tokens. ### Configuration ```json { "client": { "token": { "jwks": { "enabled": true, "providers": [ { "name": "auth0_connection", "enabled": true, "endpoint": "https://tenant.auth0.com/.well-known/jwks.json", "issuer": "https://tenant.auth0.com/", "audience": "centrifugo" } ] } }, "subscription_token": { "enabled": true, "jwks": { "enabled": true, "providers": [ { "name": "subscription_identity", "enabled": true, "endpoint": "https://tenant.example.com/.well-known/jwks.json", "issuer": "https://tenant.example.com", "audience": "centrifugo" } ] } } } } ``` ### Notes - `meta_from_claim` is not supported for subscription tokens. - Issuer+audience matching applies to subscription tokens similarly to connection tokens. ``` -------------------------------- ### Redis Sentinel Configuration Example Source: https://centrifugal.dev/docs/server/engines Example configuration for a 3-node Redis Sentinel setup. This defines the port, monitors the master, and sets down-after-milliseconds and failover-timeout. ```text port 26379 sentinel monitor mymaster 127.0.0.1 6379 2 sentinel down-after-milliseconds mymaster 10000 sentinel failover-timeout mymaster 60000 ``` -------------------------------- ### Install project dependencies Source: https://centrifugal.dev/docs/tutorial/frontend Commands to navigate to the project directory and install required packages. ```bash cd frontend npm install ``` -------------------------------- ### YAML configuration file example Source: https://centrifugal.dev/docs/server/configuration Example of a YAML configuration file for Centrifugo. ```yaml client: token: hmac_secret_key: "" allowed_origins: - http://localhost:3000 http_api: key: "" ``` -------------------------------- ### Install Django Rest Framework Source: https://centrifugal.dev/docs/tutorial/backend Install the REST framework and update the requirements file. ```bash pip install djangorestframework==3.14.0 pip freeze > requirements.txt ``` -------------------------------- ### Get User Status Response Example (Active) Source: https://centrifugal.dev/docs/pro/user_status Example response when user status information is available, including last active and online times. ```json { "result":{ "statuses":[ { "user":"42", "active":1627107289, "online":1627107289 } ] } } ``` -------------------------------- ### JSON configuration file example Source: https://centrifugal.dev/docs/server/configuration Example of a standard JSON configuration file for Centrifugo. ```json { "client": { "token": { "hmac_secret_key": "" }, "allowed_origins": [ "http://localhost:3000" ] }, "http_api": { "key": "" } } ``` -------------------------------- ### Browser Connection Example Source: https://centrifugal.dev/docs/transports/uni_sse Complete example for connecting to the SSE endpoint from a browser and handling incoming messages. ```javascript const url = new URL('http://localhost:8000/connection/uni_sse'); url.searchParams.append("cf_connect", JSON.stringify({ 'token': '' })) const eventSource = new EventSource(url); eventSource.onmessage = function(event) { console.log(event.data); }; ``` -------------------------------- ### TOML configuration file example Source: https://centrifugal.dev/docs/server/configuration Example of a TOML configuration file and the command to run Centrifugo with it. ```bash centrifugo --config=config.toml ``` ```toml [client] allowed_origins = [ "http://localhost:3000" ] [client.token] hmac_secret_key = "" [http_api] key = "" ``` -------------------------------- ### Centrifugo Configuration File Example Source: https://centrifugal.dev/docs/server/configuration Example of a Centrifugo configuration file showing settings for client origins and Prometheus. ```json { "client": { "allowed_origins": [ "https://mysite1.com", "https://mysite2.com" ] }, "prometheus": { "enabled": true } } ``` -------------------------------- ### Initialize Django project Source: https://centrifugal.dev/docs/tutorial/backend Set up a virtual environment, install Django, and create the project structure. ```bash python3 -m venv env ./env/bin/activate python -m pip install Django python -m django --version django-admin startproject app mv app backend ``` -------------------------------- ### Start Local PostgreSQL with Docker Source: https://centrifugal.dev/docs/pro/user_block Quickly start a local PostgreSQL database instance using Docker for testing or development purposes. ```bash docker run -it --rm -e POSTGRES_USER=postgres -e POSTGRES_PASSWORD=pass -p 5432:5432 postgres:15 ``` -------------------------------- ### Docker Compose configuration Source: https://centrifugal.dev/docs/getting-started/installation Example JSON configuration and docker-compose.yml setup for Centrifugo. ```json { "client": { "token": { "hmac_secret_key": "my_secret" }, "allowed_origins": ["*"] }, "http_api": { "key": "my_api_key" }, "admin": { "password": "password", "secret": "secret", "enabled": true } } ``` ```yaml version: "3.9" services: centrifugo: container_name: centrifugo image: centrifugo/centrifugo:v6 volumes: - ./config.json:/centrifugo/config.json command: centrifugo -c config.json ports: - 8000:8000 ulimits: nofile: soft: 65535 hard: 65535 ``` -------------------------------- ### Connect to PostgreSQL Source: https://centrifugal.dev/docs/tutorial/tips_and_tricks Access the PostgreSQL database from within the example repository root. ```bash docker compose exec db psql postgresql://grandchat:grandchat@localhost:5432/grandchat ``` -------------------------------- ### Complete Configuration Example (YAML) Source: https://centrifugal.dev/docs/pro/client_publications This YAML configuration provides a more readable alternative to the JSON example, defining a 'reaction' schema and a 'room_chat_reactions' channel with jq transformation. It's useful for easier configuration management. ```yaml schemas: - name: reaction definition: | { "type": "object", "properties": { "emoji": {"type": "string"}, "message_id": {"type": "string"} }, "required": ["emoji", "message_id"] } channel: patterns: true namespaces: - name: room_chat_reactions pattern: /rooms/:room_id/reactions publication_data_format: json client_publication: schemas: [reaction] transform: enabled: true engine: jq jq: program: | { data: { emoji: .data.emoji, message_id: .data.message_id, user_id: .user }, tags: { room: .vars.room_id, user: .user }, idempotency_key: (.user + ":" + .data.message_id + ":" + .data.emoji) } exclude_client_info: true allow_publish_for_subscriber: true ``` -------------------------------- ### Configuration File Snippet Source: https://centrifugal.dev/docs/transports/uni_sse Example of enabling the uni_sse feature within a configuration file. ```json { ... "uni_sse": { "enabled": true } } ``` -------------------------------- ### JSON Commands Example Source: https://centrifugal.dev/docs/transports/client_protocol Example of sending multiple commands in a line-delimited JSON format. Each command is a separate JSON object on its own line. ```json {"id": 1, "subscribe": {"channel": "ch1"}} {"id": 2, "subscribe": {"channel": "ch2"}} ``` -------------------------------- ### Initialize Subscription with Token Source: https://centrifugal.dev/docs/transports/client_api Basic setup for a subscription using a static JWT token. ```javascript const sub = centrifuge.newSubscription(channel, { token: 'JWT-GENERATED-ON-BACKEND-SIDE' }); sub.subscribe(); ``` -------------------------------- ### Run Docker Compose Source: https://centrifugal.dev/docs/getting-started/installation Start the services defined in the docker-compose.yml file. ```bash docker-compose up ``` -------------------------------- ### Start Centrifugo Server Source: https://centrifugal.dev/docs/getting-started/quickstart Command to start the Centrifugo server using a specified configuration file. Ensure the config file path is correct. ```bash ./centrifugo --config=config.json ``` -------------------------------- ### Run Docker Compose Commands Source: https://centrifugal.dev/docs/tutorial/backend Commands to start the application and perform database migrations. ```bash docker compose up --build ``` ```bash docker compose exec backend python manage.py makemigrations docker compose exec backend python manage.py migrate ``` ```bash docker compose exec backend python manage.py createsuperuser ``` -------------------------------- ### Configure installed apps Source: https://centrifugal.dev/docs/tutorial/backend Register the chat app and Django Rest Framework in settings.py. ```python INSTALLED_APPS = [ 'chat', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] ``` ```python INSTALLED_APPS = [ 'rest_framework', 'chat', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] ``` -------------------------------- ### Handle subscription state events Source: https://centrifugal.dev/docs/transports/client_api Cross-language examples for listening to subscription state changes. ```javascript const sub = client.newSubscription(channel); sub.on('subscribing', function(ctx) { console.log('subscribing'); }); sub.on('subscribed', function(ctx) { console.log('subscribed'); }); sub.on('unsubscribed', function(ctx) { console.log('unsubscribed'); }); sub.subscribe(); ``` ```dart final onSubscriptionEvent = (dynamic event) async { print('subscription $channel> $event'); }; final subscription = client.newSubscription(channel); subscription.subscribing.listen(onSubscriptionEvent); subscription.subscribed.listen(onSubscriptionEvent); subscription.unsubscribed.listen(onSubscriptionEvent); await subscription.subscribe(); ``` ```swift class SubscriptionDelegate : NSObject, CentrifugeSubscriptionDelegate { func onSubscribing(_ s: CentrifugeSubscription, _ e: CentrifugeSubscribingEvent) { print("subscribing", e.code, e.reason) } func onSubscribed(_ s: CentrifugeSubscription, _ e: CentrifugeSubscribedEvent) { print("subscribed") } func onUnsubscribed(_ s: CentrifugeSubscription, _ e: CentrifugeUnsubscribedEvent) { print("unsubscribed", e.code, e.reason) } } do { sub = try self.client?.newSubscription(channel: "example", delegate: SubscriptionDelegate()) sub!.subscribe() } catch { print("Can not create subscription: \(error)") } ``` ```java SubscriptionEventListener subListener = new SubscriptionEventListener() { @Override public void onSubscribed(Subscription sub, SubscribedEvent event) { System.out.println("subscribed to " + sub.getChannel()); } @Override public void onSubscribing(Subscription sub, SubscribingEvent event) { System.out.printf("subscribing " + sub.getChannel()); } @Override public void onUnsubscribed(Subscription sub, UnsubscribedEvent event) { System.out.println("unsubscribed " + sub.getChannel()); } }; Subscription sub; try { sub = client.newSubscription("example", subListener); sub.subscribe(); } catch (DuplicateSubscriptionException e) { e.printStackTrace(); } ``` ```go sub, err := client.NewSubscription("example") if err != nil { log.Fatalln(err) } sub.OnSubscribing(func(e centrifuge.SubscribingEvent) { log.Printf("Subscribing on channel %s - %d (%s)", sub.Channel, e.Code, e.Reason) }) sub.OnSubscribed(func(e centrifuge.SubscribedEvent) { log.Printf("Subscribed on channel %s", sub.Channel) }) sub.OnUnsubscribed(func(e centrifuge.UnsubscribedEvent) { log.Printf("Unsubscribed from channel %s - %d (%s)", sub.Channel, e.Code, e.Reason) }) err = sub.Subscribe() if err != nil { log.Fatalln(err) } ``` -------------------------------- ### SSE Session Ping Example Source: https://centrifugal.dev/docs/transports/uni_sse Example output of an SSE session showing the initial connection response followed by periodic empty data frames used as pings. ```bash ❯ curl http://localhost:8000/connection/uni_sse data: {"connect":{"client":"c09d1965...","version":"0.0.0 OSS","subs":{"#2694":{}},"ping":25,"session":"1cf6d9f5..."}} data: {} data: {} data: {} ``` -------------------------------- ### Connect Push Message Example Source: https://centrifugal.dev/docs/transports/uni_client_protocol An example of a 'connect' Push frame sent immediately after a unidirectional connection is established. It includes client details, subscription information, and session identifiers. ```json { "connect":{ "client":"5c5b6011-b282-447d-8753-cee7269117e6", "version":"0.0.0 OSS", "subs":{ "personal:user#2694": { "recoverable":true, "offset": 12, "epoch":"BXLK", "positioned":true }, "global": {} }, "ping":25, "session":"631a6f6e-02bc-473b-908f-8059a680e74c" } } ``` -------------------------------- ### Install Gunicorn Source: https://centrifugal.dev/docs/tutorial/backend Add Gunicorn to the project dependencies. ```bash pip install gunicorn==21.2.0 pip freeze > requirements.txt ``` -------------------------------- ### Get User Status Response Example (Inactive) Source: https://centrifugal.dev/docs/pro/user_status Example response when information about the last status update time is not available for a user. ```json { "result":{ "statuses":[ { "user":"42" } ] } } ``` -------------------------------- ### Generate and run with default configuration Source: https://centrifugal.dev/docs/server/configuration Use the CLI to generate a starter configuration file and start the server using that file. ```bash centrifugo genconfig ``` ```bash centrifugo -c config.json ``` -------------------------------- ### Run Centrifugo with config Source: https://centrifugal.dev/docs/getting-started/installation Start the Centrifugo instance using a specific configuration file. ```bash ./centrifugo --config=config.json ``` ```bash centrifugo --config=config.json ``` -------------------------------- ### Manage client connection states across SDKs Source: https://centrifugal.dev/docs/transports/client_api Examples of initializing a client, registering state change listeners, and initiating a connection in various programming languages. ```javascript const client = new Centrifuge('ws://localhost:8000/connection/websocket', {}); client.on('connecting', function(ctx) { console.log('connecting', ctx); }); client.on('connected', function(ctx) { console.log('connected', ctx); }); client.on('disconnected', function(ctx) { console.log('disconnected', ctx); }); client.connect(); ``` ```dart final onEvent = (dynamic event) { print('client event> $event'); }; final client = centrifuge.createClient( 'ws://localhost:8000/connection/websocket', centrifuge.ClientConfig(), ); client.connecting.listen(onEvent); client.connected.listen(onEvent); client.disconnected.listen(onEvent); await client.connect(); ``` ```swift import SwiftCentrifuge class ClientDelegate : NSObject, CentrifugeClientDelegate { func onConnecting(_ c: CentrifugeClient, _ e: CentrifugeConnectingEvent) { print("connecting", e.code, e.reason) } func onConnected(_ client: CentrifugeClient, _ e: CentrifugeConnectedEvent) { print("connected with id", e.client) } func onDisconnected(_ client: CentrifugeClient, _ e: CentrifugeDisconnectedEvent) { print("disconnected", e.code, e.reason) } } let config = CentrifugeClientConfig() let endpoint = "ws://localhost:8000/connection/websocket" let client = CentrifugeClient(endpoint: endpoint, config: config, delegate: ClientDelegate()) client.connect() ``` ```java EventListener listener = new EventListener() { @Override public void onConnected(Client client, ConnectedEvent event) { System.out.println("connected"); } @Override public void onConnecting(Client client, ConnectingEvent event) { System.out.printf("connecting: %s%n", event.getReason()); } @Override public void onDisconnected(Client client, DisconnectedEvent event) { System.out.printf("disconnected %d %s", event.getCode(), event.getReason()); } }; Options opts = new Options(); Client client = new Client("ws://localhost:8000/connection/websocket", opts, listener); client.connect(); ``` ```go client := centrifuge.NewJsonClient( "ws://localhost:8000/connection/websocket", centrifuge.Config{}, ) defer client.Close() client.OnConnecting(func(e centrifuge.ConnectingEvent) { log.Printf("Connecting - %d (%s)", e.Code, e.Reason) }) client.OnConnected(func(e centrifuge.ConnectedEvent) { log.Printf("Connected with ID %s", e.ClientID) }) client.OnDisconnected(func(e centrifuge.DisconnectedEvent) { log.Printf("Disconnected: %d (%s)", e.Code, e.Reason) }) _ = client.connect() ``` -------------------------------- ### Initialize project directory Source: https://centrifugal.dev/docs/tutorial/backend Create the root directory and the docker-compose configuration file. ```bash mkdir grand-chat-tutorial cd grand-chat-tutorial touch docker-compose.yml ``` -------------------------------- ### GET /api/csrf/ Source: https://centrifugal.dev/docs/tutorial/backend Retrieves a CSRF token required for secure communication between the frontend and backend in a session-based authentication setup. ```APIDOC ## GET /api/csrf/ ### Description Returns a CSRF token in the response headers, which is necessary for the frontend to perform authenticated requests. ### Method GET ### Endpoint /api/csrf/ ### Response #### Success Response (200) - **X-CSRFToken** (header) - The CSRF token value required for subsequent requests. ``` -------------------------------- ### Build from source Source: https://centrifugal.dev/docs/getting-started/installation Clone the repository and compile the binary using the Go toolchain. ```bash git clone https://github.com/centrifugal/centrifugo.git cd centrifugo go build ./centrifugo ``` -------------------------------- ### Serve Static Files with Centrifugo Source: https://centrifugal.dev/docs/getting-started/quickstart Start Centrifugo's built-in static file server to serve your HTML and other assets. This is convenient for simple development setups. ```bash ./centrifugo serve --port 3000 ``` -------------------------------- ### Start Centrifugo Node with Redis Engine Source: https://centrifugal.dev/docs/server/engines Launches a Centrifugo instance using Redis as the engine. Ensure Redis is installed and running. Specify the configuration file, port, and engine type. ```bash centrifugo --config=config.json --port=8000 --engine.type=redis ``` ```bash centrifugo --config=config.json --port=8001 --engine.type=redis ``` ```bash centrifugo --config=config.json --port=8002 --engine.type=redis ``` -------------------------------- ### Initialize GRPC Project Source: https://centrifugal.dev/docs/server/server_api Commands to set up a Go project directory and download the Centrifugo API schema. ```bash mkdir centrifugo_grpc_example cd centrifugo_grpc_example/ touch main.go go mod init centrifugo_example mkdir apiproto cd apiproto wget https://raw.githubusercontent.com/centrifugal/centrifugo/master/internal/apiproto/api.proto -O api.proto ``` -------------------------------- ### Get Channel History Top Position Source: https://centrifugal.dev/docs/transports/client_api Retrieves the current top position (offset and epoch) of a stream within a channel where history is enabled. No setup is required beyond having an active subscription. ```javascript const resp = await subscription.history(); console.log(resp.offset); console.log(resp.epoch); ``` -------------------------------- ### Get Channel History Publications Since Position Source: https://centrifugal.dev/docs/transports/client_api Fetches up to 10 publications from a channel's history, starting from a specified stream position (offset and epoch). Ensure the channel has history enabled. ```javascript const resp = await subscription.history({limit: 10, since: {offset: 0, epoch: '...'}}); console.log(resp.publications); ``` -------------------------------- ### Basic Subscription with Channel Pattern in JS Source: https://centrifugal.dev/docs/pro/channel_patterns Demonstrates how to subscribe to a channel using a pattern in JavaScript. Ensure the client is initialized and connected. ```javascript const client = new Centrifuge("ws://...", {}); const sub = client.newSubscription('/users/mario'); sub.subscribe(); client.connect(); ``` -------------------------------- ### Connect and subscribe to a channel Source: https://centrifugal.dev/docs/transports/client_api Demonstrates initializing a client, creating a subscription, and connecting to the server across multiple languages. ```javascript const client = new Centrifuge('ws://localhost:8000/connection/websocket', {}); const sub = client.newSubscription('example').on('publication', function(ctx) { console.log("received publication from a channel", ctx.data); }); sub.subscribe(); client.connect(); ``` ```dart final client = centrifuge.createClient( 'ws://localhost:8000/connection/websocket', centrifuge.ClientConfig(), ); final subscription = client.newSubscription(channel); subscription.publication.listen((event) { print(event); }); await subscription.subscribe(); await client.connect(); ``` ```swift import SwiftCentrifuge class ClientDelegate : NSObject, CentrifugeClientDelegate {} let config = CentrifugeClientConfig() let endpoint = "ws://localhost:8000/connection/websocket" let client = CentrifugeClient(endpoint: endpoint, config: config, delegate: ClientDelegate()) class SubscriptionDelegate : NSObject, CentrifugeSubscriptionDelegate { func onPublication(_ s: CentrifugeSubscription, _ e: CentrifugePublicationEvent) { print("publication", e.data) } } do { sub = try self.client?.newSubscription(channel: "example", delegate: SubscriptionDelegate()) sub!.subscribe() } catch { print("Can not create subscription: \(error)") } client.connect() ``` ```java EventListener listener = new EventListener() {}; Options opts = new Options(); Client client = new Client("ws://localhost:8000/connection/websocket", opts, listener); SubscriptionEventListener subListener = new SubscriptionEventListener() { @Override public void onPublication(Subscription sub, PublicationEvent event) { System.out.println("publication from " + sub.getChannel()); } }; Subscription sub; try { sub = client.newSubscription("example", subListener); sub.subscribe(); } catch (DuplicateSubscriptionException e) { e.printStackTrace(); } client.connect(); ``` ```go client := centrifuge.NewJsonClient( "ws://localhost:8000/connection/websocket", centrifuge.Config{}, ) // defer client.Close() sub, err := client.NewSubscription("example") if err != nil { log.Fatalln(err) } sub.OnPublication(func(e centrifuge.PublicationEvent) { log.Printf("Publication from channel") }) err = sub.Subscribe() if err != nil { log.Fatalln(err) } if err = client.Connect(); err != nil { log.Fatalln(err) } ``` -------------------------------- ### Initialize Vite project Source: https://centrifugal.dev/docs/tutorial/frontend Command to scaffold a new React project with Vite. ```bash npm create vite@latest ``` -------------------------------- ### Install via Homebrew Source: https://centrifugal.dev/docs/getting-started/installation Install Centrifugo on macOS using the Homebrew package manager. ```bash brew tap centrifugal/centrifugo brew install centrifugo ``` -------------------------------- ### Execute Setup Function in Django Shell Source: https://centrifugal.dev/docs/tutorial/scale Import and run the `setup_dev` function within the Django shell to initialize the development environment. ```python from app.utils import setup_dev setup_dev() ``` -------------------------------- ### Logical Filter Structure Examples Source: https://centrifugal.dev/docs/server/publication_filtering Examples of using logical operators (and, or, not) to combine multiple FilterNode conditions. ```json // ticker = "AAPL" AND category = "tech" → ✅ Matches (both conditions true) { "op": "and", "nodes": [ {"key": "ticker", "cmp": "eq", "val": "AAPL"}, {"key": "category", "cmp": "eq", "val": "tech"} ] } // ticker = "MSFT" OR category = "tech" → ✅ Matches (category = "tech" is true) { "op": "or", "nodes": [ {"key": "ticker", "cmp": "eq", "val": "MSFT"}, {"key": "category", "cmp": "eq", "val": "tech"} ] } // NOT (source = "NYSE") → ✅ Matches (source is "NASDAQ", not "NYSE") { "op": "not", "nodes": [ {"key": "source", "cmp": "eq", "val": "NYSE"} ] } ``` -------------------------------- ### Configure Kafka Consumer Source: https://centrifugal.dev/docs/server/consumers Example configuration for enabling and setting up a Kafka consumer. Specify brokers, topics, and consumer group. ```json { "consumers": [ { "enabled": true, "name": "my_kafka_consumer", "type": "kafka", "kafka": { "brokers": ["localhost:9092"], "topics": ["postgres.public.chat_cdc"], "consumer_group": "centrifugo" } } ] } ``` -------------------------------- ### Unsubscribe Push Message Example Source: https://centrifugal.dev/docs/transports/uni_client_protocol Example of an 'unsubscribe' Push frame sent when a connection is unsubscribed from a channel during its lifetime. ```json { "channel":"test", "unsubscribe":{} } ``` -------------------------------- ### Reply with Error Example Source: https://centrifugal.dev/docs/transports/client_protocol An example of a server reply containing an error object associated with a specific command ID. ```json {"id": 1, "error": {"code": 100, "message": "internal server error"}} ``` -------------------------------- ### Leave Push Message Example Source: https://centrifugal.dev/docs/transports/uni_client_protocol Example of a 'leave' Push frame sent when a user unsubscribes from a channel that has join/leave features enabled. ```json { "channel":"#2694", "leave":{ "info":{"user":"2694","client":"99288691-e378-4a03-a34d-bf2c0dab6b51"} } } ``` -------------------------------- ### Join Push Message Example Source: https://centrifugal.dev/docs/transports/uni_client_protocol Example of a 'join' Push frame sent when a user subscribes to a channel that has join/leave features enabled. ```json { "channel":"#2694", "join":{ "info":{"user":"2694","client":"99288691-e378-4a03-a34d-bf2c0dab6b51"} } } ``` -------------------------------- ### Start Centrifugo with Tracing Enabled Source: https://centrifugal.dev/docs/server/observability Launch the Centrifugo binary with environment variables configured to export traces to the local OTLP endpoint. ```bash OTEL_EXPORTER_OTLP_ENDPOINT="http://localhost:4318" CENTRIFUGO_OPENTELEMETRY=1 CENTRIFUGO_OPENTELEMETRY_API=1 ./centrifugo ``` -------------------------------- ### Unidirectional HTTP Streaming Connection Example Source: https://centrifugal.dev/docs/transports/uni_client_protocol Example of establishing a unidirectional connection using HTTP streaming and the subsequent messages exchanged. ```APIDOC ## Unidirectional HTTP Streaming Connection Example ### Description This example demonstrates establishing a unidirectional connection via HTTP streaming and shows the typical message flow, including connection establishment, channel joins, publications, and disconnections. ### Method POST ### Endpoint `/connection/uni_http_stream` ### Request Example ```json {} ``` ### Response Example ```json {"connect":{"client":"bb56837...","version":"0.0.0 OSS","subs":{"#2694":{}},"ping":25,"session":"3159c4f8..."}} {"channel":"#2694","join":{"info":{"user":"2694","client":"bb56837e-5b93-4478-95b6-98f3d2269b29"}}} {"channel":"#2694","pub":{"data":{"input":1}}} {} {"channel":"#2694","pub":{"data":{"input":2}}} {"channel":"#2694","pub":{"data":{"input":3}}} {"disconnect":{"code":3001,"reason":"shutdown"}} ``` ``` -------------------------------- ### Install centrifuge-js SDK Source: https://centrifugal.dev/docs/tutorial/centrifugo Installs the Centrifugo JavaScript SDK using npm. This package is required for establishing WebSocket connections from the frontend. ```bash npm install centrifuge ``` -------------------------------- ### Generate Configuration Documentation Source: https://centrifugal.dev/docs/server/console_commands Starts a web server on port 6060 to display Centrifugo configuration options. Can output Markdown or filter by section. ```bash centrifugo configdoc ``` ```bash centrifugo configdoc --markdown ``` ```bash centrifugo configdoc --section=consumers ``` -------------------------------- ### Complete Configuration Example (JSON) Source: https://centrifugal.dev/docs/pro/client_publications This JSON configuration defines a 'reaction' schema and a 'room_chat_reactions' channel with a jq transformation for client publications. Use this for complex data handling and routing. ```json { "schemas": [ { "name": "reaction", "type": "jsonschema_draft_2020_12", "definition": "{\"type\":\"object\",\"properties\":{\"emoji\":{\"type\":\"string\"},\"message_id\":{\"type\":\"string\"}},\"required\":[\"emoji\",\"message_id\"],\"additionalProperties\":false}" } ], "channel": { "patterns": true, "namespaces": [ { "name": "room_chat_reactions", "pattern": "/rooms/:room_id/reactions", "publication_data_format": "json", "client_publication": { "schemas": ["reaction"], "transform": { "enabled": true, "engine": "jq", "jq": { "program": "{data: {emoji: .data.emoji, message_id: .data.message_id, user_id: .user}, tags: {room: .vars.room_id, user: .user}, idempotency_key: (.user + ":" + .data.message_id + ":" + .data.emoji)}" } }, "exclude_client_info": true }, "allow_publish_for_subscriber": true } ] } } ``` -------------------------------- ### Subscription Refresh Response Example Source: https://centrifugal.dev/docs/server/proxy An example of the expected response from your application backend to Centrifugo regarding subscription expiration. It should include an `expire_at` timestamp. ```json { "result": { "expire_at": 1565436268 } } ``` -------------------------------- ### Send Connect Command via wscat Source: https://centrifugal.dev/docs/transports/uni_websocket Interactive session showing the connection establishment and the initial connect command with token and subscriptions. ```bash ❯ wscat -c "ws://localhost:8000/connection/uni_websocket" Connected (press CTRL+C to quit) > {"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ0ZXN0X3VzZXIiLCJleHAiOjE2NTY1MDMwNDV9.3UYL-UCUBp27TybeBK7Z0OenwdsKwCMRe46fuEjJnzI", "subs": {"abc": {}}} < {"connect":{"client":"bfd28799-b958-4791-b9e9-b011eaef68c1","version":"0.0.0","subs":{"#test_user":{}},"expires":true,"ttl":604407,"ping":25,"session":"57b1287b-44ec-45c8-93fc-696c5294af25"}} ``` -------------------------------- ### RPC Response Payload Example Source: https://centrifugal.dev/docs/server/proxy An example of a successful response payload from the application backend to Centrifugo for an RPC request. It contains a 'result' field with the data. ```json { "result": { "data": {"answer": "2019"} } } ``` -------------------------------- ### Configure Multiple JWKS Providers Source: https://centrifugal.dev/docs/pro/client_authentication Example configuration for setting up multiple JWKS providers, each with a unique issuer and audience. Ensure `client.token.jwks.enabled` is set to `true`. ```json { "client": { "token": { "jwks": { "enabled": true, "providers": [ { "name": "auth0", "enabled": true, "endpoint": "https://tenant.auth0.com/.well-known/jwks.json", "issuer": "https://tenant.auth0.com/", "audience": "centrifugo" }, { "name": "keycloak", "enabled": true, "endpoint": "https://keycloak.example.com/realms/myrealm/protocol/openid-connect/certs", "issuer": "https://keycloak.example.com/realms/myrealm", "audience": "centrifugo" } ] } } } } ``` -------------------------------- ### Disconnect Push Message Example Source: https://centrifugal.dev/docs/transports/uni_client_protocol Example of a 'disconnect' Push frame sent when a connection cannot be established or is closed by the server. The connection is closed after this message is sent. ```json { "disconnect":{ "code":3004, "reason":"internal server error" } } ``` -------------------------------- ### Example JWT Token Output Source: https://centrifugal.dev/docs/getting-started/quickstart This is an example of the output from the `centrifugo gentoken` command. The actual token value will differ based on your configuration's `client.token.hmac_secret_key`. ```text HMAC SHA-256 JWT for user "123722" with expiration TTL 168h0m0s: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM3MjIiLCJleHAiOjE2NTU0NDgyOTl9.mUU9s5kj3yqp-SAEqloGy8QBgsLg0llA7lKUNwtHRnw ``` -------------------------------- ### Install Centrifugo PRO RPM Package (CentOS) Source: https://centrifugal.dev/docs/pro/install_and_run Download the RPM package for Centrifugo PRO and install it using yum. Ensure you have the correct architecture and version. ```bash wget https://github.com/centrifugal/centrifugo-pro/releases/download/v6.7.0/centrifugo-pro-6.7.0-0.x86_64.rpm ``` ```bash sudo yum install centrifugo-pro-6.7.0-0.x86_64.rpm ``` -------------------------------- ### Configure JWKS Providers for Connection and Subscription Tokens Source: https://centrifugal.dev/docs/pro/client_authentication Example configuration showing how to define JWKS providers for both client connection tokens and subscription tokens. ```json { "client": { "token": { "jwks": { "enabled": true, "providers": [{ "name": "auth0_connection", "enabled": true, "endpoint": "https://tenant.auth0.com/.well-known/jwks.json", "issuer": "https://tenant.auth0.com/", "audience": "centrifugo" }] } }, "subscription_token": { "enabled": true, "jwks": { "enabled": true, "providers": [{ "name": "subscription_identity", "enabled": true, "endpoint": "https://tenant.example.com/.well-known/jwks.json", "issuer": "https://tenant.example.com", "audience": "centrifugo" }] } } } } ``` -------------------------------- ### Install Centrifugo PRO DEB Package (Debian/Ubuntu) Source: https://centrifugal.dev/docs/pro/install_and_run Download the DEB package for Centrifugo PRO and install it using dpkg. Ensure you have the correct architecture and version. ```bash wget https://github.com/centrifugal/centrifugo-pro/releases/download/v6.7.0/centrifugo-pro_6.7.0-0_amd64.deb ``` ```bash sudo dpkg -i centrifugo-pro_6.7.0-0_amd64.deb ``` -------------------------------- ### wscat Debugging Example Source: https://centrifugal.dev/docs/transports/websocket Demonstrates a typical debugging session with `wscat` when the `cf_ws_frame_ping_pong` parameter is not enabled. Note the 'no pong' disconnect. ```bash ❯ wscat --connect ws://localhost:8000/connection/websocket Connected (press CTRL+C to quit) > {"id": 1, "connect": {}} < {"id":1,"connect":{"client":"9ac9de4e-5289-4ad6-9aa7-8447f007083e","version":"0.0.0","ping":25,"pong":true}} < {} Disconnected (code: 3012, reason: "no pong") ``` -------------------------------- ### Configure TLS with Certificate and Key Files Source: https://centrifugal.dev/docs/server/tls Use this configuration to enable TLS using your own certificate and key files. Ensure the paths to `key_pem_file` and `cert_pem_file` are correct. ```json { "tls": { "enabled": true, "key_pem_file": "server.key", "cert_pem_file": "server.crt" } } ``` -------------------------------- ### Example of v4 namespace configuration Source: https://centrifugal.dev/docs/getting-started/migration_v4 This is an example of how a namespace configuration might look in Centrifugo v4 after using the provided converter. It reflects the new 'secure by default' approach. ```json { "name": "example-namespace", "allow_subscribe_for_client": true, "allow_publish_for_client": true, "allow_subscribe_for_user": true, "allow_publish_for_user": true, "allow_user_limited_channels": true, "allow_anonymous_connect_without_token": false } ```