1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
|
// Copyright Epic Games, Inc. All Rights Reserved.
#include <zenutil/sessionsclient.h>
#include <zencore/compactbinarybuilder.h>
#include <zencore/fmtutils.h>
#include <zencore/iobuffer.h>
#include <zencore/logging/logmsg.h>
#include <zencore/process.h>
#include <zencore/system.h>
#include <zencore/thread.h>
#include <vector>
ZEN_THIRD_PARTY_INCLUDES_START
#include <fmt/format.h>
ZEN_THIRD_PARTY_INCLUDES_END
namespace zen {
//////////////////////////////////////////////////////////////////////////
//
// SessionLogSink — thin enqueuer that posts log messages to the
// SessionsServiceClient worker thread via its BlockingQueue.
//
class SessionLogSink final : public logging::Sink
{
public:
explicit SessionLogSink(BlockingQueue<SessionsServiceClient::SessionCommand>* Queue) : m_Queue(Queue) { SetLevel(logging::Info); }
~SessionLogSink() override = default;
void Log(const logging::LogMessage& Msg) override
{
SessionsServiceClient::SessionCommand Cmd;
Cmd.CommandType = SessionsServiceClient::SessionCommand::Type::Log;
Cmd.LogLevel = Msg.GetLevel();
Cmd.LogMessage = CompactString(Msg.GetPayload());
m_Queue->Enqueue(std::move(Cmd));
}
void Flush() override
{
SessionsServiceClient::SessionCommand Cmd;
Cmd.CommandType = SessionsServiceClient::SessionCommand::Type::FlushLogs;
m_Queue->Enqueue(std::move(Cmd));
}
void SetFormatter(std::unique_ptr<logging::Formatter> /*InFormatter*/) override
{
// No formatting needed - we send raw message text
}
private:
BlockingQueue<SessionsServiceClient::SessionCommand>* m_Queue;
};
//////////////////////////////////////////////////////////////////////////
//
// SessionsServiceClient
//
SessionsServiceClient::SessionsServiceClient(Options Opts)
: m_Log(logging::Get("sessionsclient"))
, m_Options(std::move(Opts))
, m_SessionPath(fmt::format("/sessions/{}", m_Options.SessionId))
{
// Strip trailing slash to avoid double-slash when appending paths like /sessions/{id}
while (m_Options.TargetUrl.ends_with('/'))
{
m_Options.TargetUrl.pop_back();
}
// Auto-detect the platform if the caller didn't set one explicitly.
if (m_Options.Platform.empty())
{
m_Options.Platform = std::string(GetRuntimePlatformName());
}
// Auto-fill ClientPid when we can reasonably assume the target is on the
// same machine. The server ALSO defensively gates pid acceptance on
// IsLocalMachineRequest(), so sending a pid for a non-local URL doesn't
// cause false positives — this heuristic just avoids the redundant send.
if (m_Options.ClientPid == 0)
{
const bool IsUnixSocket = !m_Options.ClientSettings.UnixSocketPath.empty();
const bool LooksLocal = IsUnixSocket || m_Options.TargetUrl.find("localhost") != std::string::npos ||
m_Options.TargetUrl.find("127.0.0.1") != std::string::npos;
if (LooksLocal)
{
m_Options.ClientPid = static_cast<uint32_t>(GetCurrentProcessId());
}
}
m_WorkerThread = std::thread([this]() {
zen::SetCurrentThreadName("SessionIO");
WorkerLoop();
});
}
SessionsServiceClient::~SessionsServiceClient()
{
SessionCommand ShutdownCmd;
ShutdownCmd.CommandType = SessionCommand::Type::Shutdown;
m_Queue.Enqueue(std::move(ShutdownCmd));
m_Queue.CompleteAdding();
if (m_WorkerThread.joinable())
{
m_WorkerThread.join();
}
}
CbObject
SessionsServiceClient::BuildRequestBody(CbObjectView Metadata) const
{
CbObjectWriter Writer;
Writer << "appname" << m_Options.AppName;
if (!m_Options.Mode.empty())
{
Writer << "mode" << m_Options.Mode;
}
if (!m_Options.Platform.empty())
{
Writer << "platform" << m_Options.Platform;
}
if (m_Options.ClientPid != 0)
{
Writer << "pid" << m_Options.ClientPid;
}
if (m_Options.ParentSessionId != Oid::Zero)
{
Writer << "parent_session_id" << m_Options.ParentSessionId;
}
if (m_Options.JobId != Oid::Zero)
{
Writer << "jobid" << m_Options.JobId;
}
if (Metadata)
{
Writer.AddObject("metadata", Metadata);
}
return Writer.Save();
}
//////////////////////////////////////////////////////////////////////////
// Public API — non-blocking enqueuers
void
SessionsServiceClient::Announce(CbObjectView Metadata)
{
SessionCommand Cmd;
Cmd.CommandType = SessionCommand::Type::Announce;
if (Metadata)
{
Cmd.Metadata = CbObject::Clone(Metadata);
}
m_Queue.Enqueue(std::move(Cmd));
}
void
SessionsServiceClient::UpdateMetadata(CbObjectView Metadata)
{
SessionCommand Cmd;
Cmd.CommandType = SessionCommand::Type::UpdateMetadata;
if (Metadata)
{
Cmd.Metadata = CbObject::Clone(Metadata);
}
m_Queue.Enqueue(std::move(Cmd));
}
void
SessionsServiceClient::Remove()
{
SessionCommand Cmd;
Cmd.CommandType = SessionCommand::Type::Remove;
m_Queue.Enqueue(std::move(Cmd));
}
logging::SinkPtr
SessionsServiceClient::CreateLogSink()
{
return Ref(new SessionLogSink(&m_Queue));
}
//////////////////////////////////////////////////////////////////////////
// Worker thread — processes all session HTTP I/O
void
SessionsServiceClient::DoAnnounce(HttpClient& Http, CbObjectView Metadata)
{
try
{
CbObject Body = BuildRequestBody(Metadata);
HttpClient::Response Result = Http.Post(m_SessionPath, std::move(Body));
if (Result.Error)
{
ZEN_WARN("sessions announce failed for '{}': HTTP error {} - {}",
m_Options.TargetUrl,
static_cast<int>(Result.Error->ErrorCode),
Result.Error->ErrorMessage);
return;
}
if (!IsHttpOk(Result.StatusCode))
{
ZEN_WARN("sessions announce failed for '{}': HTTP status {}", m_Options.TargetUrl, static_cast<int>(Result.StatusCode));
return;
}
ZEN_DEBUG("session announced to '{}'", m_Options.TargetUrl);
}
catch (const std::exception& Ex)
{
ZEN_WARN("sessions announce failed for '{}': {}", m_Options.TargetUrl, Ex.what());
}
}
void
SessionsServiceClient::DoUpdateMetadata(HttpClient& Http, CbObjectView Metadata)
{
try
{
CbObject Body = BuildRequestBody(Metadata);
MemoryView View = Body.GetView();
IoBuffer Payload = IoBufferBuilder::MakeCloneFromMemory(View, ZenContentType::kCbObject);
HttpClient::Response Result = Http.Put(m_SessionPath, Payload);
if (Result.Error)
{
ZEN_WARN("sessions update failed for '{}': HTTP error {} - {}",
m_Options.TargetUrl,
static_cast<int>(Result.Error->ErrorCode),
Result.Error->ErrorMessage);
return;
}
if (!IsHttpOk(Result.StatusCode))
{
ZEN_WARN("sessions update failed for '{}': HTTP status {}", m_Options.TargetUrl, static_cast<int>(Result.StatusCode));
return;
}
}
catch (const std::exception& Ex)
{
ZEN_WARN("sessions update failed for '{}': {}", m_Options.TargetUrl, Ex.what());
}
}
void
SessionsServiceClient::DoRemove(HttpClient& Http)
{
try
{
HttpClient::Response Result = Http.Delete(m_SessionPath);
if (Result.Error)
{
ZEN_WARN("sessions remove failed for '{}': HTTP error {} - {}",
m_Options.TargetUrl,
static_cast<int>(Result.Error->ErrorCode),
Result.Error->ErrorMessage);
return;
}
if (!IsHttpOk(Result.StatusCode))
{
ZEN_WARN("sessions remove failed for '{}': HTTP status {}", m_Options.TargetUrl, static_cast<int>(Result.StatusCode));
return;
}
ZEN_DEBUG("session removed from '{}'", m_Options.TargetUrl);
}
catch (const std::exception& Ex)
{
ZEN_WARN("sessions remove failed for '{}': {}", m_Options.TargetUrl, Ex.what());
}
}
void
SessionsServiceClient::SendLogBatch(HttpClient& Http, const std::string& LogPath, const std::vector<SessionCommand>& Batch)
{
try
{
CbObjectWriter Writer;
Writer.BeginArray("entries");
for (const SessionCommand& Entry : Batch)
{
Writer.BeginObject();
Writer << "level" << static_cast<int32_t>(Entry.LogLevel);
Writer << "message" << Entry.LogMessage.c_str();
Writer.EndObject();
}
Writer.EndArray();
HttpClient::Response Result = Http.Post(LogPath, Writer.Save());
(void)Result; // Best-effort
}
catch (const std::exception&)
{
// Best-effort — silently discard on failure
}
}
void
SessionsServiceClient::WorkerLoop()
{
HttpClientSettings Settings = m_Options.ClientSettings;
Settings.ConnectTimeout = std::chrono::milliseconds(3000);
Settings.Timeout = std::chrono::milliseconds(5000);
HttpClient Http(m_Options.TargetUrl, Settings);
std::string LogPath = m_SessionPath + "/log";
bool Removed = false;
static constexpr size_t BatchSize = 50;
std::vector<SessionCommand> LogBatch;
LogBatch.reserve(BatchSize);
auto FlushLogBatch = [&]() {
if (!LogBatch.empty())
{
SendLogBatch(Http, LogPath, LogBatch);
LogBatch.clear();
}
};
// Returns false to signal loop exit (Shutdown received)
auto ProcessCommand = [&](SessionCommand& Cmd) -> bool {
switch (Cmd.CommandType)
{
case SessionCommand::Type::Log:
LogBatch.push_back(std::move(Cmd));
if (LogBatch.size() >= BatchSize)
{
FlushLogBatch();
}
return true;
case SessionCommand::Type::FlushLogs:
FlushLogBatch();
return true;
case SessionCommand::Type::Announce:
FlushLogBatch();
DoAnnounce(Http, Cmd.Metadata);
return true;
case SessionCommand::Type::UpdateMetadata:
FlushLogBatch();
DoUpdateMetadata(Http, Cmd.Metadata);
return true;
case SessionCommand::Type::Remove:
FlushLogBatch();
if (!Removed)
{
Removed = true;
DoRemove(Http);
}
return true;
case SessionCommand::Type::Shutdown:
{
// Drain remaining log entries from the queue
SessionCommand Remaining;
while (m_Queue.WaitAndDequeue(Remaining))
{
if (Remaining.CommandType == SessionCommand::Type::Log)
{
LogBatch.push_back(std::move(Remaining));
}
}
FlushLogBatch();
if (!Removed)
{
Removed = true;
DoRemove(Http);
}
return false;
}
}
return true;
};
SessionCommand Cmd;
while (m_Queue.WaitAndDequeue(Cmd))
{
if (!ProcessCommand(Cmd))
{
return;
}
// Drain additional queued entries without blocking (batching optimization)
while (LogBatch.size() < BatchSize && m_Queue.Size() > 0)
{
SessionCommand Extra;
if (m_Queue.WaitAndDequeue(Extra))
{
if (!ProcessCommand(Extra))
{
return;
}
}
}
FlushLogBatch();
}
}
} // namespace zen
|