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 // todo!("zed_stateless")
41 // if *db::ZED_STATELESS {
42 // return IsOnlyInstance::Yes;
43 // }
44
45 if check_got_handshake() {
46 return IsOnlyInstance::No;
47 }
48
49 let listener = match TcpListener::bind(address()) {
50 Ok(listener) => listener,
51
52 Err(err) => {
53 log::warn!("Error binding to single instance port: {err}");
54 if check_got_handshake() {
55 return IsOnlyInstance::No;
56 }
57
58 // Avoid failing to start when some other application by chance already has
59 // a claim on the port. This is sub-par as any other instance that gets launched
60 // will be unable to communicate with this instance and will duplicate
61 log::warn!("Backup handshake request failed, continuing without handshake");
62 return IsOnlyInstance::Yes;
63 }
64 };
65
66 thread::spawn(move || {
67 for stream in listener.incoming() {
68 let mut stream = match stream {
69 Ok(stream) => stream,
70 Err(_) => return,
71 };
72
73 _ = stream.set_nodelay(true);
74 _ = stream.set_read_timeout(Some(SEND_TIMEOUT));
75 _ = stream.write_all(instance_handshake().as_bytes());
76 }
77 });
78
79 IsOnlyInstance::Yes
80}
81
82fn check_got_handshake() -> bool {
83 match TcpStream::connect_timeout(&address(), CONNECT_TIMEOUT) {
84 Ok(mut stream) => {
85 let mut buf = vec![0u8; instance_handshake().len()];
86
87 stream.set_read_timeout(Some(RECEIVE_TIMEOUT)).unwrap();
88 if let Err(err) = stream.read_exact(&mut buf) {
89 log::warn!("Connected to single instance port but failed to read: {err}");
90 return false;
91 }
92
93 if buf == instance_handshake().as_bytes() {
94 log::info!("Got instance handshake");
95 return true;
96 }
97
98 log::warn!("Got wrong instance handshake value");
99 false
100 }
101
102 Err(_) => false,
103 }
104}