Files
effect/.patterns/platform-integration.md
T

15 KiB

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:

// packages/effect/src/platform/FileSystem.ts
export interface FileSystem {
  readonly [TypeId]: TypeId
  readonly access: (path: string, options?: AccessFileOptions) => Effect.Effect<void, PlatformError>
  readonly readFile: (path: string) => Effect.Effect<Uint8Array, PlatformError>
  readonly writeFile: (path: string, data: Uint8Array) => Effect.Effect<void, PlatformError>
  readonly stat: (path: string) => Effect.Effect<File.Info, PlatformError>
  readonly mkdir: (path: string, options?: MakeDirectoryOptions) => Effect.Effect<void, PlatformError>
  readonly readdir: (path: string) => Effect.Effect<ReadonlyArray<string>, PlatformError>
  readonly rm: (path: string, options?: RemoveOptions) => Effect.Effect<void, PlatformError>
  readonly watch: (path: string) => Stream.Stream<WatchEvent, PlatformError>
}

// Service key for dependency injection
export const FileSystem: ServiceMap.Service<FileSystem, FileSystem> = 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:

// HTTP platform service
export class HttpPlatform extends ServiceMap.Service<HttpPlatform, {
  readonly fileResponse: (path: string, options?: FileResponseOptions) => Effect.Effect<Response>
  readonly fileWebResponse: (file: FileLike, options?: FileWebResponseOptions) => Effect.Effect<Response>
  readonly formData: (source: Readable) => Effect.Effect<FormData>
}>()("effect/http/HttpPlatform") {}

// Socket service
export class NetSocket extends ServiceMap.Service<NetSocket, Net.Socket>()(
  "@effect/platform-node/NodeSocket/NetSocket"
) {}

🔧 PLATFORM IMPLEMENTATION PATTERN

Node.js Implementation Structure

// 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<FileSystem.FileSystem, never, never> = Layer.succeed(FileSystem.FileSystem, make())

Bun Platform Implementation

// 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<FileSystem, never, never> = 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:

// packages/platform-node-shared/src/internal/utils.ts
export const handleErrnoException =
  (module: string, method: string) => (err: NodeJS.ErrnoException, args: Array<any>): 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

// 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:

// 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:

// 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<FileSystem.FileSystem> = 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:

// 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 = <A = Uint8Array, E = Cause.UnknownError>(options: {
  readonly evaluate: LazyArg<Readable | NodeJS.ReadableStream>
  readonly onError?: (error: unknown) => E
  readonly chunkSize?: number | undefined
  readonly closeOnDone?: boolean | undefined
}): Stream.Stream<A, E> => Stream.fromChannel(fromReadableChannel<A, E>(options))

export const fromReadableChannel = <A = Uint8Array, E = Cause.UnknownError>(options: {
  readonly evaluate: LazyArg<Readable | NodeJS.ReadableStream>
  readonly onError?: (error: unknown) => E
  readonly chunkSize?: number | undefined
  readonly closeOnDone?: boolean | undefined
}): Channel.Channel<Arr.NonEmptyReadonlyArray<A>, 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:

// packages/platform-bun/src/BunStream.ts
export const fromReadableStream = <A, E>(
  options: {
    readonly evaluate: LazyArg<ReadableStream<A>>
    readonly onError: (error: unknown) => E
    readonly releaseLockOnEnd?: boolean | undefined
  }
): Stream.Stream<A, E> =>
  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<Bun.ReadableStreamDefaultReadManyResult<A>, 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<Arr.NonEmptyReadonlyArray<A>, 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:

// packages/platform-node-shared/src/NodeStream.ts
export const toReadable = <E, R>(stream: Stream.Stream<string | Uint8Array, E, R>): Effect.Effect<Readable, never, R> =>
  Effect.map(
    Effect.services<R>(),
    (context) => new StreamAdapter(context, stream)
  )

export const toReadableNever = <E>(stream: Stream.Stream<string | Uint8Array, E, never>): Readable =>
  new StreamAdapter(ServiceMap.empty(), stream)

🔐 RESOURCE MANAGEMENT PATTERNS

Scoped Resource Acquisition

Proper cleanup using Effect's Scope system:

// HTTP Server with automatic cleanup
export const make = Effect.fnUntraced(function*(
  evaluate: LazyArg<NodeHttp.Server>,
  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<void>((resolve, reject) => {
        if (!server.listening) return resolve()
        server.close((error) => error ? reject(error) : resolve())
      })
    )
  )

  // Start the server
  yield* Effect.async<void, ServeError>((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:

// 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: <A, E, R>(
        operation: (conn: Connection) => Effect.Effect<A, E, R>
      ): Effect.Effect<A, E | PoolError, R> =>
        Pool.get(pool).pipe(
          Effect.flatMap(operation),
          Effect.scoped
        )
    }
  })

🧪 TESTING PATTERNS

Platform Service Mocking

// Mock implementations for testing
const mockFileSystem: FileSystem.FileSystem = {
  [FileSystem.TypeId]: FileSystem.TypeId,

  access: () => Effect.void,

  readFile: (path: string) => {
    const mockFiles: Record<string, string> = {
      "/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<FileSystem.FileSystem> = Layer.succeed(FileSystem.FileSystem, mockFileSystem)

Cross-Platform Testing

// 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.