Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: bound and reuse recording storage connections

Richie McIlroy30dd00e193b0
diff --git a/.github/workflows/recording-reliability.yml b/.github/workflows/recording-reliability.yml
index b3c3a78de..9b2ddfc6c 100644
--- a/.github/workflows/recording-reliability.yml
+++ b/.github/workflows/recording-reliability.yml
@@ -48,4 +48,5 @@ jobs:
__tests__/unit/media-processing-budget.test.ts \
__tests__/unit/playback-source.test.ts \
__tests__/unit/upload-progress-playback.test.ts \
- __tests__/unit/recording-prepare.test.ts
+ __tests__/unit/recording-prepare.test.ts \
+ __tests__/unit/s3-bucket-connections.test.ts
diff --git a/apps/web/__tests__/unit/s3-bucket-connections.test.ts b/apps/web/__tests__/unit/s3-bucket-connections.test.ts
new file mode 100644
index 000000000..07df81095
--- /dev/null
+++ b/apps/web/__tests__/unit/s3-bucket-connections.test.ts
@@ -0,0 +1,230 @@
+import { createServer, request as httpRequest } from "node:http";
+import type { Socket } from "node:net";
+import { S3Bucket } from "@cap/web-domain";
+import { ConfigProvider, Effect, Layer, ManagedRuntime, Option } from "effect";
+import { describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({ getById: vi.fn() }));
+
+vi.mock("@cap/database/crypto", () => ({
+ decrypt: async (value: string) => value,
+}));
+vi.mock("@cap/web-backend/src/Database.ts", async () => {
+ const { Effect } = await import("effect");
+ class Database extends Effect.Service<Database>()("Database", {
+ sync: () => ({}),
+ }) {}
+ return { Database };
+});
+vi.mock("@cap/web-backend/src/Aws.ts", async () => {
+ const { Effect } = await import("effect");
+ class AwsCredentials extends Effect.Service<AwsCredentials>()(
+ "AwsCredentials",
+ {
+ sync: () => ({
+ credentials: {
+ accessKeyId: "default-key",
+ secretAccessKey: "test-secret",
+ },
+ }),
+ },
+ ) {}
+ return { AwsCredentials };
+});
+vi.mock("@cap/web-backend/src/S3Buckets/S3BucketsRepo.ts", async () => {
+ const { Effect } = await import("effect");
+ class S3BucketsRepo extends Effect.Service<S3BucketsRepo>()("S3BucketsRepo", {
+ sync: () => ({ getById: mocks.getById }),
+ }) {}
+ return { S3BucketsRepo };
+});
+
+import { S3Buckets } from "@cap/web-backend/src/S3Buckets";
+import { s3ConnectionPool } from "@cap/web-backend/src/S3Buckets/S3ConnectionPool";
+
+async function storageFixture() {
+ let connections = 0;
+ const sockets = new Set<Socket>();
+ const authorizations: string[] = [];
+ const server = createServer((request, response) => {
+ authorizations.push(request.headers.authorization ?? "");
+ response.writeHead(200, {
+ "Content-Length": "1",
+ ETag: '"source-identity"',
+ });
+ response.end();
+ });
+ server.on("connection", (socket) => {
+ connections++;
+ sockets.add(socket);
+ socket.on("close", () => sockets.delete(socket));
+ });
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+ const address = server.address();
+ if (!address || typeof address === "string") throw new Error("Missing port");
+ const endpoint = `http://127.0.0.1:${address.port}`;
+ const runtime = ManagedRuntime.make(
+ S3Buckets.Default.pipe(
+ Layer.provide(
+ Layer.setConfigProvider(
+ ConfigProvider.fromMap(
+ new Map([
+ ["CAP_AWS_REGION", "us-east-1"],
+ ["CAP_AWS_BUCKET", "capso"],
+ ["S3_INTERNAL_ENDPOINT", endpoint],
+ ["S3_PUBLIC_ENDPOINT", endpoint],
+ ]),
+ ),
+ ),
+ ),
+ ),
+ );
+ const service = await runtime.runPromise(S3Buckets);
+ return {
+ endpoint,
+ runtime,
+ service,
+ authorizations,
+ connections: () => connections,
+ async close() {
+ await runtime.dispose();
+ for (const socket of sockets) socket.destroy();
+ await new Promise<void>((resolve, reject) =>
+ server.close((error) => (error ? reject(error) : resolve())),
+ );
+ },
+ };
+}
+
+describe("S3 connection reuse", () => {
+ it("bounds connections across simultaneous recording checkpoints", async () => {
+ const fixture = await storageFixture();
+ try {
+ await Promise.all(
+ Array.from({ length: 24 }, async (_, recording) => {
+ const [access] = await fixture.runtime.runPromise(
+ fixture.service.getBucketAccess(Option.none()),
+ );
+ await Promise.all(
+ Array.from({ length: 8 }, (_, index) =>
+ fixture.runtime.runPromise(
+ access.headObject(`recording/${recording}/${index}`),
+ ),
+ ),
+ );
+ }),
+ );
+ expect(fixture.authorizations).toHaveLength(192);
+ expect(fixture.connections()).toBeLessThanOrEqual(50);
+ } finally {
+ await fixture.close();
+ }
+ });
+
+ it("expires idle connections, clears their timer on reuse, and closes on disposal", async () => {
+ const fixture = await storageFixture();
+ try {
+ const socket = await Effect.runPromise(
+ Effect.scoped(
+ Effect.gen(function* () {
+ const pool = yield* s3ConnectionPool;
+ return yield* Effect.promise(async () => {
+ const send = () =>
+ new Promise<{ socket: Socket; timeout: number | undefined }>(
+ (resolve, reject) => {
+ let acquired: Socket | undefined;
+ let timeout: number | undefined;
+ const request = httpRequest(fixture.endpoint, {
+ method: "HEAD",
+ agent: pool.httpAgent,
+ });
+ request.on("socket", (socket) => {
+ acquired = socket;
+ timeout = socket.timeout;
+ });
+ request.on("response", (response) => {
+ response.on("end", () => {
+ if (acquired) resolve({ socket: acquired, timeout });
+ else reject(new Error("Missing connection"));
+ });
+ response.resume();
+ });
+ request.on("error", reject);
+ request.end();
+ },
+ );
+ const first = await send();
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ expect(first.socket.timeout).toBeGreaterThan(0);
+ expect(first.socket.timeout).toBeLessThanOrEqual(30_000);
+ const second = await send();
+ expect(second.socket).toBe(first.socket);
+ expect(second.timeout).toBe(0);
+ return first.socket;
+ });
+ }),
+ ),
+ );
+ expect(socket.destroyed).toBe(true);
+ } finally {
+ await fixture.close();
+ }
+ });
+
+ it("does not grow connections with every recording checkpoint", async () => {
+ const fixture = await storageFixture();
+ try {
+ for (let checkpoint = 0; checkpoint < 40; checkpoint++) {
+ const [access] = await fixture.runtime.runPromise(
+ fixture.service.getBucketAccess(Option.none()),
+ );
+ await Promise.all(
+ Array.from({ length: 8 }, (_, index) =>
+ fixture.runtime.runPromise(
+ access.headObject(`recording/${checkpoint}/${index}`),
+ ),
+ ),
+ );
+ }
+ expect(fixture.authorizations).toHaveLength(320);
+ expect(fixture.connections()).toBeLessThanOrEqual(16);
+ } finally {
+ await fixture.close();
+ }
+ });
+
+ it("reuses custom bucket connections while using current credentials", async () => {
+ const fixture = await storageFixture();
+ try {
+ for (let revision = 0; revision < 40; revision++) {
+ mocks.getById.mockReturnValue(
+ Effect.succeed(
+ Option.some(
+ S3Bucket.decodeSync({
+ id: "custom-bucket",
+ ownerId: "owner",
+ region: "us-east-1",
+ endpoint: fixture.endpoint,
+ name: "custom-storage",
+ accessKeyId: `rotated-key-${revision}`,
+ secretAccessKey: "custom-secret",
+ }),
+ ),
+ ),
+ );
+ const [access] = await fixture.runtime.runPromise(
+ fixture.service.getBucketAccess(
+ Option.some(S3Bucket.S3BucketId.make("custom-bucket")),
+ ),
+ );
+ await fixture.runtime.runPromise(access.headObject("fragment.m4s"));
+ expect(fixture.authorizations.at(-1)).toContain(
+ `Credential=rotated-key-${revision}/`,
+ );
+ }
+ expect(fixture.connections()).toBeLessThanOrEqual(2);
+ } finally {
+ await fixture.close();
+ }
+ });
+});
diff --git a/packages/web-backend/src/S3Buckets/S3ConnectionPool.ts b/packages/web-backend/src/S3Buckets/S3ConnectionPool.ts
new file mode 100644
index 000000000..be0a15c8a
--- /dev/null
+++ b/packages/web-backend/src/S3Buckets/S3ConnectionPool.ts
@@ -0,0 +1,41 @@
+import { Agent as HttpAgent } from "node:http";
+import { Agent as HttpsAgent } from "node:https";
+import { Socket } from "node:net";
+import { Effect } from "effect";
+
+function boundIdleConnections<T extends HttpAgent>(agent: T) {
+ // Idle custom hosts must release their slots without timing out an active copy.
+ const keepSocketAlive = agent.keepSocketAlive.bind(agent);
+ const reuseSocket = agent.reuseSocket.bind(agent);
+ agent.keepSocketAlive = (socket) => {
+ const keep: unknown = keepSocketAlive(socket);
+ if (keep !== false && socket instanceof Socket)
+ socket.setTimeout(Math.min(socket.timeout || 30_000, 30_000));
+ return keep;
+ };
+ agent.reuseSocket = (socket, request) => {
+ if (socket instanceof Socket) socket.setTimeout(0);
+ reuseSocket(socket, request);
+ };
+ return agent;
+}
+
+export const s3ConnectionPool = Effect.acquireRelease(
+ Effect.sync(() => {
+ const options = {
+ keepAlive: true,
+ maxSockets: 50,
+ maxTotalSockets: 128,
+ maxFreeSockets: 8,
+ };
+ return {
+ httpAgent: boundIdleConnections(new HttpAgent(options)),
+ httpsAgent: boundIdleConnections(new HttpsAgent(options)),
+ };
+ }),
+ (pool) =>
+ Effect.sync(() => {
+ pool.httpAgent.destroy();
+ pool.httpsAgent.destroy();
+ }),
+);
diff --git a/packages/web-backend/src/S3Buckets/index.ts b/packages/web-backend/src/S3Buckets/index.ts
index 64a6c481b..49ecb912e 100644
--- a/packages/web-backend/src/S3Buckets/index.ts
+++ b/packages/web-backend/src/S3Buckets/index.ts
@@ -10,11 +10,13 @@ import { Database } from "../Database.ts";
import { createS3BucketAccess } from "./S3BucketAccess.ts";
import { S3BucketClientProvider } from "./S3BucketClientProvider.ts";
import { S3BucketsRepo } from "./S3BucketsRepo.ts";
+import { s3ConnectionPool } from "./S3ConnectionPool.ts";
export class S3Buckets extends Effect.Service<S3Buckets>()("S3Buckets", {
- effect: Effect.gen(function* () {
+ scoped: Effect.gen(function* () {
const repo = yield* S3BucketsRepo;
const { credentials } = yield* AwsCredentials;
+ const requestHandler = yield* s3ConnectionPool;
const defaultConfigs = {
publicEndpoint: yield* Config.string("S3_PUBLIC_ENDPOINT").pipe(
@@ -43,7 +45,10 @@ export class S3Buckets extends Effect.Service<S3Buckets>()("S3Buckets", {
credentials: defaultConfigs.credentials,
forcePathStyle: defaultConfigs.forcePathStyle,
requestStreamBufferSize: 16 * 1024,
+ requestHandler,
});
+ const defaultInternalClient = createDefaultClient(true);
+ const defaultPublicClient = createDefaultClient(false);
const endpointIsPathStyle = (endpoint: string, bucket: string) => {
try {
@@ -78,6 +83,7 @@ export class S3Buckets extends Effect.Service<S3Buckets>()("S3Buckets", {
Option.getOrNull,
) ?? true,
useArnRegion: false,
+ requestHandler,
});
};
@@ -142,8 +148,8 @@ export class S3Buckets extends Effect.Service<S3Buckets>()("S3Buckets", {
const bucketAccess = yield* Option.match(customBucket, {
onNone: () => {
const provider = Layer.succeed(S3BucketClientProvider, {
- getInternal: Effect.succeed(createDefaultClient(true)),
- getPublic: Effect.succeed(createDefaultClient(false)),
+ getInternal: Effect.succeed(defaultInternalClient),
+ getPublic: Effect.succeed(defaultPublicClient),
bucket: defaultConfigs.bucket,
isPathStyle: defaultConfigs.forcePathStyle,
});