Сопоставление и преобразование тем
Фильтр выбирает данные, не меняя тему. Сопоставление переписывает её в трёх местах:
- На входе — subject transform потока меняет сохраняемую тему.
- На выходе — republish выдаёт сохранённое в новые темы обычным подписчикам без потребителя.
- При копировании — преобразования зеркала или источника, см. Зеркала и источники.
Язык преобразований общий.
Язык преобразований
Пара source → destination: исходный фильтр с */>, целевой шаблон с совпавшими токенами:
{{wildcard(1)}}— токен первого*,{{wildcard(2)}}— второго; старый$1эквивалентен.{{partition(n, 1)}}хеширует первый токен в0…n-1. Значение всегда попадает в один раздел.- Конечный
>переносит остаток без изменений: orders.> → dash.orders.>. {{split(1, -)}},{{splitfromleft(1, 3)}}делят токен по разделителю без кавычек, кроме точки, либо по позиции символа.
Полный список — в ADR-30 ниже. Обычно нужны wildcard и partition; split, splitfromleft/right и slicefromleft/right изменяют отдельный токен.
Проверьте без потока через nats server mappings, передав источник, цель и тему:
nats server mappings "orders.*" "orders.{{wildcard(1)}}.archived" orders.created
orders.created.archived
Преобразование на входе
Subject transform меняет тему при сохранении. Подписки потока прежние: совпавшее преобразуется, остальное сохраняется как есть. Сообщения не отбрасываются.
Для детерминированного разбиения оставьте ORDERS и создайте временный поток ingest.*. Токен заказчика хешируется в три раздела:
- CLI
- JavaScript/TypeScript
- Go
- Python
- Java
- Rust
- C#/.NET
- C
#!/bin/bash
# A subject transform rewrites the subject a message is STORED under, which
# is separate from the subjects the stream listens on. Leave ORDERS alone:
# this is a throwaway stream that ingests on ingest.* and shards each
# message into one of three buckets by hashing the customer token.
# --transform-source which incoming subjects to match (wildcards ok)
# --transform-destination the stored subject, pulling matched tokens in
# {{partition(3,1)}} hash the 1st token into bucket 0, 1, or 2
# {{wildcard(1)}} the 1st * token from the source
nats stream add ORDERS-SHARDED \
--subjects "ingest.*" \
--transform-source "ingest.*" \
--transform-destination "orders.{{partition(3,1)}}.{{wildcard(1)}}" \
--defaults
// Create ORDERS-SHARDED with a subject transform. Every message on `ingest.*`
// is rewritten before it is stored: `partition(3,1)` shards each customer
// (the first wildcard token) into one of three buckets, and `wildcard(1)`
// keeps the customer id, so `ingest.acme` becomes `orders.<0-2>.acme`.
const info = await jsm.streams.add({
name: "ORDERS-SHARDED",
subjects: ["ingest.*"],
subject_transform: {
src: "ingest.*",
dest: "orders.{{partition(3,1)}}.{{wildcard(1)}}",
},
});
console.log(`Created stream: ${info.config.name}`);
// Create a stream that rewrites subjects as it stores them. The transform
// shards each customer into one of three buckets: partition(3,1) hashes the
// first wildcard token into 0, 1, or 2, and wildcard(1) keeps that token.
// So "ingest.alice" might land on "orders.2.alice".
stream, err := js.CreateStream(ctx, jetstream.StreamConfig{
Name: "ORDERS-SHARDED",
Subjects: []string{"ingest.*"},
SubjectTransform: &jetstream.SubjectTransformConfig{
Source: "ingest.*",
Destination: "orders.{{partition(3,1)}}.{{wildcard(1)}}",
},
})
if err != nil {
panic(err)
}
fmt.Printf("Created stream: %s\n", stream.CachedInfo().Config.Name)
# Create a stream that rewrites subjects as it stores them. Incoming
# ingest.<customer> messages become orders.<bucket>.<customer>, where
# partition(3,1) hashes the first wildcard token into one of three
# buckets — sharding each customer into a fixed partition.
info = await js.add_stream(
StreamConfig(
name="ORDERS-SHARDED",
subjects=["ingest.*"],
subject_transform=SubjectTransform(
src="ingest.*",
dest="orders.{{partition(3,1)}}.{{wildcard(1)}}",
),
)
)
print(f"created stream {info.config.name}")
// Rewrite each ingested subject as it lands in the stream. The template
// shards each customer into one of three buckets: partition(3,1) hashes
// the first wildcard token into 0, 1 or 2, and wildcard(1) keeps that
// same token as the trailing part of the stored subject.
SubjectTransform st = new SubjectTransform(
"ingest.*",
"orders.{{partition(3,1)}}.{{wildcard(1)}}");
StreamConfiguration sc = StreamConfiguration.builder()
.name("ORDERS-SHARDED")
.subjects("ingest.*")
.subjectTransform(st)
.build();
StreamInfo info = jsm.addStream(sc);
System.out.println("Created stream: " + info.getConfiguration().getName());
// Create a stream that rewrites each incoming subject as it is stored. Every
// message published to `ingest.*` is transformed into
// `orders.<bucket>.<original-token>`, where `partition(3, 1)` hashes the first
// wildcard token into one of three buckets (0, 1, or 2). This spreads orders
// across three shard subjects so consumers can filter by bucket.
let stream = js
.create_stream(stream::Config {
name: "ORDERS-SHARDED".to_string(),
subjects: vec!["ingest.*".to_string()],
subject_transform: Some(stream::SubjectTransform {
source: "ingest.*".to_string(),
destination: "orders.{{partition(3,1)}}.{{wildcard(1)}}".to_string(),
}),
..Default::default()
})
.await?;
println!("Created stream: {}", stream.cached_info().config.name);
// Ingest orders on `ingest.<customer>` and rewrite the subject on the way
// in. `partition(3, 1)` hashes the first wildcard token into one of three
// buckets, so each customer always shards to the same bucket.
var stream = await js.CreateStreamAsync(new StreamConfig(name: "ORDERS-SHARDED", subjects: ["ingest.*"])
{
SubjectTransform = new SubjectTransform
{
Src = "ingest.*",
Dest = "orders.{{partition(3,1)}}.{{wildcard(1)}}",
},
});
output.WriteLine($"Created {stream.Info.Config.Name}");
// Create a stream that rewrites subjects as it stores them. The
// transform shards each customer into one of three buckets:
// partition(3,1) hashes the first wildcard token into 0, 1, or 2,
// and wildcard(1) keeps that token. So "ingest.alice" might land on
// "orders.2.alice".
jsStreamConfig sc;
const char *subjects[] = {"ingest.*"};
jsStreamConfig_Init(&sc);
sc.Name = "ORDERS-SHARDED";
sc.Subjects = subjects;
sc.SubjectsLen = 1;
sc.SubjectTransform.Source = "ingest.*";
sc.SubjectTransform.Destination = "orders.{{partition(3,1)}}.{{wildcard(1)}}";
s = js_AddStream(&si, js, &sc, NULL, &jerr);
if (s == NATS_OK)
printf("Created stream: %s\n", si->Config->Name);
Опубликуйте заказы нескольких заказчиков: результат — orders.<bucket>.<customer>.
nats pub ingest.acme "an order"
nats pub ingest.globex "an order"
nats pub ingest.wayne "an order"
nats stream subjects ORDERS-SHARDED
Subject │ Count
orders.1.acme │ 1
orders.1.globex │ 1
orders.2.wayne │ 1
Фильтр orders.1.> всегда получает одну долю заказчиков. Изменение — nats stream edit --transform-source/--transform-destination, удаление — --no-transform.
Уже сохранённые записи не переписываются; подробнее ниже.
Повторная публикация в живые темы
Republish повторно выдаёт каждую сохранённую запись в другую тему. Это дешёвое живое наблюдение для панели без потребителя и истории.
- CLI
- JavaScript/TypeScript
- Go
- Python
- Java
- Rust
- C#/.NET
- C
#!/bin/bash
# Republish re-emits every message the stream stores onto a second subject,
# in real time. A plain core subscriber on that subject sees the data flow
# by without creating a consumer. This adds republish to ORDERS; clear it
# later with: nats stream edit ORDERS --no-republish
nats stream edit ORDERS \
--republish-source "orders.>" \
--republish-destination "dash.orders.>"
// Add a republish rule so every message stored under `orders.>` is also
// published live to a matching `dash.orders.>` subject that dashboards can
// subscribe to, then apply the update.
const config = info.config;
config.republish = {
src: "orders.>",
dest: "dash.orders.>",
// headers_only: true, // republish only the headers, not the message body
};
const updated = await jsm.streams.update("ORDERS", config);
console.log(`republish dest: ${updated.config.republish?.dest}`);
// Read the current config, add a republish rule, and push the update.
// Every message stored on "orders.>" is also echoed live to "dash.orders.>"
// so a dashboard can subscribe without touching the stream.
cfg := stream.CachedInfo().Config
cfg.RePublish = &jetstream.RePublish{
Source: "orders.>",
Destination: "dash.orders.>",
// HeadersOnly: true, // republish only the headers, not the body
}
updated, err := js.UpdateStream(ctx, cfg)
if err != nil {
panic(err)
}
fmt.Printf("Republish destination: %s\n", updated.CachedInfo().Config.RePublish.Destination)
# Republish every stored orders.> message onto a dash.orders.> subject, so
# core subscribers can watch the stream live without a consumer.
# Set headers_only=True to republish just the headers, not the body.
config.republish = RePublish(
src="orders.>",
dest="dash.orders.>",
# headers_only=True,
)
updated = await js.update_stream(config)
print(f"republishing to {updated.config.republish.dest}")
// Republish every message ORDERS stores onto a parallel subject that
// ordinary core subscribers can watch, without them touching the stream.
Republish rp = Republish.builder()
.source("orders.>")
.destination("dash.orders.>")
// .headersOnly(true) // republish only the headers, not the body
.build();
StreamConfiguration updated = StreamConfiguration.builder(current)
.republish(rp)
.build();
StreamInfo info = jsm.updateStream(updated);
System.out.println("Republish destination: " + info.getConfiguration().getRepublish().getDestination());
// Republish a copy of every stored message onto a second subject so a
// dashboard can subscribe live without touching the stream. Set
// `headers_only: true` to republish just the headers (subject, sequence,
// size) and skip the payload.
config.republish = Some(async_nats::jetstream::stream::Republish {
source: "orders.>".to_string(),
destination: "dash.orders.>".to_string(),
headers_only: false,
});
let info = js.update_stream(&config).await?;
println!(
"Republishing to: {}",
info.config
.republish
.as_ref()
.map_or("", |r| r.destination.as_str())
);
// Mirror every stored order onto a `dash.orders.>` subject as it lands.
// Read the current config, add the republish rule, and send it back.
var config = stream.Info.Config;
config.Republish = new Republish
{
Src = "orders.>",
Dest = "dash.orders.>",
// HeadersOnly = true,
};
var updated = await js.UpdateStreamAsync(config);
output.WriteLine($"Republishing to {updated.Info.Config.Republish!.Dest}");
// Read the current config, add a republish rule, and push the
// update. Every message stored on "orders.>" is also echoed live to
// "dash.orders.>" so a dashboard can subscribe without touching the
// stream.
jsRePublish rp;
s = js_GetStreamInfo(&si, js, "ORDERS", NULL, &jerr);
if (s == NATS_OK)
{
jsRePublish_Init(&rp);
rp.Source = "orders.>";
rp.Destination = "dash.orders.>";
// rp.HeadersOnly = true; // republish only the headers, not the body
si->Config->RePublish = &rp;
s = js_UpdateStream(&updated, js, si->Config, NULL, &jerr);
}
if (s == NATS_OK)
printf("Republish destination: %s\n", updated->Config->RePublish->Destination);
Обычная подписка видит поступающие заказы:
nats sub "dash.orders.>"
[#1] Received on "dash.orders.created"
Nats-Stream: ORDERS
Nats-Subject: orders.created
Nats-Sequence: 5
Nats-Time-Stamp: 2026-05-22T11:02:00Z
Nats-Last-Sequence: 4
{"order_id":"ord_5xk1","customer":"initech","total_cents":1500,"ts":"2026-05-22T11:02:00Z"}
Пять заголовков происхождения: Nats-Stream, Nats-Subject, Nats-Sequence, Nats-Time-Stamp, Nats-Last-Sequence. Последний — прежний номер той же темы либо 0, что помогает обнаружить пропуск. Заголовки издателя тоже сохраняются.
--republish-headers исключает тела, добавляя их размер Nats-Msg-Size. Отключение — nats stream edit ORDERS --no-republish.
Преобразование при копировании
Каждый источник или зеркало может менять пространство тем, например добавляя регион при агрегации. Это разобрано с механизмом копирования.
Отличие от сопоставления учётной записи
Сопоставление Core NATS настраивается серверу для учётной записи и меняет маршрутизацию до записи в поток. Это отдельный механизм.
Типичные ошибки
Основные ловушки:
Потерянный токен фильтра. Шаблон сохраняет только указанные части. orders.* → orders.archived без {{wildcard(1)}} лишает потребителя фильтрации по типу. Сохраняйте нужные токены.
Republish не заменяет потребителя. Это Core без хранения, ack и повторов: отключённый читатель пропускает. Для наверстывания нужна долговременная доставка.
Цикл republish. Цель не должна пересекать подписки потока. Для orders.> цель orders.dash.> отклоняется кодом 10052; используйте dash.orders.>. Циклы между двумя потоками сервер не всегда обнаруживает.
Правка не переписывает историю. Для изменения прежних тем копируйте в новый поток с преобразованием источника.
Количество разделов нельзя безболезненно менять. Переход partition(3, …) → partition(4, …) перемещает заказчиков между фильтрами orders.0.>, orders.1.> и другими. Планируйте число заранее.
Что уже готово
Преобразование выполнялось на временном ORDERS-SHARDED, не ORDERS. Если добавлен republish, его убирает nats stream edit ORDERS --no-republish. Три места изменения:
- Subject transform при сохранении.
- Republish в живые темы.
- Преобразования источников при копировании.
Что дальше
TTL отдельных сообщений сокращает жизнь выбранной записи.
См. также
- Создание потока — subject_transform, republish, subject_transforms.
- ADR-36 — места подключения.
- ADR-30 — функции шаблона.
- ADR-28 — заголовки и циклы.
- Фильтрация — без смены тем.
- Зеркала и источники — агрегация.