-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathspeechflow-util-queue.ts
More file actions
387 lines (364 loc) · 12.8 KB
/
speechflow-util-queue.ts
File metadata and controls
387 lines (364 loc) · 12.8 KB
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
/*
** SpeechFlow - Speech Processing Flow Graph
** Copyright (c) 2024-2026 Dr. Ralf S. Engelschall <rse@engelschall.com>
** Licensed under GPL 3.0 <https://spdx.org/licenses/GPL-3.0-only>
*/
/* standard dependencies */
import { EventEmitter } from "node:events"
/* external dependencies */
import { type, type Type } from "arktype"
import { Duration } from "luxon"
import * as IntervalTree from "node-interval-tree"
/* internal dependencies */
import * as util from "./speechflow-util"
/* import an object with parsing and strict error handling */
export function importObject<T> (name: string, arg: object | string, validator: Type<T, {}>): T {
const obj: object = typeof arg === "string" ?
util.run(`${name}: parsing JSON`, () => JSON.parse(arg)) :
arg
const result = validator(obj)
if (result instanceof type.errors)
throw new Error(`${name}: validation: ${result.summary}`)
return result as T
}
/* queue element */
export type QueueElement = { type: string }
/* queue pointer */
export class QueuePointer<T extends QueueElement> extends EventEmitter {
/* internal state */
private index = 0
private silence = false
/* construction */
constructor (
private name: string,
private queue: Queue<T>
) {
super()
this.setMaxListeners(100)
}
/* control silence operation */
silent (silence: boolean) {
this.silence = silence
}
silently<R> (fn: () => R): R {
this.silence = true
try {
return fn()
}
finally {
this.silence = false
}
}
/* notify about operation */
notify (event: string, info: any) {
if (!this.silence)
this.emit(event, info)
}
/* positioning operations */
maxPosition () {
return this.queue.elements.length
}
position (index?: number): number {
if (index !== undefined) {
this.index = Math.max(0, Math.min(index, this.queue.elements.length))
this.notify("position", { start: this.index })
}
return this.index
}
walk (num: number) {
const indexOld = this.index
if (num > 0)
this.index = Math.min(this.index + num, this.queue.elements.length)
else if (num < 0)
this.index = Math.max(this.index + num, 0)
if (this.index !== indexOld)
this.notify("position", { start: this.index })
}
walkForwardUntil (type: T["type"]): boolean {
while (this.index < this.queue.elements.length
&& this.queue.elements[this.index].type !== type)
this.index++
this.notify("position", { start: this.index })
return this.index < this.queue.elements.length
&& this.queue.elements[this.index].type === type
}
walkBackwardUntil (type: T["type"]): boolean {
if (this.index === this.queue.elements.length && this.index > 0)
this.index--
while (this.index < this.queue.elements.length
&& this.queue.elements[this.index].type !== type) {
if (this.index === 0)
break
this.index--
}
this.notify("position", { start: this.index })
return this.index < this.queue.elements.length
&& this.queue.elements[this.index].type === type
}
/* search operations */
searchForward (type: T["type"]): number {
let position = this.index
while (position < this.queue.elements.length
&& this.queue.elements[position].type !== type)
position++
const found = position < this.queue.elements.length
&& this.queue.elements[position].type === type
this.notify("search", { start: this.index, end: found ? position : this.index })
return found ? position : -1
}
searchBackward (type: T["type"]): number {
let position = this.index
if (position === this.queue.elements.length && position > 0)
position--
while (position < this.queue.elements.length
&& this.queue.elements[position].type !== type) {
if (position === 0)
break
position--
}
const found = position < this.queue.elements.length
&& this.queue.elements[position].type === type
this.notify("search", { start: found ? position : this.index, end: this.index })
return found ? position : -1
}
/* reading operations */
peek (position?: number): T | undefined {
if (position === undefined)
position = this.index
position = Math.max(0, Math.min(position, this.queue.elements.length))
const element = this.queue.elements[position]
this.queue.notify("read", { start: position, end: position })
return element
}
read (): T | undefined {
const element = this.queue.elements[this.index]
if (this.index < this.queue.elements.length)
this.index++
this.queue.notify("read", { start: this.index - 1, end: this.index - 1 })
return element
}
slice (size?: number) {
let slice: T[]
const start = this.index
if (size !== undefined) {
size = Math.max(0, Math.min(size, this.queue.elements.length - this.index))
slice = this.queue.elements.slice(this.index, this.index + size)
this.index += size
}
else {
slice = this.queue.elements.slice(this.index)
this.index = this.queue.elements.length
}
this.queue.notify("read", { start, end: this.index })
return slice
}
/* writing operations */
touch (position?: number) {
if (position === undefined)
position = this.index
if (position >= this.queue.elements.length)
throw new Error(`cannot touch after last element ${position} ${this.queue.elements.length}`)
this.queue.notify("write", { start: position, end: position, op: "touch" })
}
append (element: T) {
this.queue.elements.push(element)
this.index = this.queue.elements.length
this.queue.notify("write", { start: this.index - 1, end: this.index - 1, op: "append" })
}
insert (element: T) {
this.queue.elements.splice(this.index, 0, element)
this.queue.adjustPointers(this, this.index, "insert")
this.queue.notify("write", { start: this.index, end: this.index, op: "insert" })
}
delete () {
if (this.index >= this.queue.elements.length)
throw new Error("cannot delete after last element")
this.queue.elements.splice(this.index, 1)
this.queue.adjustPointers(this, this.index, "delete")
this.queue.notify("write", { start: this.index, end: this.index, op: "delete" })
}
}
/* queue */
export class Queue<T extends QueueElement> extends EventEmitter {
public elements: T[] = []
private pointers = new Map<string, QueuePointer<T>>()
private silence = false
constructor () {
super()
this.setMaxListeners(100)
}
silent (silence: boolean) {
this.silence = silence
}
silently<R> (fn: () => R): R {
this.silence = true
try {
return fn()
}
finally {
this.silence = false
}
}
notify (event: string, info: any) {
if (!this.silence)
this.emit(event, info)
}
pointerUse (name: string): QueuePointer<T> {
if (!this.pointers.has(name))
this.pointers.set(name, new QueuePointer<T>(name, this))
return this.pointers.get(name)!
}
pointerDelete (name: string): void {
if (!this.pointers.has(name))
throw new Error("pointer does not exist")
this.pointers.delete(name)
}
/* adjust all sibling pointer positions (after insert/delete splice)
NOTICE: for insert, pointers AT the index are shifted forward to preserve
their pointer-to-element binding; for delete, pointers AT the index are
intentionally NOT adjusted, causing them to silently advance to the next
element (which shifted into the deleted position). */
adjustPointers (exclude: QueuePointer<T>, index: number, op: "insert" | "delete"): void {
for (const pointer of this.pointers.values()) {
if (pointer === exclude)
continue
const pos = pointer.position()
if (op === "insert" && pos >= index)
pointer.position(pos + 1)
else if (op === "delete" && pos > index)
pointer.position(pos - 1)
}
}
trim (): void {
/* determine minimum pointer position */
let min = this.elements.length
for (const pointer of this.pointers.values()) {
if (min > pointer.position())
min = pointer.position()
}
/* trim the maximum amount of first elements */
if (min > 0) {
this.elements.splice(0, min)
/* shift all pointers */
for (const pointer of this.pointers.values())
pointer.position(pointer.position() - min)
/* notify (start/end refer to pre-splice indices) */
this.notify("write", { start: 0, end: min, op: "trim" })
}
}
clear (): void {
this.elements.length = 0
for (const pointer of this.pointers.values())
pointer.position(0)
}
}
/* meta store */
interface TimeStoreInterval<T> extends IntervalTree.Interval {
item: T
}
export class TimeStore<T> extends EventEmitter {
private tree = new IntervalTree.IntervalTree<TimeStoreInterval<T>>()
store (start: Duration, end: Duration, item: T): void {
this.tree.insert({ low: start.toMillis(), high: end.toMillis(), item })
}
fetch (start: Duration, end: Duration): T[] {
const intervals = this.tree.search(start.toMillis(), end.toMillis())
return intervals.map((interval) => interval.item)
}
prune (_before: Duration): void {
const before = _before.toMillis()
const intervals = this.tree.search(0, before - 1)
for (const interval of intervals)
if (interval.low < before && interval.high < before)
this.tree.remove(interval)
}
clear (): void {
this.tree = new IntervalTree.IntervalTree<TimeStoreInterval<T>>()
}
}
/* asynchronous queue */
export class AsyncQueue<T> {
private queue = new Array<T>()
private resolvers: { resolve: (v: T) => void, reject: (err: Error) => void }[] = []
public destroyed = false
write (v: T) {
if (this.destroyed)
return
const resolver = this.resolvers.shift()
if (resolver)
resolver.resolve(v)
else
this.queue.push(v)
}
async read () {
if (this.queue.length > 0)
return this.queue.shift()!
else
return new Promise<T>((resolve, reject) => { this.resolvers.push({ resolve, reject }) })
}
empty () {
return this.queue.length === 0
}
drain () {
const items = this.queue
this.queue = new Array<T>()
return items
}
destroy () {
this.destroyed = true
for (const resolver of this.resolvers)
resolver.reject(new Error("AsyncQueue destroyed"))
this.resolvers = []
this.queue = []
}
}
/* cached regular expression class */
export class CachedRegExp {
private cache = new Map<string, RegExp>()
compile (pattern: string): RegExp | null {
if (this.cache.has(pattern))
return this.cache.get(pattern)!
try {
const regex = new RegExp(pattern)
this.cache.set(pattern, regex)
return regex
}
catch (_error) {
return null
}
}
clear (): void {
this.cache.clear()
}
size (): number {
return this.cache.size
}
}
/* set of promises */
export class PromiseSet<T> {
private promises = new Set<Promise<T>>()
add (promise: Promise<T>) {
this.promises.add(promise)
promise.finally(() => {
this.promises.delete(promise)
}).catch(() => {})
}
async awaitAll (timeout = 0) {
const deadline = timeout > 0 ? Date.now() + timeout : 0
while (this.promises.size > 0) {
const snapshot = [ ...this.promises ]
const remaining = deadline > 0 ? deadline - Date.now() : 0
if (deadline > 0 && remaining <= 0)
break
if (deadline > 0)
await Promise.race([
Promise.all(snapshot),
new Promise((resolve) => { setTimeout(resolve, remaining) })
])
else
await Promise.all(snapshot)
if (deadline > 0 && Date.now() >= deadline)
break
}
}
}