# Platform Integration Patterns - Effect Library ## ๐ŸŽฏ OVERVIEW Patterns for integrating platform-specific functionality within the Effect ecosystem, including service abstractions, layer compositions, and cross-platform compatibility. ## ๐Ÿ—๏ธ SERVICE ABSTRACTION PATTERN ### Core Service Interface Definition Define platform-agnostic interfaces in the core Effect package: ```typescript // packages/effect/src/platform/FileSystem.ts export interface FileSystem { readonly [TypeId]: TypeId readonly access: (path: string, options?: AccessFileOptions) => Effect.Effect readonly readFile: (path: string) => Effect.Effect readonly writeFile: (path: string, data: Uint8Array) => Effect.Effect readonly stat: (path: string) => Effect.Effect readonly mkdir: (path: string, options?: MakeDirectoryOptions) => Effect.Effect readonly readdir: (path: string) => Effect.Effect, PlatformError> readonly rm: (path: string, options?: RemoveOptions) => Effect.Effect readonly watch: (path: string) => Stream.Stream } // Service key for dependency injection export const FileSystem: ServiceMap.Service = ServiceMap.Service("effect/platform/FileSystem") // Type identification const TypeId: unique symbol = Symbol.for("effect/platform/FileSystem") export type TypeId = typeof TypeId ``` ### Tagged Service Pattern Use service classes for type-safe dependency injection: ```typescript // HTTP platform service export class HttpPlatform extends ServiceMap.Service Effect.Effect readonly fileWebResponse: (file: FileLike, options?: FileWebResponseOptions) => Effect.Effect readonly formData: (source: Readable) => Effect.Effect }>()("effect/http/HttpPlatform") {} // Socket service export class NetSocket extends ServiceMap.Service()( "@effect/platform-node/NodeSocket/NetSocket" ) {} ``` ## ๐Ÿ”ง PLATFORM IMPLEMENTATION PATTERN ### Node.js Implementation Structure ```typescript // packages/platform-node-shared/src/NodeFileSystem.ts import { Effect, Layer } from "effect" import * as FileSystem from "effect/platform/FileSystem" import * as NFS from "node:fs/promises" // Effectify Node.js callback APIs const nodeAccess = effectify( NFS.access, handleErrnoException("FileSystem", "access") ) const nodeReadFile = effectify( NFS.readFile, handleErrnoException("FileSystem", "readFile") ) // Core implementation const make = (): FileSystem.FileSystem => ({ [FileSystem.TypeId]: FileSystem.TypeId, access: (path: string, options?: FileSystem.AccessFileOptions) => { let mode = NFS.constants.F_OK if (options?.readable) mode |= NFS.constants.R_OK if (options?.writable) mode |= NFS.constants.W_OK return nodeAccess(path, mode) }, readFile: (path: string) => nodeReadFile(path).pipe( Effect.map((buffer) => new Uint8Array(buffer)) ), writeFile: (path: string, data: Uint8Array) => nodeWriteFile(path, data) // ... other methods }) // Layer export export const layer: Layer.Layer = Layer.succeed(FileSystem.FileSystem, make()) ``` ### Bun Platform Implementation ```typescript // packages/platform-bun/src/BunFileSystem.ts import * as NodeFileSystem from "@effect/platform-node-shared/NodeFileSystem" import type { FileSystem } from "effect/FileSystem" import type * as Layer from "effect/Layer" // Bun currently reuses the Node.js FileSystem implementation // No Bun-specific optimizations are implemented yet export const layer: Layer.Layer = NodeFileSystem.layer ``` **Note**: Bun's FileSystem layer currently delegates entirely to `@effect/platform-node-shared/NodeFileSystem`. Future Bun-specific optimizations may be added to leverage Bun's native APIs (e.g., `Bun.file()`), but these are not yet implemented. ## ๐Ÿ”„ ERROR HANDLING PATTERNS ### Platform Error Transformation Convert platform-specific errors to structured Effect errors: ```typescript // packages/platform-node-shared/src/internal/utils.ts export const handleErrnoException = (module: string, method: string) => (err: NodeJS.ErrnoException, args: Array): PlatformError.PlatformError => { switch (err.code) { case "ENOENT": return new PlatformError.SystemError({ module, method, reason: "NotFound", pathOrDescriptor: args[0], cause: err }) case "EACCES": return new PlatformError.SystemError({ module, method, reason: "PermissionDenied", pathOrDescriptor: args[0], cause: err }) case "EEXIST": return new PlatformError.SystemError({ module, method, reason: "AlreadyExists", pathOrDescriptor: args[0], cause: err }) default: return new PlatformError.SystemError({ module, method, reason: "Unknown", pathOrDescriptor: args[0], syscall: err.syscall, cause: err }) } } // Usage with effectify (from effect/Effect) import { effectify } from "effect/Effect" const nodeAccess = effectify( NFS.access, handleErrnoException("FileSystem", "access"), handleBadArgument("access") ) const nodeCopyFile = effectify( NFS.copyFile, handleErrnoException("FileSystem", "copyFile"), handleBadArgument("copyFile") ) // handleBadArgument handles synchronous argument validation errors const handleBadArgument = (method: string) => (err: unknown) => new PlatformError.BadArgument({ module: "FileSystem", method }) ``` ### Standardized Error Reasons ```typescript // Platform-agnostic error classification export type SystemErrorReason = | "AlreadyExists" | "BadResource" | "Busy" | "InvalidData" | "NotFound" | "PermissionDenied" | "TimedOut" | "UnexpectedEof" | "Unknown" | "WouldBlock" | "WriteZero" // HTTP-specific error reasons export type HttpErrorReason = | "BadRequest" | "Unauthorized" | "Forbidden" | "NotFound" | "InternalServerError" | "BadGateway" | "ServiceUnavailable" ``` ## ๐Ÿ”— LAYER COMPOSITION PATTERNS ### Service Aggregation Combine related services into unified layers: ```typescript // packages/platform-node/src/NodeServices.ts export const layer: Layer.Layer< FileSystem.FileSystem | Path.Path > = Layer.mergeAll( NodeFileSystem.layer, NodePath.layer ) // HTTP server with all dependencies export const layerHttpServices: Layer.Layer< | FileSystem.FileSystem | Path.Path | HttpPlatform.HttpPlatform | Etag.Generator > = Layer.mergeAll( NodeHttpPlatform.layer, Etag.layerWeak, NodeServices.layer ) ``` ### Test Layer Pattern Provide test-specific implementations: ```typescript // Test layers for consistent testing export const layerTest: Layer.Layer< | HttpServer.HttpServer | FileSystem.FileSystem | Path.Path | HttpPlatform.HttpPlatform | Etag.Generator | HttpClient.HttpClient, ServeError, never > = HttpServer.layerTestClient.pipe( Layer.provide(Layer.fresh(FetchHttpClient.layer)), Layer.provideMerge(layer(Http.createServer, { port: 0 })) ) // In-memory file system for testing export const layerMemoryFileSystem: Layer.Layer = Layer.succeed( FileSystem.FileSystem, makeMemoryFileSystem() ) ``` ## ๐ŸŒŠ STREAM INTEGRATION PATTERNS ### Node.js Stream Conversion Convert Node.js streams to Effect streams using `Stream.fromChannel` with `Channel.fromTransform`: ```typescript // packages/platform-node-shared/src/NodeStream.ts import * as Arr from "effect/Array" import * as Channel from "effect/Channel" import * as Effect from "effect/Effect" import type { LazyArg } from "effect/Function" import * as Pull from "effect/Pull" import * as Scope from "effect/Scope" import * as Stream from "effect/Stream" import { Readable } from "node:stream" export const fromReadable = (options: { readonly evaluate: LazyArg readonly onError?: (error: unknown) => E readonly chunkSize?: number | undefined readonly closeOnDone?: boolean | undefined }): Stream.Stream => Stream.fromChannel(fromReadableChannel(options)) export const fromReadableChannel = (options: { readonly evaluate: LazyArg readonly onError?: (error: unknown) => E readonly chunkSize?: number | undefined readonly closeOnDone?: boolean | undefined }): Channel.Channel, E> => Channel.fromTransform((_, scope) => readableToPullUnsafe({ scope, readable: options.evaluate(), onError: options.onError ?? defaultOnError as any, chunkSize: options.chunkSize, closeOnDone: options.closeOnDone }) ) ``` ### Bun ReadableStream Conversion Bun provides an optimized stream conversion using the `.readMany()` API: ```typescript // packages/platform-bun/src/BunStream.ts export const fromReadableStream = ( options: { readonly evaluate: LazyArg> readonly onError: (error: unknown) => E readonly releaseLockOnEnd?: boolean | undefined } ): Stream.Stream => Stream.fromChannel(Channel.fromTransform(Effect.fnUntraced(function*(_, scope) { const reader = options.evaluate().getReader() yield* Scope.addFinalizer( scope, options.releaseLockOnEnd ? Effect.sync(() => reader.releaseLock()) : Effect.promise(() => reader.cancel()) ) const readMany = Effect.callback, E>((resume) => { const result = reader.readMany() if ("then" in result) { result.then((_) => resume(Effect.succeed(_)), (e) => resume(Effect.fail(options.onError(e)))) } else { resume(Effect.succeed(result)) } }) return Effect.flatMap( readMany, function loop({ done, value }): Pull.Pull, E> { if (done) return Pull.haltVoid if (!Arr.isReadonlyArrayNonEmpty(value)) return Effect.flatMap(readMany, loop) return Effect.succeed(value) } ) }))) ``` ### Stream to Node.js Readable Convert Effect streams back to Node.js Readable streams: ```typescript // packages/platform-node-shared/src/NodeStream.ts export const toReadable = (stream: Stream.Stream): Effect.Effect => Effect.map( Effect.services(), (context) => new StreamAdapter(context, stream) ) export const toReadableNever = (stream: Stream.Stream): Readable => new StreamAdapter(ServiceMap.empty(), stream) ``` ## ๐Ÿ” RESOURCE MANAGEMENT PATTERNS ### Scoped Resource Acquisition Proper cleanup using Effect's Scope system: ```typescript // HTTP Server with automatic cleanup export const make = Effect.fnUntraced(function*( evaluate: LazyArg, options: Net.ListenOptions ) { const scope = yield* Effect.scope const server = evaluate() // Ensure server is closed when scope closes yield* Scope.addFinalizer( scope, Effect.promise(() => new Promise((resolve, reject) => { if (!server.listening) return resolve() server.close((error) => error ? reject(error) : resolve()) }) ) ) // Start the server yield* Effect.async((resume) => { server.on("error", (cause) => resume(Effect.fail(new ServeError({ cause })))) server.listen(options, () => resume(Effect.void)) return Effect.sync(() => { server.removeAllListeners() }) }) return HttpServer.make({ address: { _tag: "TcpAddress", hostname: "localhost", port: options.port }, serve: (handler) => serveEffect(server, handler) }) }) ``` ### Connection Pool Pattern Managed resource pools for expensive resources: ```typescript // Database connection pool example const makeConnectionPool = (config: PoolConfig) => Effect.gen(function*() { const pool = yield* Pool.make({ acquire: createConnection(config.connectionString), size: config.poolSize }) return { withConnection: ( operation: (conn: Connection) => Effect.Effect ): Effect.Effect => Pool.get(pool).pipe( Effect.flatMap(operation), Effect.scoped ) } }) ``` ## ๐Ÿงช TESTING PATTERNS ### Platform Service Mocking ```typescript // Mock implementations for testing const mockFileSystem: FileSystem.FileSystem = { [FileSystem.TypeId]: FileSystem.TypeId, access: () => Effect.void, readFile: (path: string) => { const mockFiles: Record = { "/test.txt": "test content", "/config.json": JSON.stringify({ key: "value" }) } return path in mockFiles ? Effect.succeed(new TextEncoder().encode(mockFiles[path])) : Effect.fail( new PlatformError.SystemError({ module: "FileSystem", method: "readFile", reason: "NotFound", pathOrDescriptor: path }) ) } // ... other mocked methods } // Test layer with mocks export const testLayer: Layer.Layer = Layer.succeed(FileSystem.FileSystem, mockFileSystem) ``` ### Cross-Platform Testing ```typescript // Test that works across all platforms describe("FileSystem", () => { it.effect("should read and write files", () => Effect.gen(function*() { const fs = yield* FileSystem.FileSystem const testData = new TextEncoder().encode("test content") yield* fs.writeFile("/tmp/test.txt", testData) const content = yield* fs.readFile("/tmp/test.txt") assert.deepStrictEqual(content, testData) }).pipe( Effect.provide(NodeFileSystem.layer) // Can be swapped for other platforms )) }) ``` ## ๐ŸŽฏ SUCCESS CRITERIA ### Well-Integrated Platform Code Checklist - [ ] Clean service interfaces in core Effect package - [ ] Platform-specific implementations in separate packages - [ ] Consistent error handling with structured error types - [ ] Proper resource management with automatic cleanup - [ ] Stream integration for async operations - [ ] Layer composition for service aggregation - [ ] Test layers for consistent testing - [ ] Cross-platform compatibility considerations - [ ] Performance optimizations where platform allows - [ ] Documentation showing platform-specific usage patterns This platform integration approach ensures clean separation of concerns while providing a unified API across different runtime environments.