Skip to content
Back to search

forge

The standard library for agent-built SaaS

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/isala404-forge/badge.svg)](/listings/isala404-forge)

HTML

<a href="/listings/isala404-forge"><img src="/api/listings/isala404-forge/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 282 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # Forge
  2. [![CI](https://img.shields.io/github/actions/workflow/status/isala404/forge/ci.yml?branch=main&style=flat-square&logo=github&label=CI)](https://github.com/isala404/forge/actions/workflows/ci.yml) [![crates.io](https://img.shields.io/crates/v/forgelib?style=flat-square&logo=rust&logoColor=white)](https://crates.io/crates/forgelib) [![npm](https://img.shields.io/npm/v/forgelib?style=flat-square&logo=npm&logoColor=white)](https://www.npmjs.com/package/forgelib) [![PyPI](https://img.shields.io/pypi/v/forgelib?style=flat-square&logo=pypi&logoColor=white)](https://pypi.org/project/forgelib/) [![PostgreSQL 18](https://img.shields.io/badge/PostgreSQL-18-4169E1?style=flat-square&logo=postgresql&logoColor=white)](https://www.postgresql.org/) [![MIT License](https://img.shields.io/github/license/isala404/forge?style=flat-square&color=blue)](./LICENSE)
  3. Forge is a backend infrastructure library for Rust, Node.js and Bun, Python, and Go. It provides queues, key/value storage, blobs, authentication helpers, rate limits, scheduling, configuration, and pub/sub through one versioned contract.
  4. Most applications need the same backend plumbing:
  5. - Redis for caching and sessions
  6. - a queue for background jobs
  7. - object storage for uploads
  8. - an auth service for logins and sessions
  9. - a cron runner for scheduled work
  10. - a rate limiter
  11. Each separate service adds another deployment, security boundary, test double, and failure mode.
  12. Forge keeps these primitives inside the backend process. PostgreSQL is the shared durable backend, memory is the process-local test backend, filesystem storage is available for local blob data, and S3-compatible storage handles larger blob workloads. Forge 1.1 is the compatibility baseline; later 1.x releases move in lockstep and reserve breaking changes for 2.0.
  13. ## Ownership boundary
  14. Forge owns its public contract, backend implementations, schema and migration validation, bounded payload formats, worker leases, retries, lifecycle, diagnostics, metrics, and trace propagation.
  15. The application owns HTTP or RPC routes, business data, authorization policy, worker handlers, process signals, deployment, MCP transport, and observability export. It also owns every frontend choice: framework, browser transport, WebSocket or SSE client, cache, TanStack Query setup, optimistic state, reconnect behavior, and refetch policy. Forge can encode and publish a bounded server-side invalidation hint, but the application decides whether and how that hint reaches a client.
  16. The exact consistency, durability, ordering, expiry, and retry rules are in the [semantics guide](https://tryforge.dev/semantics/). Security-sensitive ownership is in the [security guide](https://tryforge.dev/security/).
  17. ## One connection, eight backend primitives
  18. ```bash
  19. npm install forgelib
  20. ```
  21. Configuration lives in a `forge.toml` at your project root. `init()` reads it and instantiates the runtime; string values may reference the environment as `${VAR}`:
  22. ```toml
  23. [postgres]
  24. url = "${DATABASE_URL:-}"
  25. embedded = true
  26. ```
  27. Set `DATABASE_URL` to use a managed or shared PostgreSQL 18 server. Leave it unset and Forge downloads and runs PostgreSQL 18 for you (data persists in `.forge/pg`) — built into the Node and Python packages, behind the `embedded` cargo feature in Rust.
  28. Omit settings you do not need; Forge applies production-safe defaults for the rest.
  29. Development and test startup migrate automatically. Production defaults to validation-only startup: run `ForgeClient.migrate()` (or the Rust, Python, or Go equivalent) in the deployment job, require every structured report to be `applied`, then start the application. `migration_lock_timeout_secs` bounds advisory-lock waiting, and [`contract/schema-ownership.json`](contract/schema-ownership.json) lists every Forge-owned object.
  30. ```ts
  31. import { ForgeClient } from "forgelib";
  32. const forge = await ForgeClient.init(); // instantiates the runtime from ./forge.toml
  33. // auth: argon2 password hashing, sessions, one-time tokens (password reset, magic links)
  34. const hash = await forge.hashPassword(password);
  35. const session = await forge.createSession(userId);
  36. const reset = await forge.createToken(userId, "password-reset", 900); // consumeToken later, once
  37. // rate limit: 20 attempts per minute, keyed by email
  38. const limit = await forge.rateLimitCheck("login", email, 20, 60);
  39. if (!limit.allowed) throw new Error("slow down");
  40. // key/value: TTL cache and atomic counters
  41. await forge.kv<typeof profile>(`user:${userId}`).set(profile, { ttlSeconds: 3600 });
  42. const views = await forge.kvIncr(`views:${userId}`, 1);
  43. // queue: background jobs
  44. await forge.queue<{ to: string }>("emails").enqueue({ to: email });
  45. // pub/sub: fan an event out to subscribers
  46. await forge.topic<{ userId: string }>("user.created").publish({ userId });
  47. // blob: store a file, hand back a link that expires in an hour
  48. await forge.blobPut(`exports/${userId}.csv`, csv, "text/csv");
  49. const link = (await forge.blobPresignDownload(`exports/${userId}.csv`, 3600)).url;
  50. // schedule: recurring work on a cron
  51. await forge.scheduleCron("nightly-report", "0 0 * * *", "reports", "{}");
  52. // feature flags: roll a feature out to 25% of users
  53. await forge.setFlagPercent("new-ui", 25);
  54. const newUi = await forge.flag("new-ui", false, userId);
  55. ```
  56. <details>
  57. <summary>The same in Rust</summary>
  58. ```bash
  59. cargo add forgelib
  60. ```
  61. ```rust
  62. use std::time::Duration;
  63. use forgelib::{
  64. Forge, Bytes, SetOpts, EnqueueOpts, PutOpts,
  65. ScheduleOpts, SessionOpts, Limit, FlagRule, EvalCtx,
  66. };
  67. let forge = Forge::init().await?; // instantiates the runtime from ./forge.toml
  68. // auth
  69. let hash = forge.auth().hash_password(&password).await?;
  70. let session = forge.auth().create_session(&user_id, SessionOpts::default()).await?;
  71. let reset = forge.auth().create_token(&user_id, "password-reset", Duration::from_secs(900)).await?;
  72. // rate limit
  73. let limit = forge.ratelimit()
  74. .check("login", &email, Limit::per_duration(20, Duration::from_secs(60)))
  75. .await?;
  76. // key/value
  77. forge.kv().set(&format!("user:{user_id}"), profile.into(),
  78. SetOpts::new().with_ttl(Duration::from_secs(3600))).await?;
  79. let views = forge.kv().incr(&format!("views:{user_id}"), 1).await?;
  80. // queue
  81. forge.queue().enqueue("emails", payload.into(), EnqueueOpts::new()).await?;
  82. // pub/sub
  83. forge.pubsub().publish("user.created", Bytes::from(event)).await?;
  84. // blob
  85. forge.blob().put(&key, body, PutOpts::new()).await?;
  86. let link = forge.blob().presign_download(&key, Duration::from_secs(3600)).await?.url;
  87. // schedule
  88. forge.schedule().cron("nightly-report", "0 0 * * *", "reports", Bytes::new(), ScheduleOpts::new()).await?;
  89. // feature flags
  90. forge.config().set_flag("new-ui", FlagRule::Percent(25)).await?;
  91. let new_ui = forge.config().flag("new-ui", false, &EvalCtx::user(user_id)).await;
  92. ```
  93. </details>
  94. <details>
  95. <summary>The same in Go</summary>
  96. ```bash
  97. go get github.com/isala404/forge/bindings/go
  98. ```
  99. ```go
  100. import (
  101. "context"
  102. "time"
  103. forge "github.com/isala404/forge/bindings/go"
  104. )
  105. client, err := forge.InitFrom(context.Background(), "forge.toml")
  106. if err != nil { return err }
  107. defer client.Close(context.Background())
  108. hash, err := client.HashPassword(context.Background(), password)
  109. session, err := client.CreateSession(context.Background(), userID, forge.SessionOptions{})
  110. reset, err := client.CreateToken(context.Background(), userID, "password-reset", 15*time.Minute)
  111. limit, err := client.RateLimitCheck(context.Background(), "login", email, forge.RateLimitOptions{Max: 20, Per: time.Minute})
  112. if !limit.Allowed { return errTooManyRequests }
  113. ttl := time.Hour
  114. _, err = client.KVSet(context.Background(), "user:"+userID, profile, forge.SetOptions{TTL: &ttl})
  115. views, err := client.KVIncr(context.Background(), "views:"+userID, 1)
  116. _, err = client.Enqueue(context.Background(), "emails", payload, forge.EnqueueOptions{})
  117. err = client.Publish(context.Background(), "user.created", event)
  118. err = client.BlobPut(context.Background(), "exports/"+userID+".csv", csv, forge.PutOptions{ContentType: "text/csv"})
  119. err = client.ScheduleCron(context.Background(), "nightly-report", "0 0 * * *", "reports", nil, forge.ScheduleOptions{})
  120. err = client.SetFlag(context.Background(), "new-ui", forge.FlagRule{Kind: forge.FlagPercent, Percent: 25})
  121. newUI := client.Flag(context.Background(), "new-ui", false, userID)
  122. ```
  123. </details>
  124. <details>
  125. <summary>The same in Python</summary>
  126. ```bash
  127. pip install forgelib
  128. ```
  129. ```python
  130. import forgelib
  131. forge = await forgelib.ForgeClient.init() # instantiates the runtime from ./forge.toml
  132. # auth
  133. hash = await forge.hash_password(password)
  134. session = await forge.create_session(user_id)
  135. reset = await forge.create_token(user_id, "password-reset", 900) # consume_token later, once
  136. # rate limit
  137. limit = await forge.rate_limit_check("login", email, 20, 60)
  138. if not limit.allowed:
  139. raise RuntimeError("slow down")
  140. # key/value
  141. await forge.kv(f"user:{user_id}").set(profile, ttl_seconds=3600)
  142. views = await forge.kv_incr(f"views:{user_id}", 1)
  143. # queue
  144. await forge.queue("emails").enqueue({"to": email})
  145. # pub/sub
  146. await forge.topic("user.created").publish({"user_id": user_id})
  147. # blob
  148. await forge.blob_put(f"exports/{user_id}.csv", csv, "text/csv")
  149. link = (await forge.blob_presign_download(f"exports/{user_id}.csv", 3600)).url
  150. # schedule
  151. await forge.schedule_cron("nightly-report", "0 0 * * *", "reports", "{}")
  152. # feature flags
  153. await forge.set_flag_percent("new-ui", 25)
  154. new_ui = await forge.flag("new-ui", False, user_id)
  155. ```
  156. </details>
  157. ## What you get
  158. | Primitive | What it does |
  159. | --- | --- |
  160. | key/value | get, set, mget, incr, compare-and-swap, prefix scan, TTLs |
  161. | queue | deterministic enqueue, managed workers, retries, dead-letter operations, depth/age, transactional outbox relay |
  162. | pub/sub | publish and subscribe on topics |
  163. | blob | put, get, delete, presigned upload and download URLs |
  164. | auth | password hashing, sessions, API keys |
  165. | rate limit | token-bucket or sliding-window checks |
  166. | schedule | cron and one-off jobs |
  167. | config | settings and feature flags with percentage rollout |
  168. Typed flags include stable variants and OpenFeature evaluation details. Official provider adapters ship for Rust, Node, Python, and Go, with application-scoped OpenTelemetry evaluation hooks. Bulk reads avoid per-key startup queries, while explicitly expiring snapshots support bounded disconnected reads without turning stale config into a silent source of truth.
  169. Schedules use canonical UTC instants, deterministic occurrence job IDs, named pause/resume/inspect controls, and bounded diagnostics. Late work follows an explicit `skip`, `run_once` (default), or `catch_up` policy capped at 100; Forge does not model workflow dependencies or multi-step state.
  170. State-free CloudEvents 1.0 structured-JSON and explicit environment alias adapters ship in all four languages. Framework, deployment, MCP, artifact, cancellation, trace-correlation, and authenticated diagnostics patterns live in the [integration recipes](https://tryforge.dev/integrations/) so protocol and runtime dependencies stay outside Forge core.
  171. By default every primitive runs on one Postgres database, so there's nothing else to operate. When measurements justify a bulkhead, a hot primitive can use a separate PostgreSQL target while keeping the same coordinated schema and behavior.
  172. ## Test on memory, ship on Postgres
  173. The explicit memory and PostgreSQL profiles pass the same conformance suite, so tests run in-process without a database while application code keeps the same primitive APIs. Memory is process-local and non-durable; PostgreSQL is the normal production profile.
  174. ```toml
  175. [forge]
  176. mode = "memory"
  177. environment = "test"
  178. ```
  179. For expiry and retry tests, every language also exposes a memory test factory with a manual clock and seeded entropy. Advancing the test clock drives TTLs, delayed jobs, rate-limit refill, schedules, sessions, and tokens without sleeping; seeded entropy must never mint production credentials.
  180. ## Agent integration
  181. The repository includes a `forge-idiomatic-developer` skill with the supported contract and language conventions.
  182. ```bash
  183. npx skills add isala404/forge
  184. ```
  185. The skill is a development aid. It does not add runtime code or change the backend contract.
  186. ## Not in scope
  187. - The APIs are a shared subset, not a full reimplementation. Key/value does not expose Lua or sorted sets. Blob does not manage S3 lifecycle, replication, legal hold, or CDN behavior.
  188. - Auth provides password hashing, sessions, API keys, and one-time tokens. OAuth, OIDC, MFA, email delivery, account policy, cookies, CSRF protection, and authorization remain application concerns.
  189. - Forge ships a PostgreSQL production profile, a complete memory test profile, and local disk for blob development. Rust supports compile-time trait injection as an advanced extension; Forge has no dynamic backend loader.
  190. - Forge is not an ORM, web framework, frontend package, durable event log, or workflow engine. Application tables, routes, transports, and user interfaces stay outside the library.
  191. ## Examples
  192. The repository keeps one canonical application example per language and runs each in CI: Rust todo, Node chat, Python links, and the pure-Go worker example.
  193. Performance work is also executable: the [performance and scaling guide](https://tryforge.dev/performance/) covers release-mode backend workloads, all five supported runtime boundaries, JSON regression budgets, multi-process PostgreSQL contention, and role-specific pool sizing.
  194. ## License
  195. MIT. Do whatever you want.
  196. <p align="center">
  197. <strong>Postgres is enough.</strong><br>
  198. <a href="#one-connection-the-backend-primitives-most-applications-need">Quick Start</a> ·
  199. <a href="#examples">Examples</a> ·
  200. <a href="https://github.com/isala404/forge/discussions">Discussions</a>
  201. </p>

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.