Skip to content

Commit 7c83530

Browse files
authored
fix(mobile): synchronize Expo network path updates (pingdotgg#22043)
1 parent d5fdfdc commit 7c83530

6 files changed

Lines changed: 191 additions & 3 deletions

File tree

‎apps/mobile/package.json‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,8 @@
179179
"react-native-screens",
180180
"react-native-reanimated",
181181
"@react-native-menu/menu",
182-
"expo-audio"
182+
"expo-audio",
183+
"expo-network"
183184
]
184185
}
185186
},
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
import Foundation
2+
3+
enum NWInterface {
4+
enum InterfaceType {
5+
case other, wifi, cellular, loopback, wiredEthernet
6+
}
7+
}
8+
9+
struct NWPath {
10+
enum Status {
11+
case satisfied, unsatisfied
12+
}
13+
14+
// A reference inside the value models the native path's retained storage.
15+
final class Storage {
16+
let type: NWInterface.InterfaceType
17+
init(_ type: NWInterface.InterfaceType) { self.type = type }
18+
}
19+
20+
let status: Status
21+
let storage: Storage
22+
23+
init(_ type: NWInterface.InterfaceType, status: Status = .satisfied) {
24+
self.status = status
25+
storage = Storage(type)
26+
}
27+
28+
func usesInterfaceType(_ type: NWInterface.InterfaceType) -> Bool {
29+
storage.type == type
30+
}
31+
}
32+
33+
final class NWPathMonitor {
34+
static var scenario = "first"
35+
static let deliveries = DispatchGroup()
36+
var pathUpdateHandler: ((NWPath) -> Void)?
37+
38+
func start(queue: DispatchQueue) {
39+
guard let handler = pathUpdateHandler else { fatalError("Missing path handler") }
40+
if Self.scenario == "offline" {
41+
handler(NWPath(.wifi, status: .unsatisfied))
42+
} else if Self.scenario == "first" {
43+
handler(NWPath(.wifi))
44+
handler(NWPath(.cellular))
45+
} else {
46+
queue.async(group: Self.deliveries) {
47+
handler(NWPath(.wifi))
48+
DispatchQueue.concurrentPerform(iterations: 128) { index in
49+
handler(NWPath(index.isMultiple(of: 2) ? .cellular : .wiredEthernet))
50+
}
51+
}
52+
}
53+
}
54+
55+
// Already queued callbacks can run after cancellation.
56+
func cancel() {}
57+
}
58+
59+
@main
60+
enum NetworkModuleRegression {
61+
static func main() {
62+
NWPathMonitor.scenario = CommandLine.arguments[1]
63+
let module = NetworkModule()
64+
if NWPathMonitor.scenario == "concurrent" {
65+
DispatchQueue.concurrentPerform(iterations: 64) { _ in
66+
let state = module.getNetworkStateAsync()
67+
precondition(state["type"] as? String == "WIFI", "The first path must survive late callbacks")
68+
precondition(state["isConnected"] as? Bool == true)
69+
}
70+
NWPathMonitor.deliveries.wait()
71+
} else {
72+
let state = module.getNetworkStateAsync()
73+
let connected = NWPathMonitor.scenario != "offline"
74+
precondition(state["type"] as? String == (connected ? "WIFI" : "NONE"))
75+
precondition(state["isConnected"] as? Bool == connected)
76+
precondition(state["isInternetReachable"] as? Bool == connected)
77+
}
78+
print("passed")
79+
}
80+
}
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
// @effect-diagnostics nodeBuiltinImport:off - Compiles and runs the native dependency regression directly.
2+
import * as NodeChildProcess from "node:child_process";
3+
import * as NodeFS from "node:fs";
4+
import * as NodeOS from "node:os";
5+
import * as NodePath from "node:path";
6+
import * as NodeURL from "node:url";
7+
import { afterAll, beforeAll, describe, expect, it } from "vite-plus/test";
8+
9+
// oxlint-disable-next-line t3code/no-global-process-runtime -- This native integration test uses the host Swift compiler.
10+
describe.skipIf(NodeOS.platform() !== "darwin")("NetworkModule native path handoff", () => {
11+
let directory: string;
12+
let executable: string;
13+
14+
beforeAll(() => {
15+
directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-network-test-"));
16+
executable = NodePath.join(directory, "network-regression");
17+
const source = NodeFS.readFileSync(
18+
new URL("../node_modules/expo-network/ios/NetworkModule.swift", import.meta.url),
19+
"utf8",
20+
);
21+
// Compile the dependency's query and conversion methods, replacing only
22+
// NWPathMonitor so we can deliver updates during and after cancellation.
23+
const start = source.indexOf(" private func getNetworkPathAsync()");
24+
if (start === -1) throw new Error("NetworkModule query implementation not found");
25+
const methods = source
26+
.slice(start, source.lastIndexOf("\n}"))
27+
.replace("private func getNetworkStateAsync", "func getNetworkStateAsync");
28+
const module = NodePath.join(directory, "NetworkModule.swift");
29+
NodeFS.writeFileSync(
30+
module,
31+
`import Foundation\nfinal class NetworkModule {\n private let monitorQueue = DispatchQueue.global(qos: .default)\n${methods}\n}\n`,
32+
);
33+
const types = NodePath.join(directory, "NetworkType.swift");
34+
NodeFS.writeFileSync(
35+
types,
36+
NodeFS.readFileSync(
37+
new URL("../node_modules/expo-network/ios/NetworkType.swift", import.meta.url),
38+
"utf8",
39+
).replace(/^import Network\n/m, ""),
40+
);
41+
NodeChildProcess.execFileSync(
42+
"swiftc",
43+
[
44+
"-swift-version",
45+
"5",
46+
"-sanitize=thread",
47+
module,
48+
types,
49+
NodeURL.fileURLToPath(new URL("./fixtures/NetworkModuleRegression.swift", import.meta.url)),
50+
"-o",
51+
executable,
52+
],
53+
{ timeout: 30_000, encoding: "utf8" },
54+
);
55+
});
56+
57+
afterAll(() => {
58+
if (directory) NodeFS.rmSync(directory, { recursive: true, force: true });
59+
});
60+
61+
it.each([
62+
["first", "keeps the first path when several updates arrive before the query resumes"],
63+
["offline", "reports a disconnected path"],
64+
["concurrent", "reads paths during overlapping queries and late callbacks without data races"],
65+
])("%s: %s", (name) => {
66+
expect(
67+
NodeChildProcess.execFileSync(executable, [name], {
68+
encoding: "utf8",
69+
timeout: 15_000,
70+
env: { ...process.env, TSAN_OPTIONS: "halt_on_error=1" },
71+
}).trim(),
72+
).toBe("passed");
73+
});
74+
});

‎patches/[email protected]‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
diff --git a/ios/NetworkModule.swift b/ios/NetworkModule.swift
2+
--- a/ios/NetworkModule.swift
3+
+++ b/ios/NetworkModule.swift
4+
@@ -93,10 +93,18 @@
5+
// since we want to wait for the result to be updated once:
6+
let tempMonitor = NWPathMonitor()
7+
var tempPath: NWPath?
8+
+ let pathLock = NSLock()
9+
10+
let semaphore = DispatchSemaphore(value: 0)
11+
12+
tempMonitor.pathUpdateHandler = { updatedPath in
13+
+ // Cancellation does not drain queued updates. Publish only the first path
14+
+ // and synchronize its retain with the caller reading it on another queue.
15+
+ pathLock.lock()
16+
+ defer { pathLock.unlock() }
17+
+ guard tempPath == nil else {
18+
+ return
19+
+ }
20+
tempPath = updatedPath
21+
semaphore.signal() // Notify that we got the path
22+
}
23+
@@ -114,6 +122,8 @@
24+
return nil
25+
}
26+
27+
+ pathLock.lock()
28+
+ defer { pathLock.unlock() }
29+
return tempPath
30+
}
31+

‎pnpm-lock.yaml‎

Lines changed: 3 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎pnpm-workspace.yaml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -322,6 +322,7 @@ patchedDependencies:
322322
323323
324324
325+
325326
326327
327328

0 commit comments

Comments
 (0)