@soffits/dsh-card-board 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/watch.js ADDED
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Noticing changes to a board's files, for the live events route.
3
+ *
4
+ * One watch per board, shared by every page that has it open. `fs.watch` on
5
+ * the board folder and its cards folder only triggers a rescan; a slower stat
6
+ * poll does the same where watching is unreliable (network file systems, some
7
+ * containers). The scan compares file sizes and times, so what reaches the
8
+ * listeners is exact: `{ type: 'card', id }` for a card written, added or
9
+ * removed, `{ type: 'board' }` for board.json.
10
+ */
11
+ import { watch as fsWatch } from 'node:fs'
12
+ import { readdir, stat } from 'node:fs/promises'
13
+ import { join } from 'node:path'
14
+ import { ID_PATTERN } from './schema.js'
15
+
16
+ async function snapshot(dir) {
17
+ const files = new Map()
18
+ const add = async (name, path) => {
19
+ const info = await stat(path).catch(() => undefined)
20
+ if (info?.isFile()) files.set(name, `${info.size}:${info.mtimeMs}`)
21
+ }
22
+ await add('board.json', join(dir, 'board.json'))
23
+ const names = await readdir(join(dir, 'cards')).catch(() => [])
24
+ for (const name of names) if (name.endsWith('.json') && ID_PATTERN.test(name.slice(0, -5))) await add(name, join(dir, 'cards', name))
25
+ return files
26
+ }
27
+
28
+ /** What changed between two snapshots, as events. */
29
+ export function changes(before, after) {
30
+ const names = new Set([...before.keys(), ...after.keys()])
31
+ const events = []
32
+ for (const name of [...names].sort()) {
33
+ if (before.get(name) === after.get(name)) continue
34
+ events.push(name === 'board.json' ? { type: 'board' } : { type: 'card', id: name.slice(0, -5) })
35
+ }
36
+ return events
37
+ }
38
+
39
+ /**
40
+ * @param {object} [options]
41
+ * @param {number} [options.pollMs] - the stat poll's interval (default 10 s)
42
+ * @param {number} [options.settleMs] - how long a burst of file events is gathered before one scan (default 120 ms)
43
+ */
44
+ export function createWatches({ pollMs = 10_000, settleMs = 120 } = {}) {
45
+ const boards = new Map()
46
+
47
+ function open(dir) {
48
+ const entry = { listeners: new Set(), files: null, watchers: [], timer: null, poll: null, scanning: null }
49
+ const scan = async () => {
50
+ // One scan at a time; a request during a scan runs once more after it.
51
+ if (entry.scanning) { entry.again = true; return entry.scanning }
52
+ entry.scanning = (async () => {
53
+ do {
54
+ entry.again = false
55
+ const files = await snapshot(dir)
56
+ const events = entry.files === null ? [] : changes(entry.files, files)
57
+ entry.files = files
58
+ for (const event of events) for (const listener of entry.listeners) listener(event)
59
+ } while (entry.again)
60
+ })().finally(() => { entry.scanning = null })
61
+ return entry.scanning
62
+ }
63
+ const soon = () => {
64
+ clearTimeout(entry.timer)
65
+ entry.timer = setTimeout(scan, settleMs)
66
+ }
67
+ for (const path of [dir, join(dir, 'cards')]) {
68
+ try {
69
+ entry.watchers.push(fsWatch(path, { persistent: false }, soon).on('error', () => {}))
70
+ } catch {
71
+ // a missing cards folder: the poll notices when it appears
72
+ }
73
+ }
74
+ entry.poll = setInterval(scan, pollMs)
75
+ entry.poll.unref?.()
76
+ entry.ready = scan()
77
+ entry.close = () => {
78
+ clearTimeout(entry.timer)
79
+ clearInterval(entry.poll)
80
+ for (const watcher of entry.watchers) watcher.close()
81
+ }
82
+ return entry
83
+ }
84
+
85
+ return {
86
+ /**
87
+ * Call `listener` with each change to the board in `dir` until the returned function is called. Resolves once
88
+ * the first scan is done, so changes after that are all reported.
89
+ */
90
+ async watch(dir, listener) {
91
+ let entry = boards.get(dir)
92
+ if (entry === undefined) {
93
+ entry = open(dir)
94
+ boards.set(dir, entry)
95
+ }
96
+ entry.listeners.add(listener)
97
+ await entry.ready
98
+ return () => {
99
+ entry.listeners.delete(listener)
100
+ if (entry.listeners.size === 0 && boards.get(dir) === entry) {
101
+ entry.close()
102
+ boards.delete(dir)
103
+ }
104
+ }
105
+ },
106
+
107
+ /** Stop every watch (the plugin is unloading). */
108
+ close() {
109
+ for (const entry of boards.values()) entry.close()
110
+ boards.clear()
111
+ },
112
+ }
113
+ }