Debian Codegraph @

examples/gio-async-co.cpp

raw symbols SCIP
1 #define GI_INLINE 1
2 #include <gio/gio.hpp>
3
4 #include "co-async.hpp"
5
6 namespace GLib = gi::repository::GLib;
7 namespace GObject_ = gi::repository::GObject;
8 namespace Gio = gi::repository::Gio;
9
10 class async_result
11 {
12 using p_type = co_promise<Gio::AsyncResult>;
13
14 // protect against cancellation/destruction of async call stack
15 struct state
16 {
17 p_type p_;
18 Gio::Cancellable cancel_;
19 };
20
21 std::shared_ptr<state> s_ = std::make_shared<state>();
22
23 public:
24 ~async_result()
25 {
26 auto c = cancellable(false);
27 if (c)
28 c.cancel();
29 }
30
31 operator Gio::AsyncReadyCallback()
32 {
33 // setup for new gio call
34 s_->p_.reset();
35 return [wp = std::weak_ptr(s_)](GObject_::Object, Gio::AsyncResult result) {
36 if (auto sp = wp.lock(); sp) {
37 // clear state for subsequent re-use if needed
38 if (sp->cancel_ && sp->cancel_.is_cancelled())
39 sp->cancel_ = nullptr;
40 sp->p_.set_value(result);
41 sp->p_.resume();
42 }
43 };
44 }
45
46 Gio::Cancellable cancellable(bool create = true)
47 {
48 auto &s = *s_;
49 if (!s.cancel_ && create)
50 s.cancel_ = Gio::Cancellable::new_();
51 return s.cancel_;
52 }
53
54 static Gio::Cancellable timeout(
55 const std::chrono::milliseconds &to, Gio::Cancellable cancel)
56 {
57 if (to.count() > 0 && cancel) {
58 GLib::timeout_add_once(
59 to.count(), [cancel]() mutable { cancel.cancel(); });
60 }
61 return cancel;
62 }
63
64 auto operator co_await() { return s_->p_.operator co_await(); }
65 };
66
67 task<void>
68 sleep_for(std::chrono::milliseconds to)
69 {
70 co_promise<void> w;
71 GLib::SourceFunc func = [&w]() {
72 w.set_value();
73 w.resume();
74 return GLib::SOURCE_REMOVE_;
75 };
76 auto id = GLib::timeout_add(to.count(), func);
77 // scope guard on w in case task stack gets dropped
78 GLib::SourceScopedConnection guard = gi::make_connection(id, func);
79 co_await w;
80 co_return;
81 }
82
83 static task<void>
84 async_client(int port, int id, int &count)
85 {
86 async_result w;
87
88 auto dest = Gio::NetworkAddress::new_loopback(port);
89
90 std::string sid = "client ";
91 sid += std::to_string(id);
92
93 // connect a client
94 std::cout << sid << ": connect" << std::endl;
95 auto client = Gio::SocketClient::new_();
96 client.connect_async(dest, w);
97 auto conn = gi::expect(client.connect_finish(co_await w));
98
99 // say something
100 auto os = conn.get_output_stream();
101 std::cout << sid << ": send: " << sid << std::endl;
102 os.write_all_async(
103 (guint8 *)sid.data(), sid.size(), GLib::PRIORITY_DEFAULT_, w);
104 os.write_all_finish(co_await w, (gsize *)nullptr);
105
106 // now hear what the other side has to say
107 std::cout << sid << ": receive" << std::endl;
108 auto is = conn.get_input_stream();
109 while (1) {
110 guint8 data[1024];
111 is.read_async(data, sizeof(data), GLib::PRIORITY_DEFAULT_, w);
112 auto size = gi::expect(is.read_finish(co_await w));
113 if (!size)
114 break;
115 std::string msg(data, data + size);
116 std::cout << sid << ": got data: " << msg << std::endl;
117 }
118
119 std::cout << sid << ": closing down" << std::endl;
120 --count;
121 }
122
123 static task<void>
124 async_handle_client(Gio::SocketConnection conn)
125 {
126 async_result w;
127
128 // say hello
129 std::cout << "server: hello" << std::endl;
130 auto os = conn.get_output_stream();
131 std::string msg = "hello ";
132 os.write_all_async(
133 (guint8 *)msg.data(), msg.size(), GLib::PRIORITY_DEFAULT_, w);
134 os.write_all_finish(co_await w, (gsize *)nullptr);
135
136 // now echo what the other side has to say
137 auto is = conn.get_input_stream();
138 while (1) {
139 guint8 data[1024];
140 // give up if timeout
141 GLib::Error error;
142 std::cout << "server: reading ..." << std::endl;
143 is.read_async(data, sizeof(data), GLib::PRIORITY_DEFAULT_,
144 w.timeout(std::chrono::milliseconds(200), w.cancellable()), w);
145 auto size = gi::expect(is.read_finish(co_await w, &error));
146 if (error) {
147 if (error.matches(G_IO_ERROR, G_IO_ERROR_CANCELLED)) {
148 break;
149 } else {
150 gi::detail::try_throw(std::move(error));
151 }
152 }
153 std::string msg(data, data + size);
154 std::cout << "server: got data: " << msg << std::endl;
155 os.write_all_async(data, size, GLib::PRIORITY_DEFAULT_, w);
156 os.write_all_finish(co_await w, (gsize *)nullptr);
157 }
158
159 std::cout << "server: closing down client" << std::endl;
160 }
161
162 static task<void>
163 async_server(int clients, int &port)
164 {
165 async_result w;
166
167 auto listener = Gio::SocketListener::new_();
168 port = gi::expect(listener.add_any_inet_port());
169
170 int count = 0;
171 while (count < clients) {
172 // accept clients
173 std::cout << "server: accepting" << std::endl;
174 listener.accept_async(w);
175 auto conn = gi::expect(
176 listener.accept_finish(co_await w, (GObject_::Object *)nullptr));
177
178 // spawn client handler
179 std::cout << "server: new connection" << std::endl;
180 // task will run itself to completion, no need to wait/watch it here
181 async_handle_client(conn).detach();
182 ++count;
183 }
184
185 // wait a bit more and shutdown, because we can
186 co_await sleep_for(std::chrono::milliseconds(1000));
187 std::cout << "server going down" << std::endl;
188 }
189
190 void
191 async_demo(GLib::MainLoop loop, int clients)
192 {
193 // run server
194 // dispatch at once to obtain port
195 int port = 0;
196 auto server = async_server(clients, port);
197
198 // make clients
199 int count = 0;
200 for (int i = 0; i < clients; ++i) {
201 ++count;
202 // client task runs to completion, no need to wait/watch
203 // NOTE this frame will stay alive, so count ref is valid
204 async_client(port, i, count).detach();
205 }
206
207 // plain-and-simple; poll regularly and quit when all clients done
208 co_promise<void> cd;
209 auto check = [&]() -> gboolean {
210 if (!count) {
211 cd.set_value();
212 cd.resume();
213 return G_SOURCE_REMOVE;
214 }
215 return G_SOURCE_CONTINUE;
216 };
217 GLib::timeout_add(100, check);
218
219 auto wait = [&]() -> task<void> {
220 // wait clients
221 co_await cd;
222 std::cout << "clients down" << std::endl;
223 // server should also have completed
224 co_await server;
225 std::cout << "server down" << std::endl;
226 loop.quit();
227 };
228
229 // avoid destruct, alternatively detach()
230 auto w = wait();
231
232 std::cout << "running loop" << std::endl;
233 loop.run();
234 std::cout << "ending loop" << std::endl;
235 }
236
237 int
238 main(int argc, char **argv)
239 {
240 auto loop = GLib::MainLoop::new_();
241
242 int clients = argc > 1 ? std::stoi(argv[1]) : 0;
243 std::cout << clients << " clients" << std::endl;
244 if (clients > 0)
245 async_demo(loop, clients);
246 }