@valentinkolb/sync 0.1.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.
@@ -0,0 +1,72 @@
1
+ name: Publish Package
2
+
3
+ on:
4
+ push:
5
+ tags:
6
+ - "v*"
7
+
8
+ jobs:
9
+ publish-npm:
10
+ runs-on: ubuntu-latest
11
+ permissions:
12
+ id-token: write
13
+ contents: read
14
+ steps:
15
+ - uses: actions/checkout@v4
16
+
17
+ - uses: oven-sh/setup-bun@v2
18
+
19
+ - uses: actions/setup-node@v4
20
+ with:
21
+ node-version: "22"
22
+ registry-url: "https://registry.npmjs.org"
23
+
24
+ - name: Set version from tag
25
+ run: npm version ${GITHUB_REF#refs/tags/v} --no-git-tag-version
26
+
27
+ - name: Install dependencies
28
+ run: bun install
29
+
30
+ - name: Build package
31
+ run: bun build ./index.ts --outdir ./dist --target node
32
+
33
+ - name: Create dist package.json
34
+ run: |
35
+ # Get version from package.json
36
+ VERSION=$(node -p "require('./package.json').version")
37
+
38
+ # Create package.json for dist with lowercase name for npm
39
+ cat > dist/package.json << EOF
40
+ {
41
+ "name": "@valentinkolb/sync",
42
+ "version": "$VERSION",
43
+ "description": "Distributed synchronization primitives for Bun and TypeScript",
44
+ "main": "index.js",
45
+ "module": "index.js",
46
+ "types": "index.d.ts",
47
+ "type": "module",
48
+ "exports": {
49
+ ".": {
50
+ "import": "./index.js",
51
+ "types": "./index.d.ts"
52
+ }
53
+ },
54
+ "peerDependencies": {
55
+ "zod": "^3"
56
+ },
57
+ "keywords": ["bun", "redis", "ratelimit", "mutex", "jobs", "queue", "distributed"],
58
+ "author": "Valentin Kolb",
59
+ "license": "MIT",
60
+ "repository": {
61
+ "type": "git",
62
+ "url": "git+https://github.com/ValentinKolb/sync.git"
63
+ }
64
+ }
65
+ EOF
66
+
67
+ - name: Generate type declarations
68
+ run: bunx tsc --declaration --emitDeclarationOnly --outDir dist
69
+
70
+ - name: Publish to npm
71
+ run: npm publish --provenance --access public
72
+ working-directory: ./dist
package/CLAUDE.md ADDED
@@ -0,0 +1,106 @@
1
+
2
+ Default to using Bun instead of Node.js.
3
+
4
+ - Use `bun <file>` instead of `node <file>` or `ts-node <file>`
5
+ - Use `bun test` instead of `jest` or `vitest`
6
+ - Use `bun build <file.html|file.ts|file.css>` instead of `webpack` or `esbuild`
7
+ - Use `bun install` instead of `npm install` or `yarn install` or `pnpm install`
8
+ - Use `bun run <script>` instead of `npm run <script>` or `yarn run <script>` or `pnpm run <script>`
9
+ - Bun automatically loads .env, so don't use dotenv.
10
+
11
+ ## APIs
12
+
13
+ - `Bun.serve()` supports WebSockets, HTTPS, and routes. Don't use `express`.
14
+ - `bun:sqlite` for SQLite. Don't use `better-sqlite3`.
15
+ - `Bun.redis` for Redis. Don't use `ioredis`.
16
+ - `Bun.sql` for Postgres. Don't use `pg` or `postgres.js`.
17
+ - `WebSocket` is built-in. Don't use `ws`.
18
+ - Prefer `Bun.file` over `node:fs`'s readFile/writeFile
19
+ - Bun.$`ls` instead of execa.
20
+
21
+ ## Testing
22
+
23
+ Use `bun test` to run tests.
24
+
25
+ ```ts#index.test.ts
26
+ import { test, expect } from "bun:test";
27
+
28
+ test("hello world", () => {
29
+ expect(1).toBe(1);
30
+ });
31
+ ```
32
+
33
+ ## Frontend
34
+
35
+ Use HTML imports with `Bun.serve()`. Don't use `vite`. HTML imports fully support React, CSS, Tailwind.
36
+
37
+ Server:
38
+
39
+ ```ts#index.ts
40
+ import index from "./index.html"
41
+
42
+ Bun.serve({
43
+ routes: {
44
+ "/": index,
45
+ "/api/users/:id": {
46
+ GET: (req) => {
47
+ return new Response(JSON.stringify({ id: req.params.id }));
48
+ },
49
+ },
50
+ },
51
+ // optional websocket support
52
+ websocket: {
53
+ open: (ws) => {
54
+ ws.send("Hello, world!");
55
+ },
56
+ message: (ws, message) => {
57
+ ws.send(message);
58
+ },
59
+ close: (ws) => {
60
+ // handle close
61
+ }
62
+ },
63
+ development: {
64
+ hmr: true,
65
+ console: true,
66
+ }
67
+ })
68
+ ```
69
+
70
+ HTML files can import .tsx, .jsx or .js files directly and Bun's bundler will transpile & bundle automatically. `<link>` tags can point to stylesheets and Bun's CSS bundler will bundle.
71
+
72
+ ```html#index.html
73
+ <html>
74
+ <body>
75
+ <h1>Hello, world!</h1>
76
+ <script type="module" src="./frontend.tsx"></script>
77
+ </body>
78
+ </html>
79
+ ```
80
+
81
+ With the following `frontend.tsx`:
82
+
83
+ ```tsx#frontend.tsx
84
+ import React from "react";
85
+
86
+ // import .css files directly and it works
87
+ import './index.css';
88
+
89
+ import { createRoot } from "react-dom/client";
90
+
91
+ const root = createRoot(document.body);
92
+
93
+ export default function Frontend() {
94
+ return <h1>Hello, world!</h1>;
95
+ }
96
+
97
+ root.render(<Frontend />);
98
+ ```
99
+
100
+ Then, run index.ts
101
+
102
+ ```sh
103
+ bun --hot ./index.ts
104
+ ```
105
+
106
+ For more information, read the Bun API docs in `node_modules/bun-types/docs/**.md`.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Valentin Kolb
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,292 @@
1
+ # @valentinkolb/sync
2
+
3
+ Distributed synchronization primitives for Bun and TypeScript. Built on Redis for horizontal scaling.
4
+
5
+ **Zero external dependencies** - uses only Bun's native Redis client (`Bun.redis`) and Zod for schema validation.
6
+
7
+ ## Features
8
+
9
+ - **Rate Limiting** - Sliding window algorithm for smooth rate limiting
10
+ - **Distributed Mutex** - Acquire locks across multiple processes with automatic expiry
11
+ - **Background Jobs** - Delayed, scheduled, and periodic jobs with retries
12
+ - **Horizontal Scaling** - All state in Redis, run multiple instances safely
13
+ - **Type Safe** - Full TypeScript support with Zod schema validation for jobs
14
+
15
+ ## Installation
16
+
17
+ ```bash
18
+ bun add @valentinkolb/sync zod
19
+ ```
20
+
21
+ ## Quick Start
22
+
23
+ ### Rate Limiting
24
+
25
+ ```typescript
26
+ import { ratelimit } from "@valentinkolb/sync";
27
+
28
+ const limiter = ratelimit.create({
29
+ limit: 100, // 100 requests
30
+ windowSecs: 60, // per minute
31
+ });
32
+
33
+ const result = await limiter.check("user:123");
34
+ if (result.limited) {
35
+ console.log(`Rate limited. Retry in ${result.resetIn}ms`);
36
+ }
37
+
38
+ // Or throw on limit
39
+ await limiter.checkOrThrow("user:123");
40
+ ```
41
+
42
+ ### Distributed Mutex
43
+
44
+ ```typescript
45
+ import { mutex } from "@valentinkolb/sync";
46
+
47
+ const m = mutex.create();
48
+
49
+ // Automatic acquire/release
50
+ const result = await m.withLock("resource:123", async () => {
51
+ // Only one process can execute this at a time
52
+ return await doExclusiveWork();
53
+ });
54
+
55
+ // Or throw if lock cannot be acquired
56
+ const result = await m.withLockOrThrow("resource:123", async () => {
57
+ return await doExclusiveWork();
58
+ });
59
+ ```
60
+
61
+ ### Background Jobs
62
+
63
+ ```typescript
64
+ import { jobs } from "@valentinkolb/sync";
65
+ import { z } from "zod";
66
+
67
+ // Create a typed job queue
68
+ const emailJobs = jobs.create({
69
+ name: "emails",
70
+ schema: z.object({
71
+ to: z.string().email(),
72
+ subject: z.string(),
73
+ body: z.string(),
74
+ }),
75
+ });
76
+
77
+ // Send jobs
78
+ await emailJobs.send({ to: "user@example.com", subject: "Hello", body: "World" });
79
+
80
+ // Process jobs
81
+ const stop = emailJobs.process(async (job) => {
82
+ await sendEmail(job.data);
83
+ }, { concurrency: 10 });
84
+ ```
85
+
86
+ ## Rate Limiting
87
+
88
+ Uses a sliding window algorithm that provides smoother rate limiting than fixed windows.
89
+
90
+ ```typescript
91
+ import { ratelimit, RateLimitError } from "@valentinkolb/sync";
92
+
93
+ const limiter = ratelimit.create({
94
+ limit: 100, // Max requests in window
95
+ windowSecs: 60, // Window size in seconds (default: 1)
96
+ prefix: "rl", // Redis key prefix (default: "ratelimit")
97
+ });
98
+
99
+ // Check without throwing
100
+ const result = await limiter.check("user:123");
101
+ // { limited: boolean, remaining: number, resetIn: number }
102
+
103
+ // Check and throw RateLimitError if limited
104
+ try {
105
+ await limiter.checkOrThrow("user:123");
106
+ } catch (e) {
107
+ if (e instanceof RateLimitError) {
108
+ console.log(`Retry in ${e.resetIn}ms`);
109
+ }
110
+ }
111
+ ```
112
+
113
+ ## Distributed Mutex
114
+
115
+ Uses Redis SET NX for atomic lock acquisition with automatic expiry to prevent deadlocks.
116
+
117
+ ```typescript
118
+ import { mutex, LockError } from "@valentinkolb/sync";
119
+
120
+ const m = mutex.create({
121
+ prefix: "lock", // Redis key prefix (default: "mutex")
122
+ retryCount: 10, // Retry attempts (default: 10)
123
+ retryDelay: 200, // Delay between retries in ms (default: 200)
124
+ defaultTtl: 10000, // Lock TTL in ms (default: 10000)
125
+ });
126
+
127
+ // Automatic release with withLock
128
+ const result = await m.withLock("resource", async (lock) => {
129
+ // Extend lock if operation takes longer than expected
130
+ await m.extend(lock, 30000);
131
+ return await longOperation();
132
+ });
133
+
134
+ // Returns null if lock cannot be acquired
135
+ if (result === null) {
136
+ console.log("Could not acquire lock");
137
+ }
138
+
139
+ // Or throw LockError
140
+ try {
141
+ await m.withLockOrThrow("resource", async () => {
142
+ return await doWork();
143
+ });
144
+ } catch (e) {
145
+ if (e instanceof LockError) {
146
+ console.log(`Failed to lock: ${e.resource}`);
147
+ }
148
+ }
149
+
150
+ // Manual acquire/release
151
+ const lock = await m.acquire("resource");
152
+ if (lock) {
153
+ try {
154
+ await doWork();
155
+ } finally {
156
+ await m.release(lock);
157
+ }
158
+ }
159
+ ```
160
+
161
+ ## Background Jobs
162
+
163
+ A Redis-backed job queue with support for delayed jobs, periodic scheduling, retries, and timeouts.
164
+
165
+ ### Creating a Queue
166
+
167
+ ```typescript
168
+ import { jobs } from "@valentinkolb/sync";
169
+ import { z } from "zod";
170
+
171
+ const emailJobs = jobs.create({
172
+ name: "emails", // Queue name
173
+ schema: z.object({ // Zod schema for validation
174
+ to: z.string().email(),
175
+ subject: z.string(),
176
+ body: z.string(),
177
+ }),
178
+ prefix: "jobs", // Redis key prefix (default: "jobs")
179
+ });
180
+ ```
181
+
182
+ ### Sending Jobs
183
+
184
+ ```typescript
185
+ // Immediate execution
186
+ await emailJobs.send({ to: "...", subject: "...", body: "..." });
187
+
188
+ // Delayed execution
189
+ await emailJobs.send(data, { delay: 5000 }); // In 5 seconds
190
+ await emailJobs.send(data, { at: Date.now() + 60000 }); // At specific time
191
+
192
+ // Periodic jobs
193
+ await emailJobs.send(data, { interval: 3600000 }); // Every hour
194
+ await emailJobs.send(data, { interval: 3600000, startImmediately: true });
195
+
196
+ // With retries and timeout
197
+ await emailJobs.send(data, {
198
+ retries: 3, // 1 initial + 3 retries = 4 attempts
199
+ timeout: 60000, // Fail if processing takes > 60s
200
+ });
201
+ ```
202
+
203
+ | Option | Description | Default |
204
+ |--------|-------------|---------|
205
+ | `delay` | Delay execution by ms | - |
206
+ | `at` | Execute at timestamp | - |
207
+ | `interval` | Repeat every ms | - |
208
+ | `startImmediately` | Start interval job immediately | `false` |
209
+ | `retries` | Number of retries on failure | `0` |
210
+ | `timeout` | Max processing time before hard fail | `30000` |
211
+
212
+ > **Note:** `delay`, `at`, and `interval` are mutually exclusive.
213
+
214
+ ### Processing Jobs
215
+
216
+ ```typescript
217
+ const stop = emailJobs.process(async (job) => {
218
+ console.log(`Processing job ${job.id}`);
219
+ await sendEmail(job.data);
220
+ }, {
221
+ concurrency: 10, // Process 10 jobs in parallel
222
+ pollInterval: 1000, // Poll every 1s when queue is empty
223
+
224
+ onSuccess: (job) => {
225
+ console.log(`Job ${job.id} completed`);
226
+ },
227
+
228
+ onError: (job, error) => {
229
+ // Called when job permanently fails or interval job fails
230
+ console.error(`Job ${job.id} failed:`, error.message);
231
+ },
232
+
233
+ onFinally: (job) => {
234
+ // Called after every attempt (success or failure)
235
+ console.log(`Job ${job.id} attempt finished`);
236
+ },
237
+ });
238
+
239
+ // Stop processing
240
+ stop();
241
+ ```
242
+
243
+ ### Job Object
244
+
245
+ ```typescript
246
+ type Job<T> = {
247
+ id: string;
248
+ data: T;
249
+ status: "waiting" | "delayed" | "active" | "completed" | "failed";
250
+ attempts: number;
251
+ maxRetries: number;
252
+ timeout: number;
253
+ interval?: number;
254
+ createdAt: number;
255
+ scheduledAt?: number;
256
+ startedAt?: number;
257
+ completedAt?: number;
258
+ error?: string;
259
+ };
260
+ ```
261
+
262
+ ### Horizontal Scaling
263
+
264
+ Jobs are safe to process across multiple instances. Each job is claimed atomically using Redis RPOPLPUSH, ensuring exactly-once processing.
265
+
266
+ ```
267
+ ┌─────────────┐
268
+ │ Redis │
269
+ │ (waiting) │
270
+ └──────┬──────┘
271
+
272
+ ┌─────────────────┼─────────────────┐
273
+ │ │ │
274
+ ▼ ▼ ▼
275
+ ┌─────────┐ ┌─────────┐ ┌─────────┐
276
+ │ Worker │ │ Worker │ │ Worker │
277
+ │ (Pod 1) │ │ (Pod 2) │ │ (Pod 3) │
278
+ └─────────┘ └─────────┘ └─────────┘
279
+ ```
280
+
281
+ ## Configuration
282
+
283
+ The library reads Redis connection from environment variables:
284
+
285
+ | Variable | Default |
286
+ |----------|---------|
287
+ | `REDIS_URL` | `redis://localhost:6379` |
288
+ | `VALKEY_URL` | (fallback) |
289
+
290
+ ## License
291
+
292
+ MIT
package/bun.lock ADDED
@@ -0,0 +1,29 @@
1
+ {
2
+ "lockfileVersion": 1,
3
+ "workspaces": {
4
+ "": {
5
+ "name": "sync",
6
+ "devDependencies": {
7
+ "@types/bun": "latest",
8
+ "zod": "^3.24.0",
9
+ },
10
+ "peerDependencies": {
11
+ "typescript": "^5",
12
+ "zod": "^3",
13
+ },
14
+ },
15
+ },
16
+ "packages": {
17
+ "@types/bun": ["@types/bun@1.3.8", "", { "dependencies": { "bun-types": "1.3.8" } }, "sha512-3LvWJ2q5GerAXYxO2mffLTqOzEu5qnhEAlh48Vnu8WQfnmSwbgagjGZV6BoHKJztENYEDn6QmVd949W4uESRJA=="],
18
+
19
+ "@types/node": ["@types/node@25.1.0", "", { "dependencies": { "undici-types": "~7.16.0" } }, "sha512-t7frlewr6+cbx+9Ohpl0NOTKXZNV9xHRmNOvql47BFJKcEG1CxtxlPEEe+gR9uhVWM4DwhnvTF110mIL4yP9RA=="],
20
+
21
+ "bun-types": ["bun-types@1.3.8", "", { "dependencies": { "@types/node": "*" } }, "sha512-fL99nxdOWvV4LqjmC+8Q9kW3M4QTtTR1eePs94v5ctGqU8OeceWrSUaRw3JYb7tU3FkMIAjkueehrHPPPGKi5Q=="],
22
+
23
+ "typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
24
+
25
+ "undici-types": ["undici-types@7.16.0", "", {}, "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw=="],
26
+
27
+ "zod": ["zod@3.25.76", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="],
28
+ }
29
+ }
@@ -0,0 +1,7 @@
1
+ services:
2
+ valkey:
3
+ image: docker.io/valkey/valkey:8-alpine
4
+ container_name: sync_test_valkey
5
+ command: valkey-server --save "" --appendonly no
6
+ ports:
7
+ - "6399:6379"
package/index.ts ADDED
@@ -0,0 +1,18 @@
1
+ export {
2
+ ratelimit,
3
+ RateLimitError,
4
+ type RateLimiter,
5
+ type RateLimitResult,
6
+ type RateLimitConfig,
7
+ } from "./src/ratelimit";
8
+ export { mutex, LockError, type Mutex, type Lock, type MutexConfig } from "./src/mutex";
9
+ export {
10
+ jobs,
11
+ JobsError,
12
+ ValidationError,
13
+ type Jobs,
14
+ type Job,
15
+ type JobsConfig,
16
+ type SendOptions,
17
+ type ProcessOptions,
18
+ } from "./src/jobs";
package/package.json ADDED
@@ -0,0 +1,21 @@
1
+ {
2
+ "name": "@valentinkolb/sync",
3
+ "version": "0.1.0",
4
+ "description": "General purpose sync primitives for TypeScript and Bun (ratelimit, mutex, jobs)",
5
+ "module": "index.ts",
6
+ "type": "module",
7
+ "exports": {
8
+ ".": "./index.ts"
9
+ },
10
+ "scripts": {
11
+ "test": "bun test --preload ./tests/preload.ts"
12
+ },
13
+ "peerDependencies": {
14
+ "typescript": "^5",
15
+ "zod": "^3"
16
+ },
17
+ "devDependencies": {
18
+ "@types/bun": "latest",
19
+ "zod": "^3.24.0"
20
+ }
21
+ }