Updated history approach.

This commit is contained in:
2026-02-14 22:43:42 -05:00
parent fddd499398
commit 9985473ceb
2 changed files with 20 additions and 32 deletions

View File

@@ -98,7 +98,7 @@ int cb_chat(
for (Session* s = head; s; s = s->next) {
if (session_has_username(s)) {
yyjson_mut_val* uobj = yyjson_mut_obj(wdoc);
yyjson_mut_arr_add_val(wusers, uobj);
/* add each user once */
yyjson_mut_arr_add_val(wusers, uobj);
yyjson_mut_obj_add_uint(
wdoc, uobj, "id", session_get_id(s)
@@ -108,19 +108,7 @@ int cb_chat(
);
}
}
// Include last 100 messages in the welcome history array.
yyjson_mut_val* whist = yyjson_mut_arr(wdoc);
yyjson_mut_obj_add_val(wdoc, wdata, "history", whist);
for (size_t i = 0; i < history_count; ++i) {
size_t idx =
(history_pos + HISTORY_SIZE - history_count + i) %
HISTORY_SIZE;
// Append raw JSON string into history array.
yyjson_mut_val* raw = yyjson_mut_strn(
wdoc, history[idx], history_len[idx]
);
yyjson_mut_arr_add_val(whist, raw);
}
// History will be streamed individually after welcome.
size_t out_len;
char* out = yyjson_mut_write(wdoc, 0, &out_len);
@@ -129,10 +117,8 @@ int cb_chat(
: SESSION_CHAT_BUF_SIZE;
sess->buf_len = copy_len;
memcpy(&sess->buf[LWS_PRE], out, copy_len);
lws_write(
sess->wsi, &sess->buf[LWS_PRE], sess->buf_len,
LWS_WRITE_TEXT
);
// Schedule the welcome frame for writable callback.
lws_callback_on_writable(sess->wsi);
free(out);
yyjson_mut_doc_free(wdoc);
@@ -289,6 +275,21 @@ int cb_chat(
sess->wsi, &sess->buf[LWS_PRE], sess->buf_len,
LWS_WRITE_TEXT
);
// #1b: Stream history messages to new client.
for (size_t i = 0; i < history_count; ++i) {
size_t idx =
(history_pos + HISTORY_SIZE - history_count + i) %
HISTORY_SIZE;
size_t hist_len = history_len[idx];
size_t send_len = hist_len < SESSION_CHAT_BUF_SIZE
? hist_len
: SESSION_CHAT_BUF_SIZE;
memcpy(&sess->buf[LWS_PRE], history[idx], send_len);
lws_write(
sess->wsi, &sess->buf[LWS_PRE], send_len,
LWS_WRITE_TEXT
);
}
free(ack_out);
yyjson_mut_doc_free(ackdoc);
}
@@ -312,7 +313,7 @@ int cb_chat(
size_t out_len;
char* out = yyjson_mut_write(mdoc, 0, &out_len);
/* Store this msg-event JSON in the circular history buffer */
// Store this msg-event JSON in the circular history buffer.
if (history_count == HISTORY_SIZE) {
free(history[history_pos]);
} else {