|
24 | 24 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
25 | 25 | */ |
26 | 26 |
|
| 27 | +import GLib from 'gi://GLib'; |
| 28 | +import Gio from 'gi://Gio'; |
27 | 29 | import GObject from 'gi://GObject'; |
28 | 30 |
|
29 | 31 | const cbFun = (d, c) => { |
@@ -79,9 +81,69 @@ export const Values = GObject.registerClass({ |
79 | 81 | while (buf.length > maxPoints) buf.shift(); |
80 | 82 | } |
81 | 83 |
|
82 | | - clearTimeSeries() { |
| 84 | + clearTimeSeries(cachePath) { |
83 | 85 | this._timeSeries = {}; |
84 | 86 | this._timeSeriesFormat = {}; |
| 87 | + if (cachePath) { |
| 88 | + try { |
| 89 | + const file = Gio.File.new_for_path(cachePath); |
| 90 | + if (file.query_exists(null)) |
| 91 | + file.delete(null); |
| 92 | + } catch (e) { |
| 93 | + // ignore |
| 94 | + } |
| 95 | + } |
| 96 | + } |
| 97 | + |
| 98 | + saveTimeSeries(path) { |
| 99 | + try { |
| 100 | + const obj = { |
| 101 | + version: 1, |
| 102 | + timeSeries: this._timeSeries, |
| 103 | + timeSeriesFormat: this._timeSeriesFormat |
| 104 | + }; |
| 105 | + const json = JSON.stringify(obj); |
| 106 | + const dir = GLib.path_get_dirname(path); |
| 107 | + GLib.mkdir_with_parents(dir, 0o755); |
| 108 | + GLib.file_set_contents(path, json); |
| 109 | + } catch (e) { |
| 110 | + // ignore write failures |
| 111 | + } |
| 112 | + } |
| 113 | + |
| 114 | + loadTimeSeries(path) { |
| 115 | + try { |
| 116 | + const file = Gio.File.new_for_path(path); |
| 117 | + if (!file.query_exists(null)) return; |
| 118 | + const [ok, contents] = GLib.file_get_contents(path); |
| 119 | + if (!ok) return; |
| 120 | + const decoder = new TextDecoder('utf-8'); |
| 121 | + const json = decoder.decode(contents); |
| 122 | + const obj = JSON.parse(json); |
| 123 | + if (!obj || obj.version !== 1) return; |
| 124 | + if (obj.timeSeries && typeof obj.timeSeries === 'object') |
| 125 | + this._timeSeries = obj.timeSeries; |
| 126 | + if (obj.timeSeriesFormat && typeof obj.timeSeriesFormat === 'object') |
| 127 | + this._timeSeriesFormat = obj.timeSeriesFormat; |
| 128 | + const now = Date.now() / 1000; |
| 129 | + const maxAge = this._getHistoryDurationSeconds(); |
| 130 | + const cutoff = now - maxAge; |
| 131 | + for (const key in this._timeSeries) { |
| 132 | + const buf = this._timeSeries[key]; |
| 133 | + if (!Array.isArray(buf)) { |
| 134 | + delete this._timeSeries[key]; |
| 135 | + continue; |
| 136 | + } |
| 137 | + while (buf.length > 0 && buf[0].t < cutoff) |
| 138 | + buf.shift(); |
| 139 | + if (buf.length === 0) { |
| 140 | + delete this._timeSeries[key]; |
| 141 | + delete this._timeSeriesFormat[key]; |
| 142 | + } |
| 143 | + } |
| 144 | + } catch (e) { |
| 145 | + // ignore corrupt or missing file |
| 146 | + } |
85 | 147 | } |
86 | 148 |
|
87 | 149 | getTimeSeries(key) { |
|
0 commit comments