Publish and subscribe
Publish a CloudEvent and subscribe to a topic from each client library. The wire type, topics and delivery rules are in Events.
Client examples
C#
using var client = new ApiClient("localhost");
var ce = new CloudEvent
{
Id = Guid.NewGuid().ToString(),
Source = "urn:virtufin:my-service",
SpecVersion = "1.0",
Type = "com.virtufin.worker.started",
TextData = """{"workerId":"abc123"}""",
};
await client.Gateway.PublishEventAsync("workmanager.lifecycle", ce);
await using var sub = await client.SubscribeAsync(["workmanager.lifecycle"], token);
await foreach (var evt in sub)
Console.WriteLine($"{evt.Topic}: {evt.Cloudevent.Type}");
Python
async with ApiClient(host="localhost") as client:
ce = cloudevents_pb2.CloudEvent(
id=str(uuid.uuid4()),
source="urn:virtufin:my-service",
spec_version="1.0",
type="com.virtufin.worker.started",
text_data=json.dumps({"workerId": "abc123"}),
)
await client.pubsub.publish_async("workmanager.lifecycle", ce)
call = await client.pubsub.subscribe_async(topics=["workmanager.lifecycle"])
async for event in call:
print(event.topic, event.cloudevent.type)
TypeScript
const client = new ApiClient({ host: "localhost" });
await client.publish("workmanager.lifecycle", cloudevent);
const sub = await client.subscribe(["workmanager.lifecycle"]);
for await (const evt of sub) {
console.log(evt.topic, evt.cloudevent?.type);
}
Best practices
- Name your topics explicitly on
Subscribe— the empty-list default issys.api.state.saved/deleted, which is almost never what you want. - Handle a failed publish as an error: it is a non-OK gRPC status whose
ErrorInfonames the reason (Errors). - Pass a cancellation token to
Subscribeand cancel it to tear down; that is the only working teardown path. - Discriminate on
cloudevent.type, not on the topic alone — one topic carries a service's whole event taxonomy. - Leave
include_valueoff unless the state value is public to the whole platform. - Use the SDK's request-reply helper instead of hand-rolling correlation.