@avelonjs/core 0.8.5 → 0.8.7
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/README.md +2 -2
- package/package.json +3 -2
- package/src/runtime/after-response.ts +42 -0
- package/src/runtime/dispatcher.ts +9 -14
- package/src/runtime/errands.ts +7 -4
- package/src/runtime/jobs.ts +5 -1
- package/src/runtime/transaction.ts +23 -17
- package/src/runtime/wards.ts +18 -2
package/README.md
CHANGED
|
@@ -473,7 +473,7 @@ The table lists every public export. Capability surface interfaces describe meth
|
|
|
473
473
|
| `InProcessEventDispatcher` | `class InProcessEventDispatcher` | Default `EventDispatcher` implementation. |
|
|
474
474
|
| `KernelMiddleware` | `type KernelMiddleware` | Named middleware callback. |
|
|
475
475
|
| `MaybeNamed` | `type MaybeNamed<TDriver>` | Single driver or named registry. |
|
|
476
|
-
| `MemoryJobBoard` | `class MemoryJobBoard` | Process-local queue and failed table.
|
|
476
|
+
| `MemoryJobBoard` | `class MemoryJobBoard` | Process-local queue and failed table. `take` is FIFO. |
|
|
477
477
|
| `NamedDrivers` | `interface NamedDrivers<TDriver>` | `{ default, instances/mailers/disks/connections }` registry. |
|
|
478
478
|
| `PolicyAbilities` | `type PolicyAbilities` | Ability name to handler map. |
|
|
479
479
|
| `PolicyHandler` | `type PolicyHandler` | Policy callback receiving actor and resource. |
|
|
@@ -502,7 +502,7 @@ The table lists every public export. Capability surface interfaces describe meth
|
|
|
502
502
|
| `detectWardDrift` | `(predicate, fixtures) => WardDrift[]` | Client-side evaluation mismatches. |
|
|
503
503
|
| `disks` | `const disks` | Storage facade with named `disk()` resolution. |
|
|
504
504
|
| `eventDispatcher` | `() => InProcessEventDispatcher` | Process-wide dispatcher instance. |
|
|
505
|
-
| `evaluatePredicate` | `(predicate, row) => boolean \| null` | SQL three-valued client evaluation.
|
|
505
|
+
| `evaluatePredicate` | `(predicate, row) => boolean \| null` | SQL three-valued client evaluation. LIKE honors backslash escapes. |
|
|
506
506
|
| `finishResponse` | `() => Promise<void>` | Flushes `after` listeners and errands. |
|
|
507
507
|
| `flushAfterErrands` | `() => Promise<void>` | Runs errands scheduled with `delivery: 'after'`. |
|
|
508
508
|
| `getConfig` | `() => AvelonConfig` | Active configuration, or `Unavailable`. |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@avelonjs/core",
|
|
3
|
-
"version": "0.8.
|
|
3
|
+
"version": "0.8.7",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "Frozen TypeScript contracts, errors, and capability types shared by Avelon packages.",
|
|
6
6
|
"license": "MIT",
|
|
@@ -30,7 +30,8 @@
|
|
|
30
30
|
"LICENSE"
|
|
31
31
|
],
|
|
32
32
|
"exports": {
|
|
33
|
-
".": "./src/index.ts"
|
|
33
|
+
".": "./src/index.ts",
|
|
34
|
+
"./internal/after-response": "./src/runtime/after-response.ts"
|
|
34
35
|
},
|
|
35
36
|
"scripts": {
|
|
36
37
|
"test": "bun test",
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
2
|
+
|
|
3
|
+
type AfterJob = () => Promise<void>
|
|
4
|
+
type AfterQueue = AfterJob[]
|
|
5
|
+
|
|
6
|
+
const storage = new AsyncLocalStorage<Map<AfterQueue, AfterQueue>>()
|
|
7
|
+
|
|
8
|
+
/** @internal */
|
|
9
|
+
export function withAfterResponseScope<T>(
|
|
10
|
+
run: (pending: () => AfterJob | undefined) => T,
|
|
11
|
+
reportError: (error: unknown) => void,
|
|
12
|
+
): T {
|
|
13
|
+
const queues = new Map<AfterQueue, AfterQueue>()
|
|
14
|
+
const hasWork = () => [...queues.values()].some((queue) => queue.length > 0)
|
|
15
|
+
const flush = () =>
|
|
16
|
+
storage.run(queues, async () => {
|
|
17
|
+
while (hasWork()) {
|
|
18
|
+
for (const queue of queues.values()) {
|
|
19
|
+
for (const job of queue.splice(0)) {
|
|
20
|
+
try {
|
|
21
|
+
await job()
|
|
22
|
+
} catch (error) {
|
|
23
|
+
reportError(error)
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
})
|
|
29
|
+
return storage.run(queues, () => run(() => (hasWork() ? flush : undefined)))
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** @internal */
|
|
33
|
+
export function afterQueue(fallback: AfterQueue): AfterQueue {
|
|
34
|
+
const queues = storage.getStore()
|
|
35
|
+
if (queues === undefined) return fallback
|
|
36
|
+
let queue = queues.get(fallback)
|
|
37
|
+
if (queue === undefined) {
|
|
38
|
+
queue = []
|
|
39
|
+
queues.set(fallback, queue)
|
|
40
|
+
}
|
|
41
|
+
return queue
|
|
42
|
+
}
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import type { QueueDriver } from '../drivers/queue'
|
|
2
|
+
import { Invalid } from '../errors'
|
|
3
|
+
import { afterQueue } from './after-response'
|
|
2
4
|
import {
|
|
3
5
|
Event,
|
|
4
6
|
type EventConstructor,
|
|
@@ -45,7 +47,7 @@ class JsonEventSerializer implements EventSerializer {
|
|
|
45
47
|
}
|
|
46
48
|
|
|
47
49
|
function matchesPattern(pattern: string, name: string): boolean {
|
|
48
|
-
const escaped = pattern.replace(/[
|
|
50
|
+
const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replaceAll('*', '.*')
|
|
49
51
|
return new RegExp(`^${escaped}$`).test(name)
|
|
50
52
|
}
|
|
51
53
|
|
|
@@ -107,8 +109,7 @@ export class InProcessEventDispatcher implements EventDispatcher {
|
|
|
107
109
|
options: EventDispatchOptions = {},
|
|
108
110
|
): Promise<void> {
|
|
109
111
|
if (options.afterCommit && isInTransaction()) {
|
|
110
|
-
|
|
111
|
-
holdUntilCommit(() => this.#dispatchNow(captured, false))
|
|
112
|
+
holdUntilCommit(() => this.#dispatchNow(event, false))
|
|
112
113
|
return
|
|
113
114
|
}
|
|
114
115
|
await this.#dispatchNow(event, false)
|
|
@@ -123,14 +124,8 @@ export class InProcessEventDispatcher implements EventDispatcher {
|
|
|
123
124
|
options: EventDispatchOptions = {},
|
|
124
125
|
): Promise<TResult | null> {
|
|
125
126
|
if (options.afterCommit && isInTransaction()) {
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
try {
|
|
129
|
-
resolve(await this.#untilNow<TResult>(event))
|
|
130
|
-
} catch (error) {
|
|
131
|
-
reject(error)
|
|
132
|
-
}
|
|
133
|
-
})
|
|
127
|
+
throw new Invalid('Events.until cannot defer a result inside a transaction.', {
|
|
128
|
+
metadata: {},
|
|
134
129
|
})
|
|
135
130
|
}
|
|
136
131
|
return this.#untilNow<TResult>(event)
|
|
@@ -138,7 +133,7 @@ export class InProcessEventDispatcher implements EventDispatcher {
|
|
|
138
133
|
|
|
139
134
|
/** Runs listeners scheduled for post-response delivery. */
|
|
140
135
|
async flushAfterResponse(): Promise<void> {
|
|
141
|
-
const pending = this.#after.splice(0
|
|
136
|
+
const pending = afterQueue(this.#after).splice(0)
|
|
142
137
|
for (const job of pending) await job()
|
|
143
138
|
}
|
|
144
139
|
|
|
@@ -176,7 +171,7 @@ export class InProcessEventDispatcher implements EventDispatcher {
|
|
|
176
171
|
/** Clears registrations, the wired queue, and scheduled work. Intended for tests. */
|
|
177
172
|
reset(): void {
|
|
178
173
|
this.#registrations.length = 0
|
|
179
|
-
this.#after.length = 0
|
|
174
|
+
afterQueue(this.#after).length = 0
|
|
180
175
|
this.#queue = undefined
|
|
181
176
|
jobBoard().flush()
|
|
182
177
|
}
|
|
@@ -207,7 +202,7 @@ export class InProcessEventDispatcher implements EventDispatcher {
|
|
|
207
202
|
if (delivery === 'after') {
|
|
208
203
|
const captured = event
|
|
209
204
|
const listener = entry.listener
|
|
210
|
-
this.#after.push(async () => {
|
|
205
|
+
afterQueue(this.#after).push(async () => {
|
|
211
206
|
if (captured.isPropagationStopped()) return
|
|
212
207
|
const result = await listener.handle(captured, { delivery: 'after' })
|
|
213
208
|
if (isFalse(result)) captured.stopPropagation()
|
package/src/runtime/errands.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { DeliveryMode, ListenerContext } from '../events'
|
|
2
2
|
import type { QueueJob } from '../drivers/queue'
|
|
3
3
|
import { Invalid } from '../errors'
|
|
4
|
+
import { afterQueue } from './after-response'
|
|
4
5
|
import { backoffSeconds, jobBoard } from './jobs'
|
|
5
6
|
|
|
6
7
|
/** Job contract for background work with the same three delivery modes as listeners. */
|
|
@@ -37,7 +38,7 @@ export function registerErrand<TPayload>(definition: ErrandDefinition<TPayload>)
|
|
|
37
38
|
/** Clears registered errands and scheduled after-response work. Intended for tests. */
|
|
38
39
|
export function resetErrands(): void {
|
|
39
40
|
registry.clear()
|
|
40
|
-
afterJobs.length = 0
|
|
41
|
+
afterQueue(afterJobs).length = 0
|
|
41
42
|
}
|
|
42
43
|
|
|
43
44
|
async function run(
|
|
@@ -50,7 +51,7 @@ async function run(
|
|
|
50
51
|
|
|
51
52
|
/** Runs errands scheduled with `delivery: 'after'`. */
|
|
52
53
|
export async function flushAfterErrands(): Promise<void> {
|
|
53
|
-
const pending = afterJobs.splice(0
|
|
54
|
+
const pending = afterQueue(afterJobs).splice(0)
|
|
54
55
|
for (const job of pending) await job()
|
|
55
56
|
}
|
|
56
57
|
|
|
@@ -74,7 +75,9 @@ export const Errands = {
|
|
|
74
75
|
}
|
|
75
76
|
if (delivery === 'after') {
|
|
76
77
|
const captured = { definition, payload }
|
|
77
|
-
afterJobs.push(() =>
|
|
78
|
+
afterQueue(afterJobs).push(() =>
|
|
79
|
+
run(captured.definition, captured.payload, { delivery: 'after' }),
|
|
80
|
+
)
|
|
78
81
|
return undefined
|
|
79
82
|
}
|
|
80
83
|
const tries = definition.tries ?? 1
|
|
@@ -142,7 +145,7 @@ export const Errands = {
|
|
|
142
145
|
|
|
143
146
|
/** Drops pending and failed jobs. */
|
|
144
147
|
flush(): void {
|
|
145
|
-
afterJobs.length = 0
|
|
148
|
+
afterQueue(afterJobs).length = 0
|
|
146
149
|
jobBoard().flush()
|
|
147
150
|
},
|
|
148
151
|
}
|
package/src/runtime/jobs.ts
CHANGED
|
@@ -42,12 +42,16 @@ export class MemoryJobBoard {
|
|
|
42
42
|
take(
|
|
43
43
|
options: { queue?: string; limit?: number; now?: number; name?: string } = {},
|
|
44
44
|
): QueueReceipt[] {
|
|
45
|
+
if (options.limit !== undefined && (!Number.isInteger(options.limit) || options.limit < 0)) {
|
|
46
|
+
throw new Invalid('Queue take limit must be a non-negative integer.', {
|
|
47
|
+
metadata: { fields: { limit: ['Expected a non-negative integer.'] } },
|
|
48
|
+
})
|
|
49
|
+
}
|
|
45
50
|
const now = options.now ?? Date.now()
|
|
46
51
|
const selected = [...this.#pending.values()]
|
|
47
52
|
.filter((entry) => entry.availableAt <= now)
|
|
48
53
|
.filter((entry) => options.queue === undefined || entry.job.queue === options.queue)
|
|
49
54
|
.filter((entry) => options.name === undefined || entry.job.name === options.name)
|
|
50
|
-
.sort((left, right) => left.id.localeCompare(right.id))
|
|
51
55
|
.slice(0, options.limit ?? Number.POSITIVE_INFINITY)
|
|
52
56
|
|
|
53
57
|
return selected.map((entry) => {
|
|
@@ -1,16 +1,24 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
2
|
+
|
|
1
3
|
type HeldTask = () => Promise<void>
|
|
4
|
+
type TransactionBoundary = { tasks: HeldTask[] | undefined; generation: number }
|
|
5
|
+
|
|
6
|
+
const storage = new AsyncLocalStorage<TransactionBoundary>()
|
|
7
|
+
let generation = 0
|
|
2
8
|
|
|
3
|
-
|
|
4
|
-
const
|
|
9
|
+
function activeTasks(): HeldTask[] | undefined {
|
|
10
|
+
const boundary = storage.getStore()
|
|
11
|
+
return boundary?.generation === generation ? boundary.tasks : undefined
|
|
12
|
+
}
|
|
5
13
|
|
|
6
14
|
/** Reports whether an enclosing transaction boundary is open. */
|
|
7
15
|
export function isInTransaction(): boolean {
|
|
8
|
-
return
|
|
16
|
+
return activeTasks() !== undefined
|
|
9
17
|
}
|
|
10
18
|
|
|
11
|
-
/** Holds a task until the outermost transaction commits
|
|
19
|
+
/** Holds a task in the active boundary until the outermost transaction commits. */
|
|
12
20
|
export function holdUntilCommit(task: HeldTask): void {
|
|
13
|
-
|
|
21
|
+
activeTasks()?.push(task)
|
|
14
22
|
}
|
|
15
23
|
|
|
16
24
|
/**
|
|
@@ -22,25 +30,23 @@ export function holdUntilCommit(task: HeldTask): void {
|
|
|
22
30
|
export async function runInTransaction<TResult>(
|
|
23
31
|
callback: () => Promise<TResult>,
|
|
24
32
|
): Promise<TResult> {
|
|
25
|
-
|
|
33
|
+
if (isInTransaction()) return callback()
|
|
34
|
+
|
|
35
|
+
const tasks: HeldTask[] = []
|
|
36
|
+
const boundary: TransactionBoundary = { tasks, generation }
|
|
26
37
|
let result: TResult
|
|
27
38
|
try {
|
|
28
|
-
result = await callback
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
if (depth === 0) held.length = 0
|
|
32
|
-
throw error
|
|
39
|
+
result = await storage.run(boundary, callback)
|
|
40
|
+
} finally {
|
|
41
|
+
boundary.tasks = undefined
|
|
33
42
|
}
|
|
34
|
-
|
|
35
|
-
if (depth === 0) {
|
|
36
|
-
const tasks = held.splice(0, held.length)
|
|
43
|
+
if (boundary.generation === generation) {
|
|
37
44
|
for (const task of tasks) await task()
|
|
38
45
|
}
|
|
39
46
|
return result
|
|
40
47
|
}
|
|
41
48
|
|
|
42
|
-
/** Clears transaction
|
|
49
|
+
/** Clears transaction context. Intended for tests. */
|
|
43
50
|
export function resetTransaction(): void {
|
|
44
|
-
|
|
45
|
-
held.length = 0
|
|
51
|
+
generation += 1
|
|
46
52
|
}
|
package/src/runtime/wards.ts
CHANGED
|
@@ -160,10 +160,26 @@ function or(values: readonly TruthValue[]): TruthValue {
|
|
|
160
160
|
return false
|
|
161
161
|
}
|
|
162
162
|
|
|
163
|
+
function escapeRegex(char: string): string {
|
|
164
|
+
return char.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** SQL LIKE: `%` and `_` are wildcards, and `\` escapes the next character. */
|
|
163
168
|
function like(left: unknown, right: unknown, insensitive: boolean): boolean {
|
|
164
169
|
if (typeof left !== 'string' || typeof right !== 'string') return false
|
|
165
|
-
|
|
166
|
-
|
|
170
|
+
let pattern = '^'
|
|
171
|
+
for (let index = 0; index < right.length; index += 1) {
|
|
172
|
+
const char = right[index] ?? ''
|
|
173
|
+
if (char === '\\' && index + 1 < right.length) {
|
|
174
|
+
pattern += escapeRegex(right[index + 1] ?? '')
|
|
175
|
+
index += 1
|
|
176
|
+
continue
|
|
177
|
+
}
|
|
178
|
+
if (char === '%') pattern += '[\\s\\S]*'
|
|
179
|
+
else if (char === '_') pattern += '[\\s\\S]'
|
|
180
|
+
else pattern += escapeRegex(char)
|
|
181
|
+
}
|
|
182
|
+
pattern += '$'
|
|
167
183
|
return new RegExp(pattern, insensitive ? 'i' : undefined).test(left)
|
|
168
184
|
}
|
|
169
185
|
|