anvil/log_throttle.rs
1//! The service of the standard plugin anvil-log-throttle (`anvil_log_throttle.h`).
2//!
3//! **`anvil-log-throttle.messages`** ([`Messages`], 1.20): the table of the
4//! messages of the throttled logs (error.log by default) with their counts as
5//! they happen, rather than when the throttle's next report reaches the file.
6//! A message is its log, the game's source file and line (the game's C++ code,
7//! not a mod's file) and the text; its count is the lines written plus the
8//! lines the throttle only counted. The table is kept from [`Messages::keep`]
9//! on (the plugin's script errors panel starts it at load when it is on), and
10//! nothing leaves it until the process ends. Any thread.
11//!
12//! Depend on anvil-log-throttle in plugin.toml (`[[dependencies]] id =
13//! "anvil-log-throttle"`, `version = "^1.20"`, `optional = true` when the
14//! plugin also works without it) and look the service up with
15//! [`Messages::get`].
16//!
17//! ```no_run
18//! use anvil::log_throttle::Messages;
19//! # fn load(host: &anvil::Host) -> anvil::Result<()> {
20//! let messages = Messages::get(host).expect("anvil-log-throttle.messages");
21//! messages.keep()?;
22//! // Later: what changed since the last look.
23//! let mut seen = 0;
24//! let totals = messages.totals()?;
25//! for m in messages.changed_since(seen)? {
26//! host.log(anvil::LogLevel::Info, format_args!("{} x{}", m.text, m.count()));
27//! }
28//! seen = totals.version;
29//! # let _ = seen;
30//! # Ok(())
31//! # }
32//! ```
33
34use std::ffi::{c_char, CStr};
35use std::fmt;
36use std::mem::size_of;
37use std::ptr;
38
39use crate::error::{check, Result};
40use crate::host::Host;
41use crate::sys::{
42 AnvilLogMessage, AnvilLogMessagesService, AnvilLogTotals, ANVIL_LOG_MESSAGES_SERVICE_VERSION,
43};
44use crate::table::Table;
45
46/// The service's name.
47pub const SERVICE: &CStr = c"anvil-log-throttle.messages";
48/// The service's major version.
49pub const VERSION: u32 = ANVIL_LOG_MESSAGES_SERVICE_VERSION;
50
51/// The table's totals.
52#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
53pub struct Totals {
54 /// Whether the table is kept; before [`Messages::keep`] everything is 0.
55 pub keeping: bool,
56 /// Grows with every line the table takes: the same value, nothing changed.
57 pub version: u64,
58 /// `GetTickCount64()` when the table started.
59 pub since_ms: u64,
60 /// Messages in the table.
61 pub messages: u64,
62 /// Lines of the throttled logs since then that reached the log.
63 pub written: u64,
64 /// Lines the throttle counted instead.
65 pub counted: u64,
66 /// Of those, lines of messages the full table (32768 messages) does not take.
67 pub untracked: u64,
68}
69
70/// A message of the table and its counts at the time of the read.
71#[derive(Clone, Debug, Default, PartialEq, Eq)]
72pub struct Message {
73 /// Its position in the table, from 0, in the order first seen.
74 pub index: u64,
75 /// The table's version at its last line.
76 pub version: u64,
77 /// Lines that reached the log.
78 pub written: u64,
79 /// Lines the throttle counted instead.
80 pub counted: u64,
81 /// The log's file name, `error.log`.
82 pub log: String,
83 /// The game's C++ source file name, `triggerimplementation.cpp`.
84 pub source: String,
85 /// Its line.
86 pub source_line: i32,
87 /// The text, without the line end.
88 pub text: String,
89}
90
91impl Message {
92 /// Every line of the message: written and counted.
93 pub fn count(&self) -> u64 {
94 self.written + self.counted
95 }
96}
97
98fn owned(p: *const c_char) -> String {
99 if p.is_null() {
100 return String::new();
101 }
102 // SAFETY: a NUL-terminated string the service keeps until the process ends.
103 unsafe { CStr::from_ptr(p) }.to_string_lossy().into_owned()
104}
105
106/// The `anvil-log-throttle.messages` service.
107#[derive(Clone, Copy)]
108pub struct Messages {
109 table: Table<AnvilLogMessagesService>,
110}
111
112impl fmt::Debug for Messages {
113 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
114 f.debug_struct("Messages")
115 .field("size", &self.table.size())
116 .finish()
117 }
118}
119
120impl Messages {
121 /// The service; `None` without anvil-log-throttle 1.20.0.
122 pub fn get(host: &Host) -> Option<Self> {
123 // SAFETY: the table type of anvil-log-throttle.messages version 1.
124 let table = unsafe { host.service::<AnvilLogMessagesService>(SERVICE, VERSION) }?;
125 Some(Self { table })
126 }
127
128 /// The C table, for what this crate does not wrap.
129 pub fn c_api(&self) -> Table<AnvilLogMessagesService> {
130 self.table
131 }
132
133 /// Starts the table, if it is not kept yet. Lines before it are not in it.
134 pub fn keep(&self) -> Result<()> {
135 let f = function!(self.table, AnvilLogMessagesService, keep)?;
136 // SAFETY: no arguments.
137 check(unsafe { f() }, || "log messages keep".to_owned())
138 }
139
140 /// The table's totals.
141 pub fn totals(&self) -> Result<Totals> {
142 let f = function!(self.table, AnvilLogMessagesService, totals)?;
143 let mut out = AnvilLogTotals {
144 size: size_of::<AnvilLogTotals>() as u32,
145 keeping: 0,
146 version: 0,
147 since_ms: 0,
148 messages: 0,
149 written: 0,
150 counted: 0,
151 untracked: 0,
152 };
153 // SAFETY: a struct the service fills as far as its size says.
154 check(unsafe { f(&mut out) }, || "log messages totals".to_owned())?;
155 Ok(Totals {
156 keeping: out.keeping != 0,
157 version: out.version,
158 since_ms: out.since_ms,
159 messages: out.messages,
160 written: out.written,
161 counted: out.counted,
162 untracked: out.untracked,
163 })
164 }
165
166 /// At most `capacity` messages from position `first` on whose version is
167 /// above `changed_after` (0: every one), and the position to read on from:
168 /// the table's size once the read got to its end.
169 pub fn read(
170 &self,
171 first: u64,
172 changed_after: u64,
173 capacity: u32,
174 ) -> Result<(Vec<Message>, u64)> {
175 let f = function!(self.table, AnvilLogMessagesService, read)?;
176 let empty = AnvilLogMessage {
177 index: 0,
178 version: 0,
179 written: 0,
180 counted: 0,
181 log: ptr::null(),
182 source: ptr::null(),
183 source_line: 0,
184 reserved: 0,
185 text: ptr::null(),
186 };
187 let mut raw = vec![empty; capacity as usize];
188 let mut count = 0u32;
189 let mut next = 0u64;
190 let out = if raw.is_empty() {
191 ptr::null_mut()
192 } else {
193 raw.as_mut_ptr()
194 };
195 check(
196 // SAFETY: room for `capacity` messages of this size, and two outputs.
197 unsafe {
198 f(
199 first,
200 changed_after,
201 out,
202 capacity,
203 size_of::<AnvilLogMessage>() as u32,
204 &mut count,
205 &mut next,
206 )
207 },
208 || format!("log messages read from {first}"),
209 )?;
210 raw.truncate(count as usize);
211 let messages = raw
212 .iter()
213 .map(|m| Message {
214 index: m.index,
215 version: m.version,
216 written: m.written,
217 counted: m.counted,
218 log: owned(m.log),
219 source: owned(m.source),
220 source_line: m.source_line,
221 text: owned(m.text),
222 })
223 .collect();
224 Ok((messages, next))
225 }
226
227 /// Every message whose version is above `version` (0: the whole table),
228 /// read in pieces of 1024. Pass the `version` of the last [`Totals`] to
229 /// get what changed since.
230 pub fn changed_since(&self, version: u64) -> Result<Vec<Message>> {
231 let mut all = Vec::new();
232 let mut first = 0;
233 loop {
234 let (part, next) = self.read(first, version, 1024)?;
235 let full = part.len() == 1024;
236 all.extend(part);
237 if !full || next <= first {
238 return Ok(all);
239 }
240 first = next;
241 }
242 }
243}