pulse-sdk 0.0.5 → 0.1.0-main.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,177 +1,116 @@
1
- # Pulse SDK — TypeScript
1
+ # Pulse TypeScript SDK
2
2
 
3
- TypeScript client for Pulse Broker (gRPC). This README is written for end users and explains installation, configuration, and basic usage with practical examples.
3
+ Official TypeScript client for [Pulse Broker](https://github.com/marcosrosa/pulse).
4
4
 
5
5
  ## Installation
6
6
 
7
- Install from npm (published package):
8
-
9
7
  ```bash
10
8
  npm install pulse-sdk
11
9
  ```
12
10
 
13
- Or install locally from the repository (for development):
14
-
15
- ```bash
16
- npm install
17
- ```
18
-
19
- To compile the TypeScript sources (optional for development/CI):
20
-
21
- ```bash
22
- npm run build
23
- ```
24
-
25
- Run the lightweight integration tests (a test gRPC server is started automatically):
26
-
27
- ```bash
28
- npm test
29
- ```
30
-
31
11
  ## Configuration
32
12
 
33
- The SDK supports configuration via (in priority order):
13
+ The SDK looks for a `pulse.yaml` (or `pulse.yml`) file in your project root. If not found, it defaults to `localhost:5555` (HTTP) and `localhost:5556` (gRPC).
34
14
 
35
- 1. Programmatic: pass a `PulseConfig` object when creating `Producer` or `Consumer`.
36
- 2. Environment variables: `PULSE_GRPC_URL`, `PULSE_EVENT_TYPES` (comma-separated), `PULSE_CONSUMER_NAME`.
37
- 3. File: a `pulse.yml` or `pulse.yaml` file placed at the process working directory or in `~/.pulse/pulse.yml`.
38
-
39
- The SDK exposes two helpers:
40
-
41
- - `loadConfig(configPath?: string): PulseConfig` — reads `pulse.yml` / env and returns a merged config object.
42
- - `initFromConfig(cfg: PulseConfig): Promise<void>` — calls the broker `CreateTopic` RPC for every topic declared in `cfg.topics`. This lets the SDK create any required topics automatically at startup (useful for tests or first-run).
43
-
44
- Example `pulse.yml`:
15
+ ### Example `pulse.yaml`
45
16
 
46
17
  ```yaml
47
- grpcUrl: localhost:5556
48
- eventTypes:
49
- - events
50
- - transactions
51
- consumerName: my-consumer
18
+ # Connection Settings
19
+ broker:
20
+ host: "localhost"
21
+ http_port: 5555
22
+ grpc_port: 5556
23
+ timeout_ms: 5000
24
+
25
+ # Client Defaults
26
+ client:
27
+ id: "my-typescript-app"
28
+ auto_commit: true # Automatically commit offsets after successful processing
29
+ max_retries: 3
30
+
31
+ # Topic Configuration
52
32
  topics:
53
- - name: events
54
- fifo: false
55
- - name: transactions
56
- fifo: true
57
- ```
58
-
59
- Usage example (auto-create topics then start):
60
-
61
- ```ts
62
- import { loadConfig, initFromConfig, Producer, Consumer } from 'pulse-sdk';
63
-
64
- async function main() {
65
- const cfg = loadConfig(); // reads pulse.yml or environment
66
- await initFromConfig(cfg); // create topics listed in cfg.topics (no-op if none)
67
-
68
- const producer = new Producer(cfg);
69
- await producer.send('events', { type: 'user.created', id: 1 });
70
-
71
- const consumer = new Consumer(cfg);
72
- consumer.on('events', (msg) => console.log('received', msg.payload));
73
- await consumer.start('events', cfg.consumerName || 'default');
74
- }
75
-
76
- main().catch(console.error);
33
+ - name: "events"
34
+ create_if_missing: true
35
+ config:
36
+ fifo: false
37
+ retention_bytes: 1073741824 # 1GB
38
+ consume:
39
+ auto_commit: true
40
+
41
+ - name: "transactions"
42
+ create_if_missing: true
43
+ config:
44
+ fifo: true
45
+ consume:
46
+ auto_commit: false # Manual commit required
47
+
48
+ - name: "logs"
49
+ create_if_missing: true
50
+ config:
51
+ fifo: false
52
+ consume:
53
+ auto_commit: true
77
54
  ```
78
55
 
79
- Notes:
80
- - `initFromConfig` calls the gRPC `CreateTopic` RPC. If the broker responds with an error for a topic that already exists, the SDK logs a warning and continues.
81
- - Ensure the broker is running and reachable at `cfg.grpcUrl` before calling `initFromConfig`.
82
- - The SDK bundles `pulse.proto` inside the package so consumers do not need to copy proto files into their projects.
56
+ ## Usage
83
57
 
84
- ## Quick Start
58
+ ### Producer
85
59
 
86
- Import from the published package and pass configuration programmatically:
60
+ You can send objects (automatically serialized to JSON), strings, or raw buffers.
87
61
 
88
- ```ts
89
- import { Producer, Consumer } from 'pulse-sdk';
62
+ ```typescript
63
+ import { Producer } from 'pulse-sdk';
90
64
 
91
- const cfg = { grpcUrl: 'localhost:50052', eventTypes: ['events'] };
65
+ // Initialize (uses pulse.yaml or defaults)
66
+ // You can override settings: new Producer("10.0.0.1", 9090)
67
+ const producer = new Producer();
92
68
 
93
- // Send a JSON-serializable event
94
- const producer = new Producer(cfg);
95
- await producer.send('events', { type: 'user.created', id: 123 });
69
+ async function main() {
70
+ // Send JSON
71
+ await producer.send("events", { type: "user_created", id: 123 });
96
72
 
97
- // Consume events and register a handler
98
- const consumer = new Consumer(cfg);
99
- consumer.on('events', (msg) => {
100
- console.log('received', msg.payload);
101
- });
102
- await consumer.start('events', 'my-consumer');
103
- ```
73
+ // Send String
74
+ await producer.send("logs", "raw log line");
104
75
 
105
- ### Programmatic override
76
+ // Send Buffer
77
+ await producer.send("logs", Buffer.from("binary data"));
106
78
 
107
- You can create and pass `PulseConfig` directly in code:
79
+ producer.close();
80
+ }
108
81
 
109
- ```ts
110
- const cfg = { grpcUrl: '10.0.0.5:50052', eventTypes: ['events'] };
111
- const producer = new Producer(cfg);
82
+ main();
112
83
  ```
113
84
 
114
- ## Technical Details
115
-
116
- - The SDK dynamically loads `pulse.proto` at runtime using `@grpc/proto-loader` and `@grpc/grpc-js`.
117
- - The protobuf field `bytes payload` is used to carry the message body; the SDK serializes JSON payloads into that field by default.
118
- - `Consumer.start()` opens a server stream (`Consume`) and dispatches incoming messages to handlers registered via `consumer.on(topic, handler)`.
119
-
120
- ## Examples
85
+ ### Consumer
121
86
 
122
- Producer (send multiple events):
87
+ Use the `consumer` function to register message handlers, and `run` to start the loop.
123
88
 
124
- ```ts
125
- const producer = new Producer(loadConfig());
126
- await producer.send('events', { type: 'login', userId: 1 });
127
- await producer.send('events', { type: 'logout', userId: 1 });
128
- ```
129
-
130
- Consumer (simple processing):
131
-
132
- ```ts
133
- const cfg = loadConfig();
134
- const consumer = new Consumer(cfg);
89
+ ```typescript
90
+ import { consumer, run, commit, Message } from 'pulse-sdk';
135
91
 
136
- consumer.on('events', (msg) => {
137
- console.log('event payload', msg.payload);
92
+ // Simple Consumer (uses auto_commit from config)
93
+ consumer("events", async (msg: Message) => {
94
+ console.log(`Received event:`, msg.payload);
95
+ // msg.payload is an object if JSON, string if String, else Buffer
138
96
  });
139
97
 
140
- await consumer.start('events', cfg.consumerName || 'default');
141
- ```
142
-
143
- ## Local Tests
144
-
145
- The tests in `tests/` start a lightweight gRPC test server automatically; run them with `npm test`.
146
-
147
- ## FAQ (short)
148
-
149
- - Can I use decorators for handlers? Yes — TypeScript supports decorators, but this SDK does not use them by default. We can add decorator helpers later if desired.
150
- - How do I enable TLS / secure credentials? The client factory currently uses `createInsecure()` by default. We can expose a `credentials` option on `PulseConfig` to accept `grpc.credentials.createSsl(...)` or other credential objects.
151
-
152
- **Grouped consumption**
153
-
154
- - **What it does:** When `grouped` is `true` (the default) the SDK coalesces consumers inside the same process that use the same `consumerName` into a single streaming connection. Messages are distributed (round-robin) among the registered handlers so each message is delivered to only one handler in the group (1x per client id).
155
- - **Why:** This mirrors the Python SDK behavior where handlers registered with `grouped=True` share a single consumer stream and avoid duplicate processing inside the same client.
156
- - **How to configure:**
157
- - `pulse.yml` (recommended): set `grouped: true` or `grouped: false` under top-level config.
158
- - Environment variable: `PULSE_GROUPED=true|false`.
159
- - Programmatically: pass `grouped` in the `PulseConfig` passed to `Producer`/`Consumer`.
160
- - **Default:** `grouped` defaults to `true`.
161
- - **Grouped=false behavior:** When `grouped` is `false`, the SDK will ensure consumers use unique consumer IDs (if you pass the default client name), so multiple consumers in the same process each receive all messages independently (useful for testing or when you want duplicate consumption).
162
- - **Example `pulse.yml` entry:**
163
-
164
- ```yaml
165
- grpcUrl: localhost:5556
166
- grouped: true
98
+ // Manual Commit Consumer
99
+ // Override config params directly in the options object
100
+ consumer("transactions", async (msg: Message) => {
101
+ try {
102
+ await processPayment(msg.payload);
103
+ await commit(); // Manually commit offset
104
+ console.log(`Processed transaction ${msg.offset}`);
105
+ } catch (e) {
106
+ console.error(`Failed to process: ${e}`);
107
+ }
108
+ }, { autoCommit: false });
109
+
110
+ // Start all consumers
111
+ run();
112
+
113
+ async function processPayment(data: any) {
114
+ // ... implementation
115
+ }
167
116
  ```
168
-
169
- The test-suite includes integration tests that validate both `grouped=true` and `grouped=false` behaviour.
170
-
171
- ## Contributing
172
-
173
- Please open a PR with tests. The existing tests validate basic Producer/Consumer behaviour.
174
-
175
- ---
176
-
177
- If you want this README expanded to mirror the Python SDK more closely (topic-level config, manual offset commits, longer examples), tell me which sections to add and I will update it.
package/dist/config.d.ts CHANGED
@@ -1,16 +1,26 @@
1
+ export interface BrokerConfig {
2
+ host: string;
3
+ http_port: number;
4
+ grpc_port: number;
5
+ timeout_ms: number;
6
+ }
7
+ export interface ClientConfig {
8
+ id: string;
9
+ auto_commit: boolean;
10
+ max_retries: number;
11
+ }
1
12
  export interface TopicConfig {
2
13
  name: string;
3
- fifo?: boolean;
4
- retention_bytes?: number;
5
- retention_time?: number;
14
+ create_if_missing?: boolean;
15
+ config?: {
16
+ fifo?: boolean;
17
+ retention_bytes?: number;
18
+ };
6
19
  }
7
20
  export interface PulseConfig {
8
- grpcUrl: string;
9
- eventTypes: string[];
10
- consumerName?: string;
11
- grouped?: boolean;
12
- autoCommit?: boolean;
13
- topics?: TopicConfig[];
21
+ broker: BrokerConfig;
22
+ client: ClientConfig;
23
+ topics: TopicConfig[];
14
24
  }
15
25
  export declare function loadConfig(configPath?: string): PulseConfig;
16
- export declare function initFromConfig(cfg: PulseConfig): Promise<void>;
26
+ export declare function getConfig(): PulseConfig;
package/dist/config.js CHANGED
@@ -4,78 +4,62 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.loadConfig = loadConfig;
7
- exports.initFromConfig = initFromConfig;
7
+ exports.getConfig = getConfig;
8
8
  const fs_1 = __importDefault(require("fs"));
9
9
  const path_1 = __importDefault(require("path"));
10
10
  const os_1 = __importDefault(require("os"));
11
11
  const js_yaml_1 = __importDefault(require("js-yaml"));
12
- const client_1 = require("./proto/client");
13
- const DEFAULTS = {
14
- grpcUrl: 'localhost:50052',
15
- eventTypes: ['events'],
16
- grouped: true,
17
- autoCommit: true,
12
+ const DEFAULT_CONFIG = {
13
+ broker: {
14
+ host: 'localhost',
15
+ http_port: 5555,
16
+ grpc_port: 5556,
17
+ timeout_ms: 5000,
18
+ },
19
+ client: {
20
+ id: 'typescript-client',
21
+ auto_commit: true,
22
+ max_retries: 3,
23
+ },
24
+ topics: [],
18
25
  };
19
26
  function loadConfig(configPath) {
20
27
  const candidates = [
21
28
  configPath,
22
- path_1.default.resolve(process.cwd(), 'pulse.yml'),
23
29
  path_1.default.resolve(process.cwd(), 'pulse.yaml'),
30
+ path_1.default.resolve(process.cwd(), 'pulse.yml'),
24
31
  path_1.default.join(os_1.default.homedir(), '.pulse', 'pulse.yml'),
25
32
  ].filter(Boolean);
26
33
  let fileCfg = {};
27
34
  for (const p of candidates) {
28
35
  if (p && fs_1.default.existsSync(p)) {
29
- const raw = fs_1.default.readFileSync(p, 'utf8');
30
- const parsed = js_yaml_1.default.load(raw);
31
- fileCfg = parsed || {};
32
- break;
36
+ try {
37
+ const raw = fs_1.default.readFileSync(p, 'utf8');
38
+ fileCfg = js_yaml_1.default.load(raw) || {};
39
+ break;
40
+ }
41
+ catch (e) {
42
+ console.warn(`Failed to load config from ${p}:`, e);
43
+ }
33
44
  }
34
45
  }
35
- const envCfg = {};
36
- if (process.env.PULSE_GRPC_URL)
37
- envCfg.grpcUrl = process.env.PULSE_GRPC_URL;
38
- if (process.env.PULSE_EVENT_TYPES)
39
- envCfg.eventTypes = process.env.PULSE_EVENT_TYPES.split(',');
40
- if (process.env.PULSE_CONSUMER_NAME)
41
- envCfg.consumerName = process.env.PULSE_CONSUMER_NAME;
42
- if (process.env.PULSE_GROUPED)
43
- envCfg.grouped = process.env.PULSE_GROUPED === 'true';
44
- if (process.env.PULSE_AUTOCOMMIT)
45
- envCfg.autoCommit = process.env.PULSE_AUTOCOMMIT === 'true';
46
- const merged = Object.assign({}, DEFAULTS, fileCfg, envCfg);
47
- // Ensure eventTypes array exists
48
- if (!merged.eventTypes)
49
- merged.eventTypes = DEFAULTS.eventTypes;
50
- if (merged.grouped === undefined)
51
- merged.grouped = true;
52
- if (merged.autoCommit === undefined)
53
- merged.autoCommit = true;
54
- return merged;
46
+ // Deep merge defaults with file config
47
+ const config = JSON.parse(JSON.stringify(DEFAULT_CONFIG)); // Deep copy
48
+ if (fileCfg.broker) {
49
+ config.broker = { ...config.broker, ...fileCfg.broker };
50
+ }
51
+ if (fileCfg.client) {
52
+ config.client = { ...config.client, ...fileCfg.client };
53
+ }
54
+ if (fileCfg.topics) {
55
+ config.topics = fileCfg.topics;
56
+ }
57
+ return config;
55
58
  }
56
- // Initialize topics from config using gRPC CreateTopic RPC.
57
- async function initFromConfig(cfg) {
58
- if (!cfg.topics || cfg.topics.length === 0)
59
- return;
60
- const client = (0, client_1.createClient)(cfg.grpcUrl);
61
- for (const t of cfg.topics) {
62
- const req = {
63
- topic: t.name || t['name'],
64
- fifo: !!t.fifo,
65
- retention_bytes: t.retention_bytes || 0,
66
- retention_time: t.retention_time || 0,
67
- };
68
- await new Promise((resolve, reject) => {
69
- client.CreateTopic(req, (err, res) => {
70
- if (err) {
71
- // If topic exists the server may return an error; log and continue
72
- console.warn('CreateTopic error for', req.topic, err.message || err);
73
- resolve();
74
- }
75
- else {
76
- resolve();
77
- }
78
- });
79
- });
59
+ let _config = null;
60
+ function getConfig() {
61
+ if (!_config) {
62
+ _config = loadConfig();
80
63
  }
64
+ return _config;
81
65
  }
@@ -1,12 +1,12 @@
1
- import { PulseConfig } from './config';
2
- export type EventHandler = (payload: any) => any;
3
- export declare class Consumer {
4
- private config;
5
- private handlers;
6
- private client;
7
- private unregisterFns;
8
- constructor(config: PulseConfig);
9
- on(eventType: string, handler: EventHandler): void;
10
- start(topic?: string, consumerName?: string): Promise<void>;
11
- close(): void;
1
+ import { Message, commit } from './message';
2
+ export { commit, Message };
3
+ interface ConsumerOptions {
4
+ host?: string;
5
+ port?: number;
6
+ consumerGroup?: string;
7
+ autoCommit?: boolean;
8
+ grouped?: boolean;
12
9
  }
10
+ export declare function stop(): void;
11
+ export declare function consumer(topic: string, handler: (msg: Message) => void | Promise<void>, options?: ConsumerOptions): void;
12
+ export declare function run(): Promise<void>;