Skip to content
Merged
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
3 changes: 2 additions & 1 deletion apps/mobile/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,8 @@
"react-native-screens",
"react-native-reanimated",
"@react-native-menu/menu",
"expo-audio"
"expo-audio",
"expo-network"
]
}
},
Expand Down
80 changes: 80 additions & 0 deletions apps/mobile/scripts/fixtures/NetworkModuleRegression.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import Foundation

enum NWInterface {
enum InterfaceType {
case other, wifi, cellular, loopback, wiredEthernet
}
}

struct NWPath {
enum Status {
case satisfied, unsatisfied
}

// A reference inside the value models the native path's retained storage.
final class Storage {
let type: NWInterface.InterfaceType
init(_ type: NWInterface.InterfaceType) { self.type = type }
}

let status: Status
let storage: Storage

init(_ type: NWInterface.InterfaceType, status: Status = .satisfied) {
self.status = status
storage = Storage(type)
}

func usesInterfaceType(_ type: NWInterface.InterfaceType) -> Bool {
storage.type == type
}
}

final class NWPathMonitor {
static var scenario = "first"
static let deliveries = DispatchGroup()
var pathUpdateHandler: ((NWPath) -> Void)?

func start(queue: DispatchQueue) {
guard let handler = pathUpdateHandler else { fatalError("Missing path handler") }
if Self.scenario == "offline" {
handler(NWPath(.wifi, status: .unsatisfied))
} else if Self.scenario == "first" {
handler(NWPath(.wifi))
handler(NWPath(.cellular))
} else {
queue.async(group: Self.deliveries) {
handler(NWPath(.wifi))
DispatchQueue.concurrentPerform(iterations: 128) { index in
handler(NWPath(index.isMultiple(of: 2) ? .cellular : .wiredEthernet))
}
}
}
}

// Already queued callbacks can run after cancellation.
func cancel() {}
}

@main
enum NetworkModuleRegression {
static func main() {
NWPathMonitor.scenario = CommandLine.arguments[1]
let module = NetworkModule()
if NWPathMonitor.scenario == "concurrent" {
DispatchQueue.concurrentPerform(iterations: 64) { _ in
let state = module.getNetworkStateAsync()
precondition(state["type"] as? String == "WIFI", "The first path must survive late callbacks")
precondition(state["isConnected"] as? Bool == true)
}
NWPathMonitor.deliveries.wait()
} else {
let state = module.getNetworkStateAsync()
let connected = NWPathMonitor.scenario != "offline"
precondition(state["type"] as? String == (connected ? "WIFI" : "NONE"))
precondition(state["isConnected"] as? Bool == connected)
precondition(state["isInternetReachable"] as? Bool == connected)
}
print("passed")
}
}
74 changes: 74 additions & 0 deletions apps/mobile/scripts/network-module.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
// @effect-diagnostics nodeBuiltinImport:off - Compiles and runs the native dependency regression directly.
import * as NodeChildProcess from "node:child_process";
import * as NodeFS from "node:fs";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import * as NodeURL from "node:url";
import { afterAll, beforeAll, describe, expect, it } from "vite-plus/test";

// oxlint-disable-next-line t3code/no-global-process-runtime -- This native integration test uses the host Swift compiler.
describe.skipIf(NodeOS.platform() !== "darwin")("NetworkModule native path handoff", () => {
let directory: string;
let executable: string;

beforeAll(() => {
directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-network-test-"));
executable = NodePath.join(directory, "network-regression");
const source = NodeFS.readFileSync(
new URL("../node_modules/expo-network/ios/NetworkModule.swift", import.meta.url),
"utf8",
);
// Compile the dependency's query and conversion methods, replacing only
// NWPathMonitor so we can deliver updates during and after cancellation.
const start = source.indexOf(" private func getNetworkPathAsync()");
if (start === -1) throw new Error("NetworkModule query implementation not found");
const methods = source
.slice(start, source.lastIndexOf("\n}"))
.replace("private func getNetworkStateAsync", "func getNetworkStateAsync");
const module = NodePath.join(directory, "NetworkModule.swift");
NodeFS.writeFileSync(
module,
`import Foundation\nfinal class NetworkModule {\n private let monitorQueue = DispatchQueue.global(qos: .default)\n${methods}\n}\n`,
);
const types = NodePath.join(directory, "NetworkType.swift");
NodeFS.writeFileSync(
types,
NodeFS.readFileSync(
new URL("../node_modules/expo-network/ios/NetworkType.swift", import.meta.url),
"utf8",
).replace(/^import Network\n/m, ""),
);
NodeChildProcess.execFileSync(
"swiftc",
[
"-swift-version",
"5",
"-sanitize=thread",
module,
types,
NodeURL.fileURLToPath(new URL("./fixtures/NetworkModuleRegression.swift", import.meta.url)),
"-o",
executable,
],
{ timeout: 30_000, encoding: "utf8" },
);
});

afterAll(() => {
if (directory) NodeFS.rmSync(directory, { recursive: true, force: true });
});

it.each([
["first", "keeps the first path when several updates arrive before the query resumes"],
["offline", "reports a disconnected path"],
["concurrent", "reads paths during overlapping queries and late callbacks without data races"],
])("%s: %s", (name) => {
expect(
NodeChildProcess.execFileSync(executable, [name], {
encoding: "utf8",
timeout: 15_000,
env: { ...process.env, TSAN_OPTIONS: "halt_on_error=1" },
}).trim(),
).toBe("passed");
});
});
31 changes: 31 additions & 0 deletions patches/expo-network@58.0.3.patch
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
diff --git a/ios/NetworkModule.swift b/ios/NetworkModule.swift
--- a/ios/NetworkModule.swift
+++ b/ios/NetworkModule.swift
@@ -93,10 +93,18 @@
// since we want to wait for the result to be updated once:
let tempMonitor = NWPathMonitor()
var tempPath: NWPath?
+ let pathLock = NSLock()

let semaphore = DispatchSemaphore(value: 0)

tempMonitor.pathUpdateHandler = { updatedPath in
+ // Cancellation does not drain queued updates. Publish only the first path
+ // and synchronize its retain with the caller reading it on another queue.
+ pathLock.lock()
+ defer { pathLock.unlock() }
+ guard tempPath == nil else {
+ return
+ }
tempPath = updatedPath
semaphore.signal() // Notify that we got the path
}
@@ -114,6 +122,8 @@
return nil
}

+ pathLock.lock()
+ defer { pathLock.unlock() }
return tempPath
}

5 changes: 3 additions & 2 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions pnpm-workspace.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,7 @@ patchedDependencies:
micromark-extension-gfm-table@2.1.1: patches/micromark-extension-gfm-table@2.1.1.patch
alchemy@2.0.0-beta.80: patches/alchemy@2.0.0-beta.80.patch
expo-audio@58.0.9: patches/expo-audio@58.0.9.patch
expo-network@58.0.3: patches/expo-network@58.0.3.patch
"@clerk/expo-native-components@0.2.0": patches/@clerk__expo-native-components@0.2.0.patch
"@effect/vitest@4.0.5": patches/@effect__vitest@4.0.5.patch
"@expo/metro-config@58.0.14": patches/@expo__metro-config@58.0.14.patch
Expand Down
Loading