Skip to content
CoRISE

From COM to an F# Domain API: Options, Results and State at the Boundary

Translate COM nulls, HRESULTs and state codes into options, results and domain types. Define property-read, cleanup, RCW/apartment and HTTP error boundaries with a fictional sample.

T. AsanoPublished Updated 22 min read
  • Integration
  • API
  • Modernization
Open table of contents

Keep COM representations out of the application contract

Wrapping COM in REST creates an entry point for browsers and Linux clients. But translating null, HRESULTs, integer status codes and Connect/Disconnect sequences directly into JSON leaves every new application dependent on vendor knowledge.

The useful boundary translates legacy representations into meanings the application can use. Read values and failures at the COM edge, convert them into domain types, then expose them through HTTP or batch operations. F# options, results and discriminated unions express these contracts with small types. [1]

This implementation companion to modernization without a rewrite uses a fictional record lookup API. The sample bundle contains pure mapping, fictional managed interfaces, session outcomes, HTTP DTOs and a fake. It is not a real vendor interop assembly or COM host. .NET restore/build/tests, JSON execution, Windows COM activation, concurrency, release and cancellation exercises were not executed.

The related case used F# adapter and REST technology independently developed earlier by a technical advisor. This educational code was authored separately; it does not reproduce that asset or establish its implementation or test results.

1. Separate legacy, domain and HTTP contracts

.NET normally accesses COM through a Runtime Callable Wrapper (RCW), which mediates managed/native calls. [2] A property that looks like an ordinary .NET value can still invoke native work when read.

Scroll horizontally to view the complete diagram.

Separate COM execution, domain meaning and HTTP schema Call COM/RCWs inside the owned adapter. Copy properties into raw values, then use a pure mapper to produce domain types. Repository callers receive domain records and Option/Result; HTTP projects a separate DTO. Raw objects, HRESULTs and session procedures stay internal.
Fig. 01 — Separate COM execution, domain meaning and HTTP schema
Read the diagram as text

Call COM/RCWs inside the owned adapter. Copy properties into raw values, then use a pure mapper to produce domain types. Repository callers receive domain records and Option/Result; HTTP projects a separate DTO. Raw objects, HRESULTs and session procedures stay internal.

The application-facing repository can have this shape:

type RecordRepository = {
    Find: RecordId -> Result<Record option, LegacyError>
}

Its caller needs a validated identifier, the possibility of legitimate absence and meaningful failure cases. It does not need object activation, LastError, apartments or release order.

The domain represents required business information and constraints. HTTP DTOs represent the wire schema; raw DTOs preserve vendor representations. Shared field names do not make those three contracts interchangeable.

2. Option means legitimate absence; Result means lookup failure

Start by separating identifiers from arbitrary strings.

type RecordId = private RecordId of string

type RecordIdError = EmptyRecordId

module RecordId =
    let create value =
        if String.IsNullOrWhiteSpace value then Error EmptyRecordId
        else Ok (RecordId value)
    let value (RecordId value) = value

This example rejects blank input only. Add actual length/format constraints when the domain requires them. Conversely, unreviewed trimming, case conversion or normalization can change a vendor identifier’s meaning.

F# component design guidance recommends checking null at boundaries with external .NET APIs. [3] Applying Option.ofObj is only the mechanical step; the semantic contract must come first.

ResultMeaning
Ok (Some record)Lookup succeeded and found the record
Ok NoneLookup succeeded and confirmed absence
Error UpstreamUnavailableLookup could not be completed
Error (InvalidUpstreamData ...)A response conflicts with the expected contract

The fictional service supplies LastOutcome immediately after Find: 0 means found, 3 absent, 8 unavailable and 9 upstream access denied. These are illustrative codes, not a real vendor table or HRESULT values.

let decodeLookup outcome (raw: IRawRecord) : Result<RawRecord option, LegacyError> =
    // FICTIONAL binding contract, not a real vendor HRESULT/status table.
    match outcome, Option.ofObj raw with
    | 0, Some value -> snapshot value |> Some |> Ok
    | 3, None -> Ok None
    | 8, None -> Error UpstreamUnavailable
    | 9, None -> Error UpstreamAccessDenied
    | _ -> Error (InvalidUpstreamData InconsistentLookup)

0 + null and 3 + object are inconsistent responses. An unavailable service must not become None and then an HTTP 404. If the real API does not distinguish why it returned null, resolve that ambiguity through its specification or vendor contract instead of declaring absence.

Scroll horizontally to view the complete diagram.

Distinguish absence, failed lookup and invalid responses Read LastOutcome immediately after Find and check its fictional contract against object presence. On success, copy and validate properties. Only confirmed absence becomes Ok None. Unavailability, upstream denial, contradictory responses and missing required data become errors.
Fig. 02 — Distinguish absence, failed lookup and invalid responses
Read the diagram as text

Read LastOutcome immediately after Find and check its fictional contract against object presence. On success, copy and validate properties. Only confirmed absence becomes Ok None. Unavailability, upstream denial, contradictory responses and missing required data become errors.

Another call can overwrite LastOutcome before it is read. Keep the call and outcome read in one owned execution unit and review callback reentrancy too. A single thread alone does not guarantee that vendor state cannot change.

3. Classify HRESULT behavior from the actual interop signature

A failing COM HRESULT may become a .NET exception, but not necessarily COMException. For example, E_ACCESSDENIED maps to UnauthorizedAccessException, and E_OUTOFMEMORY maps to OutOfMemoryException. Unrecognized HRESULTs normally use COMException. [4]

Public errors do not carry vendor messages or HRESULTs directly.

type DataIssue = MissingIdentifier | IdentifierMismatch | MissingName | InvalidDate | InconsistentLookup

type LegacyError =
    | UpstreamUnavailable
    | UpstreamAccessDenied
    | UpstreamProtocolFailure
    | InvalidUpstreamData of DataIssue
    | CleanupFailed

The classifier uses explicit signed 32-bit values with hexadecimal comments:

namespace BoundaryExample

open System
open System.Runtime.InteropServices

// Internal diagnostics contain no exception Message/ToString or raw record values.
type internal Diagnostic = { Phase: string; HResult: int; ExceptionType: string }

module internal Boundary =
    // Signed Int32 bit patterns; map only after confirming the actual interop contract.
    let accessDenied = -2147024891       // 0x80070005 E_ACCESSDENIED
    let rpcUnavailable = -2147023174     // 0x800706BA RPC_S_SERVER_UNAVAILABLE

    let classify (error: exn) =
        match error with
        | :? UnauthorizedAccessException when error.HResult = accessDenied -> Some UpstreamAccessDenied
        | :? COMException when error.HResult = accessDenied -> Some UpstreamAccessDenied
        | :? COMException when error.HResult = rpcUnavailable -> Some UpstreamUnavailable
        | :? COMException -> Some UpstreamProtocolFailure
        | _ -> None

    let invoke (diagnostics: ResizeArray<Diagnostic>) phase action =
        try Ok (action ())
        with error ->
            match classify error with
            | Some mapped ->
                diagnostics.Add { Phase = phase; HResult = error.HResult; ExceptionType = error.GetType().Name }
                Error mapped
            | None -> reraise ()

Apply this classification only around external COM calls. Do not turn an application’s ArgumentException into a user-input error by default. An unfamiliar COM failure becomes UpstreamProtocolFailure for observation; it does not automatically authorize session reuse or retry.

PreserveSig makes the return value part of the contract

When signature transformation is suppressed, inspect returned HRESULTs directly. Preserving the signature can also retain distinctions between multiple success values. [5] Do not assume “no exception means success” or “every nonzero value means failure” without inspecting the declaration.

The sample uses Result.bind and Result.map, with no undeclared result { ... } computation expression. If a result builder is used, name its implementation/library and version. The Result type and its computation-expression builder are separate things.

4. Protect property reads, then map pure values

Protecting only Find is insufficient. Property getters, collection enumerators and nested-object acquisition can call COM and fail. Copy the required values once inside the owned session.

let snapshot (raw: IRawRecord) : RawRecord =
    // Each getter is an external call; invoke this INSIDE the protected owner-thread scope.
    { Id = raw.Id; Name = raw.Name; Description = raw.Description
      Status = raw.Status; Date = raw.Date }

Then pass ordinary values into a pure mapper that knows nothing about RCWs.

let record (requested: RecordId) (raw: RawRecord) : Result<Record, LegacyError> =
    RecordId.create raw.Id
    |> Result.mapError (fun _ -> InvalidUpstreamData MissingIdentifier)
    |> Result.bind (fun id ->
        if id <> requested then Error (InvalidUpstreamData IdentifierMismatch)
        elif String.IsNullOrWhiteSpace raw.Name then Error (InvalidUpstreamData MissingName)
        else
            BusinessDate.tryParse raw.Date
            |> Result.mapError (fun _ -> InvalidUpstreamData InvalidDate)
            |> Result.map (fun date ->
                let mapped: Record =
                    { Id = id; Name = raw.Name; Description = Option.ofObj raw.Description
                      Status = status raw.Status; Date = date }
                mapped))

ID and name are required domain data, so null is not replaced with an empty default. Missing required values are upstream-data failures, not malformed caller requests. Only description is optional here: null becomes None, while an empty description remains Some "" under the explicit sample contract.

The returned ID must also match the requested ID. Choose equality rules from the actual domain. A snapshot here means a value copy, not an atomic transaction across getters. If vendor data changes during those reads, use version checks or a vendor snapshot facility as required.

5. Preserve unknown states and parse encoded values

Translate numeric state at the boundary instead of distributing it through the application.

type RecordStatus = Pending | Active | Suspended | Unknown of int

let status = function
    | 0 -> Pending
    | 1 -> Active
    | 7 -> Suspended
    | value -> Unknown value

Mapping an unknown code to Pending silently changes meaning. Unknown of int explicitly preserves the uncertainty. Retaining that raw value in the domain is an intentional diagnostic trade-off; HTTP projects it to "unknown" without the number.

Displaying an unknown state does not imply that writes are permitted. Approval, billing or other consequential operations need an explicit reject/hold policy for states they do not understand.

Parse string encodings with a defined format and culture.

type BusinessDate = private BusinessDate of DateOnly

module BusinessDate =
    let tryParse (value: string) =
        match DateOnly.TryParseExact(value, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None) with
        | true, date -> Ok (BusinessDate date)
        | false, _ -> Error ()
    let value (BusinessDate date) = date

20260230 and null are invalid. DateOnly represents a date without a time or time zone. A legacy timestamp needs a different type and conversion contract. [6]

An active pattern can make parsing readable, but converting every failure to a partial pattern’s None discards the reason. Keep the original Result when boundary diagnostics matter. [12]

6. Type-state wrappers do not consume old references

A wrapper that accepts DisconnectedClient and returns ConnectedClient can prevent some calls before connection. But ordinary F# references are not linear. A caller can retain pre-connect or post-disconnect aliases, and concurrent calls remain possible.

A generic withConnection callback can also return the client itself, a closure, a lazy sequence or asynchronous work that captures it. Exiting the scope does not prove the reference stayed inside.

The example therefore keeps sessions internal. One repository operation creates, connects, copies and closes before returning domain data.

Scroll horizontally to view the complete diagram.

Keep sessions internal and finish copying and cleanup per operation Create, connect/select, find/read outcome, copy properties and close on the owned lane. Attempt contractual cleanup after intermediate failure. Preserve primary and cleanup outcomes separately and return domain values only. A type-state wrapper alone cannot prevent stale aliases or escaping lazy/asynchronous work.
Fig. 03 — Keep sessions internal and finish copying and cleanup per operation
Read the diagram as text

Create, connect/select, find/read outcome, copy properties and close on the owned lane. Attempt contractual cleanup after intermediate failure. Preserve primary and cleanup outcomes separately and return domain values only. A type-state wrapper alone cannot prevent stale aliases or escaping lazy/asynchronous work.

It checks the creating managed thread and lifecycle phase. These are guards against misuse, not evidence of a correct COM apartment, message pump or exclusive executor.

namespace BoundaryExample

open System

module internal Repository =
    type private Phase = Created | Ready | Closing | Closed

    let findReport (factory: unit -> IRawService) (id: RecordId) =
        // Call this whole function on the reviewed COM execution lane, never ThreadPool by default.
        let diagnostics = ResizeArray<Diagnostic>()
        match Boundary.invoke diagnostics "create" factory with
        | Error error ->
            { Primary = Returned (Error error); Cleanup = Returned (Ok ())
              Diagnostics = List.ofSeq diagnostics }
        | Ok raw ->
            let owner = Environment.CurrentManagedThreadId
            let mutable phase = Created
            let require expected =
                if Environment.CurrentManagedThreadId <> owner || phase <> expected then
                    invalidOp "Invalid adapter execution lane or lifecycle phase."
            let operation () =
                require Created
                Boundary.invoke diagnostics "connect-select" raw.ConnectAndSelect
                |> Result.bind (fun () ->
                    phase <- Ready
                    require Ready
                    Boundary.invoke diagnostics "find-snapshot" (fun () ->
                        let found = raw.Find (RecordId.value id)
                        let outcome = raw.LastOutcome // Read immediately before any record getters.
                        Mapping.decodeLookup outcome found)
                    |> Result.bind (fun result -> result)
                    |> Result.bind (function
                        | None -> Ok None
                        | Some copy -> Mapping.record id copy |> Result.map Some))
            let cleanup () =
                if Environment.CurrentManagedThreadId <> owner then invalidOp "Wrong cleanup thread."
                phase <- Closing
                try Boundary.invoke diagnostics "cleanup" raw.CloseOwnedSession
                finally phase <- Closed
            Session.run diagnostics operation cleanup

The fictional CloseOwnedSession contract includes partially failed connection and acquired child resources. It does not assume every real vendor’s Disconnect is valid before connection completes. If construction fails before a service is returned, the factory owns cleanup of partially acquired resources.

7. Preserve primary and cleanup outcomes independently

disconnect |> ignore inside a finally can hide a damaged session behind a successful result. Letting a cleanup exception replace the primary exception can hide the original cause.

The example retains both outcomes before selecting a public result. Unexpected exceptions are held only while cleanup is attempted; they are not normalized into routine errors, and their original stacks are preserved on rethrow.

namespace BoundaryExample

open System.Runtime.ExceptionServices

type internal Attempt<'T> =
    | Returned of Result<'T, LegacyError>
    | Raised of ExceptionDispatchInfo

type internal Completion<'T> = {
    Primary: Attempt<'T>
    Cleanup: Attempt<unit>
    Diagnostics: Diagnostic list
}

module internal Session =
    let capture operation =
        try Returned (operation ())
        with error -> Raised (ExceptionDispatchInfo.Capture error)

    let run diagnostics operation cleanup =
        // Unexpected exceptions are held only to attempt cleanup, not converted to ordinary errors.
        let primary = capture operation
        let closing = capture cleanup
        { Primary = primary; Cleanup = closing; Diagnostics = List.ofSeq diagnostics }

    let private throwOriginal (error: ExceptionDispatchInfo) =
        error.Throw()
        Unchecked.defaultof<_> // Unreachable: Throw preserves the original exception stack.

    let resolve completion =
        match completion.Primary, completion.Cleanup with
        | Raised error, _ -> throwOriginal error
        | _, Raised error -> throwOriginal error
        | Returned (Error primary), _ -> Error primary
        | Returned (Ok _), Returned (Error _) -> Error CleanupFailed
        | Returned (Ok value), Returned (Ok ()) -> Ok value
Primary operationCleanupSample behavior
SuccessSuccessReturn domain value
SuccessExpected failureReturn CleanupFailed; discard the session
Expected failureExpected failurePreserve primary error and both diagnostic outcomes
Unexpected exceptionSuccess or failureRethrow primary exception with original stack; retain cleanup outcome
Success or expected errorUnexpected cleanup exceptionEscalate to host fault handling instead of implying normal continuation

The Windows host must inspect and record both sides of Completion before resolving it, and retire damaged sessions rather than returning them to a pool. The sample provides neither a durable logging sink nor a pool. Telemetry failures need their own policy so they do not mask the operation. Process termination and catastrophic failure can prevent cleanup altogether.

8. Design RCW ownership separately from STA execution

Marshal.ReleaseComObject is not a universal Dispose operation. Releasing a shared RCW or one with an active call can break other users or cause access violations; Microsoft cautions that it should be used only when truly required. Singleton COM objects can share wrappers even when managed code appears to construct separate instances. [7]

FinalReleaseComObject also invalidates subsequent use of that RCW. [8] Copying domain values narrows the lifetime boundary but does not prove exclusive ownership. Inventory child objects, enumerators, callbacks and shared instances. Do not distribute forced-GC or release-loop recipes as generic cleanup.

Scroll horizontally to view the complete diagram.

Separate waiting, execution and unknown outcomes The authorized HTTP host applies admission limits and submits to a reviewed Windows COM executor. Handle apartments, pumps, ownership and callbacks. Client timeout does not prove native cancellation; isolate late results and hung workers. Unknown mutation outcomes need reconciliation, not unconditional retry.
Fig. 04 — Separate waiting, execution and unknown outcomes
Read the diagram as text

The authorized HTTP host applies admission limits and submits to a reviewed Windows COM executor. Handle apartments, pumps, ownership and callbacks. Client timeout does not prove native cancellation; isolate late results and hung workers. Unknown mutation outcomes need reconciliation, not unconditional retry.

An STA host may need a message loop, correct dispatch, callback/reentrancy handling and suitable waits, not merely an apartment flag. A MailboxProcessor, dedicated thread or Task.Run alone is not a complete STA host. [9]

Keep creation, calls, property copies and cleanup on the contractually appropriate execution lane, with required marshaling. Contain Windows, bitness, COM registration, execution identity, licensing and in-process/out-of-process constraints there. The managed fake verifies none of these conditions.

9. Stopping the wait does not stop native work

An HTTP timeout or disconnected client does not prove that a COM call stopped. .NET cancellation is cooperative; it cannot universally cancel arbitrary native work. [10]

Separate queue deadlines from execution deadlines. Define admission limits, late results and isolation/restart of hung workers. Mutations can have an unknown outcome and need idempotency, deduplication or reconciliation. An unavailable-style error is not sufficient justification for retrying every operation.

The repository contract shown here is synchronous and read-only. It is not a design for creating an unrestricted Windows thread per HTTP request. A real host needs a reviewed queue or IPC execution boundary. Search additionally needs limits, pages and partial-enumeration semantics; never return a lazy seq that retains RCWs beyond the session.

10. Put HTTP after the domain boundary

Expose operations such as GET /records/{id}, rather than requiring clients to call /connect and /last-error. Hiding the session sequence does not, however, make the lookup a pure function or guarantee consistent results over time.

Use an explicit response DTO: description absence is JSON null, status is a stable string and date uses yyyy-MM-dd.

[<CLIMutable>]
type RecordResponse = {
    [<JsonPropertyName("id")>] Id: string
    [<JsonPropertyName("name")>] Name: string
    [<JsonPropertyName("description")>] Description: string
    [<JsonPropertyName("status")>] Status: string
    [<JsonPropertyName("date")>] Date: string
}

let toResponse (record: Record) =
    { Id = RecordId.value record.Id; Name = record.Name
      Description = record.Description |> Option.defaultValue null
      Status = match record.Status with Pending -> "pending" | Active -> "active" | Suspended -> "suspended" | Unknown _ -> "unknown"
      Date = (BusinessDate.value record.Date).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) }

Option/union JSON representation depends on runtime, converters and settings. The sample targets net10.0 with F# 8 language mode and does not serialize its domain unions directly. DTOs stabilize the wire contract independently of whether a serializer supports a particular language type. [11]

The HTTP-result mapping is:

let fromResult correlation = function
    | Ok (Some record) -> json 200 (toResponse record)
    | Ok None -> failure 404 "record_not_found" correlation
    | Error UpstreamUnavailable -> failure 503 "upstream_unavailable" correlation
    | Error UpstreamAccessDenied -> failure 502 "upstream_failure" correlation
    | Error (InvalidUpstreamData _) -> failure 502 "upstream_failure" correlation
    | Error UpstreamProtocolFailure -> failure 502 "upstream_failure" correlation
    | Error CleanupFailed -> failure 503 "adapter_unavailable" correlation

This example assumes the adapter authenticates to the upstream under its own identity. Denial of that identity maps to 502, not a conclusion that the end user deserves 403. Authenticate and authorize the end user before lookup. Delegated upstream identity requires a separately documented mapping.

Distinguish a caller’s blank ID (400) from an upstream response missing a required name (502). Unexpected defects reach a safe host-level 500 handler, without exception text in the response. Generate correlation IDs server-side and review whether returning 404 exposes resource existence under the API’s authorization policy.

11. Verify mapping, fakes, real COM and HTTP independently

Applications receive RecordRepository, so a fake can be injected. The bundled FakeExample.create returns one known record and absence for other IDs. It provides an authored managed path into the domain; it is not an executed test result.

LayerRepresentative checks
Pure mappingRequired nulls, invalid dates, ID mismatch, unknown status, optional description
Error boundaryDifferent access-denied exception types, unknown HRESULT, getter failure
SessionPartial connection, double failures, stale aliases and wrong-thread use
Real COM integrationKnown dataset, interop version, bitness, apartment/pump, child RCWs and hangs
HTTP contractStatus and body, JSON null/date, authorization, safe errors and correlation

A pure test can establish that code 7 maps to Suspended. A real vendor fixture must also establish that this remains the vendor’s meaning. If semantics change while the numeric code stays the same, pure mapping tests alone will not discover it.

The sample layout is:

fsharp-com-boundary/
├── BoundaryExample.fsproj
├── Domain.fs
├── RawPort.fs
├── Mapping.fs
├── Boundary.fs
├── Session.fs
├── Repository.fs
├── Http.fs
├── FakeExample.fs
└── review/
    ├── vendor-contract.md
    └── contract-cases.md

A future build command is dotnet build BoundaryExample.fsproj. This is a library with a fake, not a test runner or Windows worker project. Pin the actual SDK and dependency-resolution environment before validation. Builder availability, build success, interop success and contract conformance are separate evidence.

12. Observe change at the integration boundary

Observe unknown states, mapping failures, upstream errors, call duration, queue delay, cleanup failure and worker retirement separately. A single undifferentiated error counter cannot distinguish vendor failure, a translation bug and a saturated executor.

Do not put record IDs, raw exception messages or arbitrary unknown codes into unbounded metric labels. The internal diagnostic example keeps phase, HRESULT and exception type, omitting message and record contents. Detailed logs still require redaction, access and retention policy. Public errors should carry information needed for caller decisions.

In the related modernization case, CoRISE used F# adapter, domain-model and REST technology previously developed independently by a technical advisor, and delivered customer-facing web application design/development and API integration. The fictional interfaces, codes, cleanup policy, threading discussion and exercises here are not implementation evidence for those earlier assets or that engagement. Reuse also requires confirming authorship and permitted use.

F# is useful here because legitimate absence, lookup failure, invalid upstream data and unknown state can become distinct contracts visible in the signature. Ownership and concurrency that the types do not prove remain responsibilities of execution infrastructure and runtime checks.

COM and Windows can remain inside the adapter. Contain their constraints and the reasons for change instead of carrying them into every new application. Modernizing the boundary means translating meaning and execution responsibility, not just replacing a transport.

References

  1. F# Option, Result and discriminated unions — Also Result and discriminated unions.
  2. Runtime Callable Wrapper — RCWs and marshaling.
  3. F# Component Design Guidelines — Null at external .NET boundaries and API design.
  4. Handling COM Interop Exceptions — HRESULT-to-exception mapping and IErrorInfo.
  5. PreserveSigAttribute — Contracts when signature transformation is suppressed.
  6. DateOnly.TryParseExact — Exact date formats and culture.
  7. Marshal.ReleaseComObject — Shared/active RCWs and explicit release hazards.
  8. Marshal.FinalReleaseComObject — Post-release use and lifetime.
  9. Single-threaded Apartments — Message loops, marshaling and reentrancy; also apartment overview.
  10. Cancellation in Managed Threads — Cooperative cancellation.
  11. System.Text.Json Supported Types — Runtime/converter support for F# types; also ASP.NET Core error handling.
  12. F# Active Patterns — Parser and pattern-matching boundaries.

Microsoft platform guidance is separate from the fictional API contract and expected sample outcomes. Actual vendor specifications, source licenses, interop versions and runtime validation remain adoption requirements.

T. Asano

More articles by T. Asano

Contact

Tell us about your engineering challenge.

Talk with CoRISE about the design, implementation and operation of your systems.

Start a Conversation