Skip to content
This repository was archived by the owner on Oct 22, 2025. It is now read-only.
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions examples/counter-serverless/scripts/connect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ import type { Registry } from "../src/registry";
async function main() {
const client = createClient<Registry>("http://localhost:6420");

const counter = client.counter.getOrCreate().connect();
const counter = client.counter.getOrCreate();

counter.on("newCount", (count: number) => console.log("Event:", count));
// counter.on("newCount", (count: number) => console.log("Event:", count));

for (let i = 0; i < 5; i++) {
const out = await counter.increment(5);
Expand All @@ -16,7 +16,7 @@ async function main() {
}

await new Promise((resolve) => setTimeout(resolve, 10000));
await counter.dispose();
// await counter.dispose();
}

main();
2 changes: 2 additions & 0 deletions examples/smoke-test/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
.actorcore
node_modules
39 changes: 39 additions & 0 deletions examples/smoke-test/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Smoke Test for RivetKit

Example project demonstrating a simple getOrCreate smoke test with [RivetKit](https://rivetkit.org).

[Learn More →](https://github.com/rivet-dev/rivetkit)

[Discord](https://rivet.dev/discord) — [Documentation](https://rivetkit.org) — [Issues](https://github.com/rivet-dev/rivetkit/issues)

## Getting Started

### Prerequisites

- Node.js

### Installation

```sh
git clone https://github.com/rivet-dev/rivetkit
cd rivetkit/examples/smoke-test
npm install
```

### Development

```sh
npm run dev
```

Run the smoke test to exercise multiple actor creations:

```sh
npm run smoke
```

Set `TOTAL_ACTOR_COUNT` and `SPAWN_ACTOR_INTERVAL` environment variables to adjust the workload.

## License

Apache 2.0
19 changes: 19 additions & 0 deletions examples/smoke-test/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"name": "example-smoke-test",
"version": "2.0.8",
"private": true,
"type": "module",
"scripts": {
"dev": "tsx src/server/server.ts",
"check-types": "tsc --noEmit",
"smoke": "tsx src/smoke-test/index.ts",
"connect": "tsx scripts/connect.ts"
},
"devDependencies": {
"rivetkit": "workspace:*",
"@types/node": "^22.13.9",
"tsx": "^3.12.7",
"typescript": "^5.7.3"
},
"stableVersion": "0.8.0"
}
22 changes: 22 additions & 0 deletions examples/smoke-test/scripts/connect.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { createClient } from "rivetkit/client";
import type { Registry } from "../src/registry";

async function main() {
const client = createClient<Registry>("http://localhost:6420");

const counter = client.counter.getOrCreate().connect();

counter.on("newCount", (count: number) => console.log("Event:", count));

for (let i = 0; i < 5; i++) {
const out = await counter.increment(5);
console.log("RPC:", out);

await new Promise((resolve) => setTimeout(resolve, 1000));
}

await new Promise((resolve) => setTimeout(resolve, 10000));
await counter.dispose();
}

main();
23 changes: 23 additions & 0 deletions examples/smoke-test/src/server/registry.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { actor, setup } from "rivetkit";

const counter = actor({
state: {
count: 0,
},
actions: {
increment: (c, x: number) => {
c.state.count += x;
c.broadcast("newCount", c.state.count);
return c.state.count;
},
getCount: (c) => {
return c.state.count;
},
},
});

export const registry = setup({
use: { counter },
});

export type Registry = typeof registry;
3 changes: 3 additions & 0 deletions examples/smoke-test/src/server/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { registry } from "./registry";

registry.start();
151 changes: 151 additions & 0 deletions examples/smoke-test/src/smoke-test/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
import { randomUUID } from "node:crypto";
import { createClient } from "rivetkit/client";
import type { Registry } from "../server/registry";
import { type SmokeTestError, spawnActor } from "./spawn-actor";

function parseEnvInt(value: string | undefined, fallback: number) {
const parsed = Number(value);
if (!Number.isFinite(parsed) || parsed <= 0) {
return fallback;
}
return Math.floor(parsed);
}

const RUN_DURATION = parseEnvInt(process.env.RUN_DURATION, 10_000);
const SPAWN_ACTOR_INTERVAL = parseEnvInt(process.env.SPAWN_ACTOR_INTERVAL, 10);
const TOTAL_ACTOR_COUNT = Math.ceil(RUN_DURATION / SPAWN_ACTOR_INTERVAL);
const PROGRESS_LOG_INTERVAL_MS = 250;

type DurationStats = {
average: number;
median: number;
min: number;
max: number;
};

async function delay(ms: number) {
return new Promise<void>((resolve) => setTimeout(resolve, ms));
}

function calculateDurationStats(durations: number[]): DurationStats {
if (durations.length === 0) {
return { average: 0, median: 0, min: 0, max: 0 };
}

const sorted = [...durations].sort((left, right) => left - right);
const count = sorted.length;
const sum = sorted.reduce((runningSum, duration) => runningSum + duration, 0);
const average = sum / count;
const min = sorted[0];
const max = sorted[count - 1];
const median =
count % 2 === 0
? (sorted[count / 2 - 1] + sorted[count / 2]) / 2
: sorted[Math.floor(count / 2)];

return { average, median, min, max };
}

function logProgress({
totalActorCount,
startedCount,
successCount,
failureCount,
iterationDurations,
}: {
totalActorCount: number;
startedCount: number;
successCount: number;
failureCount: number;
iterationDurations: number[];
}) {
const stats = calculateDurationStats(iterationDurations);
const remainingCount = totalActorCount - startedCount;
const pendingCount = Math.max(
0,
startedCount - (successCount + failureCount),
);
console.log(
`progress: success=${successCount}, failures=${failureCount}, pending=${pendingCount}, remaining=${remainingCount}, duration(ms): avg=${stats.average.toFixed(2)}, median=${stats.median.toFixed(2)}, min=${stats.min.toFixed(2)}, max=${stats.max.toFixed(2)}`,
);
}

async function main() {
const client = createClient<Registry>("http://localhost:6420");
const testId = randomUUID();
const errors: SmokeTestError[] = [];
let successCount = 0;
let failureCount = 0;
let startedCount = 0;
const iterationDurations: number[] = [];
const logProgressTick = () =>
logProgress({
totalActorCount: TOTAL_ACTOR_COUNT,
startedCount,
successCount,
failureCount,
iterationDurations,
});

console.log(
`starting smoke test (run duration: ${RUN_DURATION}ms, interval: ${SPAWN_ACTOR_INTERVAL}ms, expected actors: ${TOTAL_ACTOR_COUNT}, test id: ${testId})`,
);

const pendingActors: Promise<void>[] = [];
const progressInterval = setInterval(
logProgressTick,
PROGRESS_LOG_INTERVAL_MS,
);
logProgressTick();

try {
for (let index = 0; index < TOTAL_ACTOR_COUNT; index++) {
startedCount += 1;
pendingActors.push(
spawnActor({
client,
index,
testId,
errors,
iterationDurations,
onSuccess: () => {
successCount += 1;
},
onFailure: () => {
failureCount += 1;
},
}),
);
if (index < TOTAL_ACTOR_COUNT - 1) {
await delay(SPAWN_ACTOR_INTERVAL);
}
}

await Promise.all(pendingActors);
} finally {
clearInterval(progressInterval);
}

logProgressTick();

const finalStats = calculateDurationStats(iterationDurations);
console.log(
`iteration duration stats (ms): avg=${finalStats.average.toFixed(2)}, median=${finalStats.median.toFixed(2)}, min=${finalStats.min.toFixed(2)}, max=${finalStats.max.toFixed(2)}`,
);

if (errors.length > 0) {
console.error(`completed with ${errors.length} error(s)`);
errors.forEach(({ index, error }) => {
console.error(`[${index}] captured error`, error);
});
process.exitCode = 1;
return;
}

console.log("smoke test completed successfully");
}

main().catch((error) => {
console.error("fatal error", error);
process.exit(1);
});
51 changes: 51 additions & 0 deletions examples/smoke-test/src/smoke-test/spawn-actor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { performance } from "node:perf_hooks";
import type { createClient } from "rivetkit/client";
import type { Registry } from "../server/registry";

export type SmokeTestError = {
index: number;
error: unknown;
};

export type RegistryClient = ReturnType<typeof createClient<Registry>>;

export type SpawnActorOptions = {
client: RegistryClient;
index: number;
testId: string;
errors: SmokeTestError[];
iterationDurations: number[];
onSuccess: () => void;
onFailure: () => void;
};

export async function spawnActor({
client,
index,
testId,
errors,
iterationDurations,
onSuccess,
onFailure,
}: SpawnActorOptions): Promise<void> {
const iterationStart = performance.now();
let succeeded = false;

try {
const key = ["test", testId, index.toString()];
const counter = client.counter.getOrCreate(key).connect();
await counter.increment(1);
await counter.dispose();
succeeded = true;
onSuccess();
} catch (error) {
errors.push({ index, error });
onFailure();
}

if (succeeded) {
const iterationEnd = performance.now();
const iterationDuration = iterationEnd - iterationStart;
iterationDurations.push(iterationDuration);
}
}
43 changes: 43 additions & 0 deletions examples/smoke-test/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */

/* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
"target": "esnext",
/* Specify a set of bundled library declaration files that describe the target runtime environment. */
"lib": ["esnext"],
/* Specify what JSX code is generated. */
"jsx": "react-jsx",

/* Specify what module code is generated. */
"module": "esnext",
/* Specify how TypeScript looks up a file from a given module specifier. */
"moduleResolution": "bundler",
/* Specify type package names to be included without being referenced in a source file. */
"types": ["node"],
/* Enable importing .json files */
"resolveJsonModule": true,

/* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */
"allowJs": true,
/* Enable error reporting in type-checked JavaScript files. */
"checkJs": false,

/* Disable emitting files from a compilation. */
"noEmit": true,

/* Ensure that each file can be safely transpiled without relying on other imports. */
"isolatedModules": true,
/* Allow 'import x from y' when a module doesn't have a default export. */
"allowSyntheticDefaultImports": true,
/* Ensure that casing is correct in imports. */
"forceConsistentCasingInFileNames": true,

/* Enable all strict type-checking options. */
"strict": true,

/* Skip type checking all .d.ts files. */
"skipLibCheck": true
},
"include": ["src/**/*.ts", "tests/**/*.ts"]
}
4 changes: 4 additions & 0 deletions examples/smoke-test/turbo.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"$schema": "https://turbo.build/schema.json",
"extends": ["//"]
}
2 changes: 1 addition & 1 deletion packages/next-js/src/mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export const toNextHandler = (
const publicUrl =
process.env.NEXT_PUBLIC_SITE_URL ??
process.env.NEXT_PUBLIC_VERCEL_URL ??
`http://127.0.0.1:${process.env.PORT ?? 8080}`;
`http://127.0.0.1:${process.env.PORT ?? 3000}`;
inputConfig.runnerKind = "serverless";
inputConfig.runEngine = true;
inputConfig.autoConfigureServerless = {
Expand Down
Loading
Loading