### Run NATS Example Source: https://github.com/connecteverything/nats-by-example/blob/main/cmd/nbe/tmpl/client.html Command to run a NATS example. It takes the path to the example as an argument and executes it using the 'nbe' tool. Ensure the 'nbe' tool is installed and accessible in your PATH. ```bash $ nbe run {{.RunPath}} ``` -------------------------------- ### Run NATS Examples with Docker Compose (Go) Source: https://context7.com/connecteverything/nats-by-example/llms.txt The ComposeRunner executes containerized NATS examples using Docker Compose. It manages infrastructure setup, example execution, and cleanup. It supports various configurations like cluster usage, container persistence, and verbose output. ```go package main import ( "fmt" "os" ) func runExample() { runner := ComposeRunner{ Name: "test-run", Repo: "/path/to/nats-by-example", Example: "jetstream/pull-consumer/go", Cluster: false, // Set true for NATS cluster Keep: false, // Set true to keep containers after run Up: false, // Set true to use compose up instead of run Verbose: true, NoAnsi: false, Versions: nil, Stdout: os.Stdout, Stderr: os.Stderr, Stdin: os.Stdin, } imageTag := "nbe/jetstream/pull-consumer/go:latest" // Run the example err := runner.Run(imageTag) if err != nil { fmt.Fprintf(os.Stderr, "Run failed: %v\n", err) os.Exit(1) } // The runner: // 1. Locates appropriate docker-compose.yaml (client > example > language > default) // 2. Creates temporary directory with all required files // 3. Injects IMAGE_TAG environment variable // 4. Pulls dependent images (NATS server) // 5. Executes example container with docker compose run // 6. Streams output to stdout/stderr // 7. Cleans up containers on exit // 8. Enforces 1-minute timeout for safety } ``` -------------------------------- ### NATS Publish-Subscribe Example (CLI) Source: https://github.com/connecteverything/nats-by-example/blob/main/README.md Demonstrates the core NATS publish-subscribe pattern using the NATS CLI client. This example requires Docker and Docker Compose to run. ```sh #!/bin/sh # This script demonstrates the NATS publish-subscribe pattern using the CLI. # It requires Docker and Docker Compose to be installed and running. # To run this example, navigate to the directory and execute: # nbe run messaging/pub-sub/cli # Example Output: # 09:17:59 Published 5 bytes to "greet.joe" # 09:17:59 Subscribing on greet.* # 09:18:00 Published 5 bytes to "greet.joe" # # [1] Received on "greet.joe" # hello # # [2] Received on "greet.pam" ``` -------------------------------- ### Start NATS Foo Publisher Script Source: https://github.com/connecteverything/nats-by-example/blob/main/examples/operations/replace-cluster-nodes/shell/README.md Shell script to start a publisher for the 'foo' stream. This script sends messages to the 'foo' stream, enabling testing of producers and stream handling. ```shell ./scripts/start-foo-publisher.sh ``` -------------------------------- ### Start NATS Cluster Script Source: https://github.com/connecteverything/nats-by-example/blob/main/examples/operations/replace-cluster-nodes/shell/README.md Shell script to start the NATS cluster. This script initializes the cluster, with servers running in the background, PIDs logged, and data/logs stored in specified directories. ```shell ./scripts/start-cluster.sh ``` -------------------------------- ### Docker ImageBuilder for Examples (Go) Source: https://context7.com/connecteverything/nats-by-example/llms.txt This Go code defines an ImageBuilder struct used to construct Docker images for NATS by Example. It takes configuration parameters like the example's repository path and sub-directory, and optionally specific version overrides. The builder handles copying Dockerfiles and example code, executing the Docker build process, and returning the generated image tag. ```go package main import ( "fmt" "os" ) func buildExample() { builder := ImageBuilder{ Name: "my-example", Repo: "/path/to/nats-by-example", Example: "messaging/pub-sub/go", Verbose: true, Versions: nil, // Optional version overrides Stdout: os.Stdout, Stderr: os.Stderr, } // Build the image imageTag, err := builder.Run() if err != nil { fmt.Fprintf(os.Stderr, "Build failed: %v\n", err) os.Exit(1) } fmt.Printf("Built image: %s\n", imageTag) // Output example: nbe/messaging/pub-sub/go:a3f2c1d8 } // The builder: // 1. Creates temporary build directory // 2. Copies default language Dockerfile and dependencies // 3. Copies example-specific files // 4. Optionally replaces version strings // 5. Executes docker build with generated tag // 6. Returns image tag for use with ComposeRunner ``` -------------------------------- ### NATS Publish-Subscribe Example (Go) Source: https://github.com/connecteverything/nats-by-example/blob/main/README.md Implements the core NATS publish-subscribe pattern using the Go client library. This example is designed to run within a containerized environment managed by Docker and Docker Compose. ```go // main.go package main import ( "log" "os" "os/signal" "syscall" "time" "github.com/nats-io/nats.go" ) func main() { // Connect to NATS server url := nats.DefaultURL if len(os.Args) > 1 { url = os.Args[1] } nc, err := nats.Connect(url) if err != nil { log.Fatalf("Error connecting to NATS: %v", err) } defer nc.Close() log.Printf("Connected to NATS at %s", nc.ConnectedUrl()) // Subscribe to messages sub, err := nc.Subscribe("greet.*", func(msg *nats.Msg) { log.Printf("Received a message: %s", string(msg.Data)) }) if err != nil { log.Fatalf("Error subscribing to subject: %v", err) } // Publish messages periodically go func() { for i := 0; i < 10; i++ { subject := "greet.joe" message := "hello" err := nc.Publish(subject, []byte(message)) if err != nil { log.Printf("Error publishing message: %v", err) } log.Printf("Published [%s] to '%s'", message, subject) time.Sleep(1 * time.Second) } }() // Wait for termination signal stopChan := make(chan os.Signal, 1) signal.Notify(stopChan, syscall.SIGINT, syscall.SIGTERM) <-stopChan log.Println("Shutting down...") // Drain the connection to ensure all messages are sent/received log.Println("Draining connection...") err = nc.Drain() if err != nil { log.Printf("Error draining connection: %v", err) } log.Println("Exiting.") sub.Unsubscribe() } ``` -------------------------------- ### Start NATS Foo Subscriber Script Source: https://github.com/connecteverything/nats-by-example/blob/main/examples/operations/replace-cluster-nodes/shell/README.md Shell script to start a subscriber for the 'foo-c' consumer. This script receives messages from the 'foo-c' consumer, demonstrating message acknowledgment and processing. ```shell ./scripts/start-foo-subscriber.sh ``` -------------------------------- ### NATS JetStream Key-Value Operations (Go) Source: https://context7.com/connecteverything/nats-by-example/llms.txt Demonstrates JetStream-based key-value store operations in Go. It covers creating a KV bucket, performing Put and Get operations with revision tracking, implementing optimistic concurrency control using Update, and setting up watchers for key changes. This example requires a running NATS server with JetStream enabled. ```go package main import ( "context" "fmt" "os" "time" "github.com/nats-io/nats.go" "github.com/nats-io/nats.go/jetstream" ) func main() { url := os.Getenv("NATS_URL") if url == "" { url = nats.DefaultURL } nc, err := nats.Connect(url) if err != nil { panic(err) } defer nc.Drain() js, err := jetstream.New(nc) if err != nil { panic(err) } ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() // Create KV bucket kv, err := js.CreateKeyValue(ctx, jetstream.KeyValueConfig{ Bucket: "profiles", }) if err != nil { panic(err) } // Put and Get with revision tracking kv.Put(ctx, "sue.color", []byte("blue")) entry, err := kv.Get(ctx, "sue.color") if err != nil { panic(err) } fmt.Printf("%s @ %d -> %q\n", entry.Key(), entry.Revision(), string(entry.Value())) // Output: sue.color @ 1 -> "blue" // Update value - revision increments kv.Put(ctx, "sue.color", []byte("green")) entry, err = kv.Get(ctx, "sue.color") if err != nil { panic(err) } fmt.Printf("%s @ %d -> %q\n", entry.Key(), entry.Revision(), string(entry.Value())) // Output: sue.color @ 2 -> "green" // Optimistic concurrency control with Update // This will fail because we expect revision 1 but current is 2 _, err = kv.Update(ctx, "sue.color", []byte("red"), 1) fmt.Printf("expected error: %s\n", err) // Update with correct revision succeeds _, err = kv.Update(ctx, "sue.color", []byte("red"), 2) if err != nil { panic(err) } entry, err = kv.Get(ctx, "sue.color") if err != nil { panic(err) } fmt.Printf("%s @ %d -> %q\n", entry.Key(), entry.Revision(), string(entry.Value())) // Output: sue.color @ 3 -> "red" // Watch for changes (supports wildcards) w, err := kv.Watch(ctx, "sue.*") if err != nil { panic(err) } defer w.Stop() // Put new value kv.Put(ctx, "sue.color", []byte("purple")) // Receive update from watcher kve := <-w.Updates() fmt.Printf("%s @ %d -> %q (op: %s)\n", kve.Key(), kve.Revision(), string(kve.Value()), kve.Operation()) // Skip nil marker <-w.Updates() kve = <-w.Updates() fmt.Printf("%s @ %d -> %q (op: %s)\n", kve.Key(), kve.Revision(), string(kve.Value()), kve.Operation()) // Watch receives updates for all matching keys kv.Put(ctx, "sue.food", []byte("pizza")) kve = <-w.Updates() fmt.Printf("%s @ %d -> %q (op: %s)\n", kve.Key(), kve.Revision(), string(kve.Value()), kve.Operation()) // Delete key kv.Delete(ctx, "sue.color") kve = <-w.Updates() fmt.Printf("%s @ %d (op: %s)\n", kve.Key(), kve.Revision(), kve.Operation()) // Output shows operation: DEL } ``` -------------------------------- ### NATS Publish-Subscribe Example (Python) Source: https://github.com/connecteverything/nats-by-example/blob/main/README.md Illustrates the NATS publish-subscribe mechanism using the Python client. This example is intended to be run within a containerized environment using Docker and Docker Compose. ```python # main.py import asyncio import os import signal from nats.aio.client import Client as NATSClient async def main(): nc = NATSClient() # Connect to NATS server url = os.environ.get("NATS_URL", "nats://localhost:4222") try: await nc.connect(url) except Exception as e: print(f"Error connecting to NATS: {e}") return print(f"Connected to NATS at {nc.connected_url.netloc}...") async def message_handler(msg): subject = msg.subject data = msg.data.decode() print(f"Received a message on '{subject}': {data}") # Subscribe to messages sub = await nc.subscribe("greet.*", cb=message_handler) # Publish messages periodically async def publisher(): for i in range(10): subject = "greet.joe" message = "hello" try: await nc.publish(subject, message.encode()) print(f"Published [{message}] to '{subject}'") except Exception as e: print(f"Error publishing message: {e}") await asyncio.sleep(1) asyncio.create_task(publisher()) # Keep the connection alive until interrupted def signal_handler(): print("Shutting down...") asyncio.create_task(nc.drain()) loop = asyncio.get_event_loop() for sig in (signal.SIGINT, signal.SIGTERM): loop.add_signal_handler(sig, signal_handler) if __name__ == '__main__': asyncio.run(main()) ``` -------------------------------- ### Start NATS Bar Publisher Script Source: https://github.com/connecteverything/nats-by-example/blob/main/examples/operations/replace-cluster-nodes/shell/README.md Shell script to start a publisher for the 'bar' stream. This script generates messages for the 'bar' stream, useful for testing stream ingestion and consumer behavior. ```shell ./scripts/start-bar-publisher.sh ``` -------------------------------- ### NATS Example Directory Structure and Metadata Source: https://context7.com/connecteverything/nats-by-example/llms.txt This YAML structure defines the organization of NATS examples across different categories and languages. Meta.yaml files at various levels provide titles and descriptions, aiding in documentation generation and example discovery. ```yaml # Root meta.yaml - defines category order categories: - messaging - jetstream - kv - services - auth - operations # Category meta.yaml (e.g., examples/messaging/meta.yaml) title: "Core Messaging Patterns" description: "Fundamental NATS messaging patterns including pub-sub and request-reply" examples: - pub-sub - request-reply - queue-groups # Example meta.yaml (e.g., examples/messaging/pub-sub/meta.yaml) title: "Publish-Subscribe" description: "Basic pub-sub messaging with wildcard subscriptions" # Directory structure: # examples/ # messaging/ # meta.yaml # pub-sub/ # meta.yaml # go/ # main.go # go.mod # python/ # main.py # requirements.txt # cli/ # main.sh ``` -------------------------------- ### Start NATS Bar Subscriber Script Source: https://github.com/connecteverything/nats-by-example/blob/main/examples/operations/replace-cluster-nodes/shell/README.md Shell script to start a subscriber for the 'bar-c' consumer. This script listens for messages sent to the 'bar-c' consumer, useful for testing the end-to-end message flow. ```shell ./scripts/start-bar-subscriber.sh ``` -------------------------------- ### Connect to NATS Server (Elixir) Source: https://github.com/connecteverything/nats-by-example/blob/main/examples/services/intro/elixir/output.txt Establishes a connection to the NATS server. It takes a host and port as configuration. This is a prerequisite for sending any NATS messages. ```elixir 00:31:40.857 [debug] connecting to %{port: 4222, host: "nats"} ``` -------------------------------- ### Create NATS JetStream Stream and Publish Messages Source: https://github.com/connecteverything/nats-by-example/blob/main/examples/jetstream/workqueue-stream/rust/output.txt This example demonstrates how to create a NATS JetStream stream named 'EVENTS' with subjects matching 'events.>' and then publish messages to this stream. It also shows how to retrieve stream information before and after adding a consumer, highlighting the consumer count. This process is fundamental for setting up a message ingestion pipeline. ```shell nats context save my-context nats stream add EVENTS --subjects 'events.>' --retention workqueue nats context use my-context nats js pub EVENTS 'events.us.page_loaded' '{"user": "user1", "page": "/home"}' nats js pub EVENTS 'events.us.input_focused' '{"user": "user1", "field": "username"}' nats js pub EVENTS 'events.eu.mouse_clicked' '{"user": "user2", "button": "left"}' ``` -------------------------------- ### Go Publish-Subscribe with Wildcards Source: https://context7.com/connecteverything/nats-by-example/llms.txt Demonstrates the basic publish-subscribe pattern in Go using NATS. Publishers send messages to subjects, and subscribers receive them. This example shows how to use wildcard subscriptions (e.g., 'greet.*') to match multiple subjects flexibly. ```go package main import ( "fmt" "os" "time" "github.com/nats-io/nats.go" ) func main() { // Connect to NATS server url := os.Getenv("NATS_URL") if url == "" { url = nats.DefaultURL } nc, err := nats.Connect(url) if err != nil { panic(err) } defer nc.Drain() // Subscribe with wildcard - greet.* matches greet.joe, greet.pam, etc. sub, err := nc.SubscribeSync("greet.*") if err != nil { panic(err) } // Publish messages to different subjects nc.Publish("greet.joe", []byte("hello")) nc.Publish("greet.pam", []byte("hello")) nc.Publish("greet.bob", []byte("hello")) // Receive messages for i := 0; i < 3; i++ { msg, err := sub.NextMsg(10 * time.Millisecond) if err == nil { fmt.Printf("msg data: %q on subject %q\n", string(msg.Data), msg.Subject) } } } // Expected output: // msg data: "hello" on subject "greet.joe" // msg data: "hello" on subject "greet.pam" // msg data: "hello" on subject "greet.bob" ``` -------------------------------- ### Create NATS Consumers Script Source: https://github.com/connecteverything/nats-by-example/blob/main/examples/operations/replace-cluster-nodes/shell/README.md Shell script to create consumers for the NATS streams. It sets up two push consumers, 'foo-c' and 'bar-c', for their respective streams. ```shell ./scripts/create-consumers.sh ``` -------------------------------- ### Watch NATS Foo Consumer Script Source: https://github.com/connecteverything/nats-by-example/blob/main/examples/operations/replace-cluster-nodes/shell/README.md Shell script to monitor the 'foo-c' NATS consumer. This allows observation of messages being received and processed by this specific consumer. ```shell ./scripts/watch-foo-consumer.sh ``` -------------------------------- ### Parse Code Comments for Documentation Generation (Go) Source: https://context7.com/connecteverything/nats-by-example/llms.txt This Go code illustrates how documentation is extracted from comments within example source files. It identifies different comment types (single-line, multi-line, code blocks, break markers) and supports various programming languages. ```go // Code blocks are identified by type: // - SingleLineCommentBlock: // or # comments (converted to prose) // - MultiLineCommentBlock: /* */ comments (converted to prose) // - CodeBlock: Actual code (syntax highlighted) // - BreakBlock: Special marker for section separation // Example Go code with documentation: func example() { // This comment becomes documentation prose. // Multiple single-line comments form a block. nc, _ := nats.Connect(nats.DefaultURL) // // The break marker above creates a visual separation // in the rendered documentation. sub, _ := nc.SubscribeSync("subject") msg, _ := sub.NextMsg(time.Second) } // The parser handles multiple languages: // - Go, Java, Rust, C, JavaScript: // and /* */ style // - Python, Ruby, Elixir, Crystal: # style // - Shell scripts: # style (but ignores shebang #!) // Supported language identifiers: // go, python, rust, java, dotnet, csharp, deno, websocket, // c, ruby, elixir, crystal, cli, shell // Main file conventions by language: // Go: main.go // Python: main.py // Rust: main.rs // Java: Main.java // C#: Main.cs // JavaScript/Deno: main.js // Shell/CLI: main.sh // C: main.c // Crystal: main.cr // Elixir: main.exs ``` -------------------------------- ### Create NATS JetStream Consumer with Subject Filtering Source: https://github.com/connecteverything/nats-by-example/blob/main/examples/jetstream/workqueue-stream/rust/output.txt This example shows how to create two consumers for the 'EVENTS' stream: 'us_consumer' for 'events.us.>' and 'eu_consumer' for 'events.eu.>'. It illustrates how to handle JetStream errors, specifically when attempting to create overlapping consumers on a workqueue stream, and demonstrates successful consumer creation with distinct subject filters. The example also shows message delivery to the respective consumers. ```shell # Attempt to create an overlapping consumer (will fail) nats js consumer add EVENTS us_consumer --filter 'events.us.>' --durable us_consumer # Create a new consumer for US events nats js consumer add EVENTS us_consumer --filter 'events.us.>' --durable us_consumer # Create a new consumer for EU events nats js consumer add EVENTS eu_consumer --filter 'events.eu.>' --durable eu_consumer # Publish additional messages to test consumer delivery nats js pub EVENTS 'events.us.page_loaded' '{"user": "user3", "page": "/dashboard"}' nats js pub EVENTS 'events.us.input_focused' '{"user": "user3", "field": "password"}' nats js pub EVENTS 'events.eu.mouse_clicked' '{"user": "user4", "button": "right"}' nats js pub EVENTS 'events.eu.page_loaded' '{"user": "user4", "page": "/settings"}' # To view messages, you would typically use 'nats js sub' ``` -------------------------------- ### Go Request-Reply Pattern Source: https://context7.com/connecteverything/nats-by-example/llms.txt Illustrates the synchronous request-reply pattern in Go using NATS. A client sends a request and waits for a single response from a service. NATS handles this efficiently by pairing publish-subscribe operations. This example shows setting up a service and sending requests to it. ```go package main import ( "fmt" "os" "time" "github.com/nats-io/nats.go" ) func main() { url := os.Getenv("NATS_URL") if url == "" { url = nats.DefaultURL } nc, err := nats.Connect(url) if err != nil { panic(err) } defer nc.Drain() // Create a service handler that responds to requests sub, err := nc.Subscribe("greet.*", func(msg *nats.Msg) { // Extract name from subject (everything after "greet.") name := msg.Subject[6:] // Respond with personalized greeting msg.Respond([]byte("hello, " + name)) }) if err != nil { panic(err) } // Send requests and receive replies rep, err := nc.Request("greet.joe", nil, time.Second) if err == nil { fmt.Println(string(rep.Data)) // "hello, joe" } rep, err = nc.Request("greet.sue", nil, time.Second) if err == nil { fmt.Println(string(rep.Data)) // "hello, sue" } // Test service unavailability sub.Unsubscribe() _, err = nc.Request("greet.joe", nil, time.Second) if err != nil { fmt.Println("Error:", err) // timeout or no responders } } ``` -------------------------------- ### Watch NATS Streams Script Source: https://github.com/connecteverything/nats-by-example/blob/main/examples/operations/replace-cluster-nodes/shell/README.md Shell script to monitor the NATS streams. This script helps in observing the state and message flow within the 'foo' and 'bar' streams. ```shell ./scripts/watch-streams.sh ``` -------------------------------- ### Create NATS JetStream Stream Source: https://github.com/connecteverything/nats-by-example/blob/main/examples/jetstream/workqueue-stream/crystal/output.txt Creates a new NATS JetStream stream named 'EVENTS' with a single shard and a replica count of 1. This is a prerequisite for publishing messages. Requires a connection to a NATS server with JetStream enabled. ```go package main import ( "log" "os" "github.com/nats-io/nats.go" "github.com/nats-io/nats.go/jetstream" ) func main() { natsURL := os.Getenv("NATS_URL") if natsURL == "" { natsURL = nats.DefaultURL } nc, err := nats.Connect(natsURL) if err != nil { log.Fatalf("Error connecting to NATS: %v", err) } sdefer nc.Close() jsc, err := nc.JetStream() if err != nil { log.Fatalf("Error getting JetStream context: %v", err) } streamName := "EVENTS" _, err = jsc.CreateStream(jetstream.Gubbins{ Name: streamName, Subjects: []string{"events.*"}, Replicas: 1, }) if err != nil { log.Printf("Stream '%s' already exists or error creating: %v", streamName, err) } else { log.Printf("Created stream '%s'", streamName) } } ``` -------------------------------- ### SQL Database Operations Source: https://github.com/connecteverything/nats-by-example/blob/main/examples/integrations/debezium/cli/output.txt This snippet illustrates basic SQL commands for database manipulation including table creation, data insertion, updates, and deletions. These are fundamental operations for managing relational database content. ```sql CREATE TABLE INSERT 0 1 INSERT 0 1 UPDATE 1 UPDATE 1 DELETE 1 CREATE TABLE INSERT 0 1 ``` -------------------------------- ### Publish Messages to NATS JetStream Stream Source: https://github.com/connecteverything/nats-by-example/blob/main/examples/jetstream/workqueue-stream/crystal/output.txt Publishes a specified number of messages to a NATS JetStream stream. This is a fundamental operation for populating a stream with data. No specific dependencies are mentioned, but a connection to a NATS server with JetStream enabled is required. ```go package main import ( "log" "os" "time" "github.com/nats-io/nats.go" ) func main() { natsURL := os.Getenv("NATS_URL") if natsURL == "" { natsURL = nats.DefaultURL } nc, err := nats.Connect(natsURL) if err != nil { log.Fatalf("Error connecting to NATS: %v", err) } sdefer nc.Close() jsc, err := nc.JetStream() if err != nil { log.Fatalf("Error getting JetStream context: %v", err) } streamName := "EVENTS" numMessages := 3 log.Printf("Publishing %d messages to stream '%s'", numMessages, streamName) for i := 1; i <= numMessages; i++ { message := []bytef("Message %d", i) _, err := jsc.Publish(streamName, message) if err != nil { log.Printf("Error publishing message %d: %v", i, err) continue } log.Printf("Published: %s", message) time.Sleep(100 * time.Millisecond) } log.Println("Finished publishing messages.") } ``` -------------------------------- ### GET /minmax.min Source: https://github.com/connecteverything/nats-by-example/blob/main/examples/services/intro/deno/output.txt Retrieves the minimum value from a JSON serialized JSON array. ```APIDOC ## GET /minmax.min ### Description This endpoint accepts a JSON serialized JSON array as input and returns the smallest value found within that array. ### Method GET ### Endpoint /minmax.min ### Parameters #### Query Parameters - **data** (string) - Required - A JSON serialized JSON array (e.g., `"[1, 5, 2, 8]"`). ### Request Example ```json { "data": "[1, 5, 2, 8]" } ``` ### Response #### Success Response (200) - **min** (number) - The minimum value found in the input array. #### Response Example ```json { "min": 1 } ``` ``` -------------------------------- ### Retrieve Service Statistics (Elixir) Source: https://github.com/connecteverything/nats-by-example/blob/main/examples/services/intro/elixir/output.txt Fetches and displays statistics for a NATS service. The output is a map containing details about endpoints, processing times, errors, and service metadata. ```elixir Service Stats: Eylül "endpoints" => [ Eylül "average_processing_time" => 914000, "name" => "add", "num_errors" => 0, "num_requests" => 1, "processing_time" => 914000, "queue_group" => "q", "subject" => "calc.add" Eylül Eylül "average_processing_time" => 263500, "name" => "sub", "num_errors" => 1, "num_requests" => 1, "processing_time" => 527000, "queue_group" => "q", "subject" => "calc.sub" Eylül ], "id" => "7B5SUkuPcoVZj7Fb", "metadata" => nil, "name" => "exampleservice", "started" => "2023-10-25T00:31:41.165877Z", "type" => "io.nats.micro.v1.stats_response", "version" => "0.1.0" ] ``` -------------------------------- ### GET /minmax.max Source: https://github.com/connecteverything/nats-by-example/blob/main/examples/services/intro/deno/output.txt Retrieves the maximum value from a JSON serialized JSON array. ```APIDOC ## GET /minmax.max ### Description This endpoint accepts a JSON serialized JSON array as input and returns the largest value found within that array. ### Method GET ### Endpoint /minmax.max ### Parameters #### Query Parameters - **data** (string) - Required - A JSON serialized JSON array (e.g., `"[1, 5, 2, 8]"`). ### Request Example ```json { "data": "[1, 5, 2, 8]" } ``` ### Response #### Success Response (200) - **max** (number) - The maximum value found in the input array. #### Response Example ```json { "max": 8 } ``` ``` -------------------------------- ### Perform Addition Operation (Elixir) Source: https://github.com/connecteverything/nats-by-example/blob/main/examples/services/intro/elixir/output.txt Sends a request to the 'calc.add' subject for an addition operation. The input is a string, and the expected output is a result. This snippet demonstrates a successful addition request. ```elixir Calculator adding..."add this!" Add result: 42 ``` -------------------------------- ### Watch NATS Bar Consumer Script Source: https://github.com/connecteverything/nats-by-example/blob/main/examples/operations/replace-cluster-nodes/shell/README.md Shell script to monitor the 'bar-c' NATS consumer. This script is used to observe the message consumption activity for the 'bar' stream's consumer. ```shell ./scripts/watch-bar-consumer.sh ``` -------------------------------- ### Create NATS Streams Script Source: https://github.com/connecteverything/nats-by-example/blob/main/examples/operations/replace-cluster-nodes/shell/README.md Shell script to set up streams within the NATS cluster. It creates two streams, 'foo' and 'bar', with different configurations for storage and replication, including file-based and memory-based options. ```shell ./scripts/create-streams.sh ``` -------------------------------- ### Watch NATS Servers Script Source: https://github.com/connecteverything/nats-by-example/blob/main/examples/operations/replace-cluster-nodes/shell/README.md Shell script to monitor the NATS servers. This is intended to be run in a separate shell to observe the state and activity of the cluster nodes during operation and migration. ```shell ./scripts/watch-servers.sh ``` -------------------------------- ### NATS Claim Request for Authorization Source: https://github.com/connecteverything/nats-by-example/blob/main/examples/auth/callout/java/output.txt This snippet details a NATS claim request used for user authorization. It contains information about the client, server, connection options, and NATS-specific client details. This request is typically sent to the NATS server for authentication. ```json { "aud": "nats-authorization-request", "jti": "XV5QMQMPXKPXKUJ3JIITLLE7MM6F4AWOQ5W3KPWUTUBNKQ6MHTJQ", "iat": 1717863532, "iss": "NAMSQRSU2DRUQEL2SXVCD4QOUUSYPLN4HOGNVBKYHZUIZT25MGX463GB", "sub": "ABJHLOVMPA4CI6R5KLNGOB4GSLNIY7IOUPAJC4YFNDLQVIOBYQGUWVLA", "exp": 1717863534, "nats": { "client_info": { "kind": "Client", "host": "127.0.0.1", "name": "NATS CLI Version development", "id": 10, "type": "nats", "user": "bob" }, "connect_opts": { "protocol": 1, "pass": "bob", "name": "NATS CLI Version development", "lang": "go", "user": "bob", "version": "1.30.0" }, "server_id": { "name": "NAMSQRSU2DRUQEL2SXVCD4QOUUSYPLN4HOGNVBKYHZUIZT25MGX463GB", "host": "0.0.0.0", "id": "NAMSQRSU2DRUQEL2SXVCD4QOUUSYPLN4HOGNVBKYHZUIZT25MGX463GB", "version": "2.10.4" }, "type": "authorization_request", "version": 2, "user_nkey": "UAWXFWQIM6SNBZQUNMPQKWWSPRQZM2BBNPQ45WACHIA2ATU7B65YNHHO" } } ``` -------------------------------- ### NATS Stream Info (With Consumers) Source: https://github.com/connecteverything/nats-by-example/blob/main/examples/jetstream/interest-stream/rust/output.txt Illustrates the information retrieved for a NATS stream that has an active consumer. This output includes the same configuration details as a stream without consumers, plus updated state information reflecting messages processed and the presence of consumers. It highlights how consumer activity impacts stream state. ```Go Info { config: Config { name: "EVENTS", max_bytes: -1, max_messages: -1, max_messages_per_subject: -1, discard: Old, discard_new_per_subject: false, subjects: [ "events.வைக்", ], retention: Interest, max_consumers: -1, max_age: 0ns, max_message_size: -1, storage: File, num_replicas: 1, no_ack: false, duplicate_window: 120s, template_owner: "", sealed: false, description: None, allow_rollup: false, deny_delete: false, deny_purge: false, republish: None, allow_direct: false, mirror_direct: false, mirror: None, sources: None, metadata: {}, subject_transform: None, compression: Some( None, ), consumer_limits: None, first_sequence: None, }, created: 2023-10-23 16:19:19.91124471 +00:00:00, state: State { messages: 2, bytes: 100, first_sequence: 4, first_timestamp: 2023-10-23 16:19:19.914922627 +00:00:00, last_sequence: 5, last_timestamp: 2023-10-23 16:19:19.915123835 +00:00:00, consumer_count: 1, }, cluster: Some( ClusterInfo { name: None, leader: Some( "NAJOLBYQCDR5GVGWQBLW3JJ27IDTTEAG6XXQ7ZXHZVXBKWKBMVFOILR7", ), replicas: [], }, ), mirror: None, sources: [], } ``` -------------------------------- ### Stop NATS Cluster Script Source: https://github.com/connecteverything/nats-by-example/blob/main/examples/operations/replace-cluster-nodes/shell/README.md Shell script to gracefully stop the NATS cluster. This script ensures all running NATS servers and associated processes are terminated cleanly. ```shell ./scripts/stop-cluster.sh ``` -------------------------------- ### Handle Service Error (Elixir) Source: https://github.com/connecteverything/nats-by-example/blob/main/examples/services/intro/elixir/output.txt Illustrates handling a service error response from a NATS request. The output indicates a service error with a specific message and returns an {:ok, %{...}} tuple. ```elixir Fail result: {:ok, %{body: "service error: \"woopsy\"", gnat: #PID<0.688.0>, topic: "_INBOX.bOwa3Sr6ehoybiWX.W2zyLIUHXMXMC3db", reply_to: nil}} ``` -------------------------------- ### Perform Subtraction Operation (Elixir) Source: https://github.com/connecteverything/nats-by-example/blob/main/examples/services/intro/elixir/output.txt Sends a request to the 'calc.sub' subject for a subtraction operation. The input is a string, and the expected output is a result. This snippet demonstrates a successful subtraction request. ```elixir Calculator subtracting..."subtract this!" Subtract result: 24 ``` -------------------------------- ### NATS JWT Authorization Response Handling Source: https://github.com/connecteverything/nats-by-example/blob/main/examples/auth/callout/java/output.txt This snippet shows the structure of a JWT authorization response from NATS. It includes details about the issuer, audience, subject, and NATS-specific claims like publish and subscribe permissions. This response is crucial for establishing authenticated connections. ```json { "aud": "APP", "jti": "DDMPOZWJ4EKMY2ATU6RRUDX2HFCZPHB5ZV4OJVE7ZLTUPHSSILTQ", "iat": 1717863532, "iss": "ABJHLOVMPA4CI6R5KLNGOB4GSLNIY7IOUPAJC4YFNDLQVIOBYQGUWVLA", "name": "bob", "sub": "UC3KJ6GV2JLG2UQCWEVRXRM5WSZSWO6NOXPP7U3PR5JWQLHL4X6G4FNL", "nats": { "type": "user", "version": 2, "pub": { "allow": [ "bob.ější" ] }, "sub": { "allow": [ "bob.ější" ] }, "resp": { "max": 1 }, "subs": -1, "data": -1, "payload": -1 } } ``` ```json { "aud": "APP", "jti": "LV2X6BNLJGMLVEKZN45X625GW5LHT7TLZEEFM5K6K57J5BSRV4BQ", "iat": 1717863532, "iss": "ABJHLOVMPA4CI6R5KLNGOB4GSLNIY7IOUPAJC4YFNDLQVIOBYQGUWVLA", "name": "bob", "sub": "UAWXFWQIM6SNBZQUNMPQKWWSPRQZM2BBNPQ45WACHIA2ATU7B65YNHHO", "nats": { "type": "user", "version": 2, "pub": { "allow": [ "bob.ější" ] }, "sub": { "allow": [ "bob.ější" ] }, "resp": { "max": 1 }, "subs": -1, "data": -1, "payload": -1 } } ``` -------------------------------- ### Inspect NATS JetStream Stream State Source: https://github.com/connecteverything/nats-by-example/blob/main/examples/jetstream/limits-stream/crystal/output.txt This snippet shows how to inspect the state of a NATS JetStream stream. It provides details about the stream's size, message count, sequence numbers, and timestamps. No external dependencies are required beyond a NATS client library. ```ruby NATS::JetStream::API::V1::StreamState( @bytes=648, @consumer_count=0, @first_seq=2, @first_ts=2023-03-16 13:36:38.572160660 UTC, @last_seq=11, @last_ts=2023-03-16 13:36:38.573442838 UTC, @messages=10) ``` -------------------------------- ### Migrate NATS Cluster Script Source: https://github.com/connecteverything/nats-by-example/blob/main/examples/operations/replace-cluster-nodes/shell/README.md Shell script to execute the cluster node migration process. This script orchestrates the addition, lame-ducking, and removal of nodes with configurable wait times to minimize downtime. ```shell ./scripts/migrate-cluster.sh ``` -------------------------------- ### NATS Stream Subjects Source: https://github.com/connecteverything/nats-by-example/blob/main/examples/integrations/debezium/cli/output.txt This section displays the subjects present within a NATS stream named 'DebeziumStream'. It shows the count of messages for each subject, indicating data distribution and topics being monitored. ```text ╭─────────────────────────────────────────────────────────────────╮ │ 2 Subjects in stream DebeziumStream │ ├───────────────────────┬───────┬─────────────────────────┬───────┤ │ Subject │ Count │ Subject │ Count │ ├───────────────────────┼───────┼─────────────────────────┼───────┤ │ postgres.public.books │ 1 │ postgres.public.profile │ 5 │ ╰───────────────────────┴───────┴─────────────────────────┴───────╯ ``` -------------------------------- ### Add Node Script for NATS Cluster Source: https://github.com/connecteverything/nats-by-example/blob/main/examples/operations/replace-cluster-nodes/shell/README.md Shell script to add a new node to the NATS cluster. This is a crucial step in the node replacement process, preparing the cluster to accept a new member. ```shell ./scripts/add-node.sh n3 ``` -------------------------------- ### Consume Messages with Subject Filtering (NATS JetStream) Source: https://github.com/connecteverything/nats-by-example/blob/main/examples/jetstream/workqueue-stream/crystal/output.txt Subscribes to messages on specific subjects ('events.us.*' and 'events.eu.*') using NATS JetStream consumers. This demonstrates how to filter messages based on subjects. The code snippet shows how to set up consumers that listen for messages published to these filtered subjects and prints the received message subject. Requires a NATS connection, an existing stream, and relevant consumers. ```go package main import ( "log" "os" "time" "github.com/nats-io/nats.go" "github.com/nats-io/nats.go/jetstream" ) func main() { natsURL := os.Getenv("NATS_URL") if natsURL == "" { natsURL = nats.DefaultURL } nc, err := nats.Connect(natsURL) if err != nil { log.Fatalf("Error connecting to NATS: %v", err) } sdefer nc.Close() jsc, err := nc.JetStream() if err != nil { log.Fatalf("Error getting JetStream context: %v", err) } streamName := "EVENTS" // US Consumer usConsumer, err := jsc.CreateConsumer(streamName, jetstream.Gubbins{ DurableName: "us-processor", DeliverPolicy: jetstream.DeliverAll, FilterSubject: "events.us.*", }) if err != nil { log.Printf("Error creating US consumer: %v", err) } else { log.Println("US Consumer created/found.") } // EU Consumer euConsumer, err := jsc.CreateConsumer(streamName, jetstream.Gubbins{ DurableName: "eu-processor", DeliverPolicy: jetstream.DeliverAll, FilterSubject: "events.eu.*", }) if err != nil { log.Printf("Error creating EU consumer: %v", err) } else { log.Println("EU Consumer created/found.") } // Subscribe to US consumer subUS, err := usConsumer.Consume(func(msg jetstream.Msg) { log.Printf("US subscription got: %s", msg.Subject()) msg.AckSync() }) if err != nil { log.Fatalf("Error subscribing US consumer: %v", err) } defer subUS.Unsubscribe() // Subscribe to EU consumer subEU, err := euConsumer.Consume(func(msg jetstream.Msg) { log.Printf("EU subscription got: %s", msg.Subject()) msg.AckSync() }) if err != nil { log.Fatalf("Error subscribing EU consumer: %v", err) } defer subEU.Unsubscribe() log.Println("Consumers are now listening for messages...") // Keep the program running to receive messages select {} } ``` -------------------------------- ### NATS Stream Info (No Consumers) Source: https://github.com/connecteverything/nats-by-example/blob/main/examples/jetstream/interest-stream/rust/output.txt Displays the configuration and state of a NATS stream when no consumers are attached. It shows details like stream name, subjects, retention policy, storage type, and current message counts. This is useful for understanding the baseline state of a stream. ```Go Info { config: Config { name: "EVENTS", max_bytes: -1, max_messages: -1, max_messages_per_subject: -1, discard: Old, discard_new_per_subject: false, subjects: [ "events.வைக்", ], retention: Interest, max_consumers: -1, max_age: 0ns, max_message_size: -1, storage: File, num_replicas: 1, no_ack: false, duplicate_window: 120s, template_owner: "", sealed: false, description: None, allow_rollup: false, deny_delete: false, deny_purge: false, republish: None, allow_direct: false, mirror_direct: false, mirror: None, sources: None, metadata: {}, subject_transform: None, compression: Some( None, ), consumer_limits: None, first_sequence: None, }, created: 2023-10-23 16:19:19.91124471 +00:00:00, state: State { messages: 0, bytes: 0, first_sequence: 4, first_timestamp: 2023-10-23 16:19:19.91269846 +00:00:00, last_sequence: 3, last_timestamp: 2023-10-23 16:19:19.91269846 +00:00:00, consumer_count: 0, }, cluster: Some( ClusterInfo { name: None, leader: Some( "NAJOLBYQCDR5GVGWQBLW3JJ27IDTTEAG6XXQ7ZXHZVXBKWKBMVFOILR7", ), replicas: [], }, ), mirror: None, sources: [], } ```