1use std::{
2 io::{Read, Write},
3 net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpListener, TcpStream},
4 thread,
5 time::Duration,
6};
7
8use util::channel::ReleaseChannel;
9
10const LOCALHOST: Ipv4Addr = Ipv4Addr::new(127, 0, 0, 1);
11const CONNECT_TIMEOUT: Duration = Duration::from_millis(10);
12const RECEIVE_TIMEOUT: Duration = Duration::from_millis(35);
13const SEND_TIMEOUT: Duration = Duration::from_millis(20);
14
15fn address() -> SocketAddr {
16 let port = match *util::channel::RELEASE_CHANNEL {
17 ReleaseChannel::Dev => 43737,
18 ReleaseChannel::Preview => 43738,
19 ReleaseChannel::Stable => 43739,
20 };
21
22 SocketAddr::V4(SocketAddrV4::new(LOCALHOST, port))
23}
24
25fn instance_handshake() -> &'static str {
26 match *util::channel::RELEASE_CHANNEL {
27 ReleaseChannel::Dev => "Zed Editor Dev Instance Running",
28 ReleaseChannel::Preview => "Zed Editor Preview Instance Running",
29 ReleaseChannel::Stable => "Zed Editor Stable Instance Running",
30 }
31}
32
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub enum IsOnlyInstance {
35 Yes,
36 No,
37}
38
39pub fn ensure_only_instance() -> IsOnlyInstance {
40 if *db::ZED_STATELESS {
41 return IsOnlyInstance::Yes;
42 }
43
44 if check_got_handshake() {
45 return IsOnlyInstance::No;
46 }
47
48 let listener = match TcpListener::bind(address()) {
49 Ok(listener) => listener,
50
51 Err(err) => {
52 log::warn!("Error binding to single instance port: {err}");
53 if check_got_handshake() {
54 return IsOnlyInstance::No;
55 }
56
57 // Avoid failing to start when some other application by chance already has
58 // a claim on the port. This is sub-par as any other instance that gets launched
59 // will be unable to communicate with this instance and will duplicate
60 log::warn!("Backup handshake request failed, continuing without handshake");
61 return IsOnlyInstance::Yes;
62 }
63 };
64
65 thread::spawn(move || {
66 for stream in listener.incoming() {
67 let mut stream = match stream {
68 Ok(stream) => stream,
69 Err(_) => return,
70 };
71
72 _ = stream.set_nodelay(true);
73 _ = stream.set_read_timeout(Some(SEND_TIMEOUT));
74 _ = stream.write_all(instance_handshake().as_bytes());
75 }
76 });
77
78 IsOnlyInstance::Yes
79}
80
81fn check_got_handshake() -> bool {
82 match TcpStream::connect_timeout(&address(), CONNECT_TIMEOUT) {
83 Ok(mut stream) => {
84 let mut buf = vec![0u8; instance_handshake().len()];
85
86 stream.set_read_timeout(Some(RECEIVE_TIMEOUT)).unwrap();
87 if let Err(err) = stream.read_exact(&mut buf) {
88 log::warn!("Connected to single instance port but failed to read: {err}");
89 return false;
90 }
91
92 if buf == instance_handshake().as_bytes() {
93 log::info!("Got instance handshake");
94 return true;
95 }
96
97 log::warn!("Got wrong instance handshake value");
98 false
99 }
100
101 Err(_) => false,
102 }
103}