-
-
Notifications
You must be signed in to change notification settings - Fork 275
Expand file tree
/
Copy pathsample.ts
More file actions
278 lines (271 loc) · 7.8 KB
/
sample.ts
File metadata and controls
278 lines (271 loc) · 7.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
import type {Cmd, Node, StateRef} from './index.h'
import type {CommonUnit, DataCarrier, Store} from './unit.h'
import {combine} from './combine'
import {mov, userFnCall, read, calc} from './step'
import {createStateRef, readRef} from './stateRef'
import {callStackAReg} from './caller'
import {processArgsToConfig} from './config'
import {getStoreState, getGraph} from './getter'
import {
assertNodeSet,
assertTarget,
is,
isObject,
isVoid,
isFunction,
} from './is'
import {createStore, getUnitTrace, setUnitTrace} from './createUnit'
import {createEvent} from './createUnit'
import {createNode} from './createNode'
import {assert, deprecate} from './throw'
import {add, forEach} from './collection'
import {STACK, VALUE} from './tag'
import {applyTemplate} from './template'
import {own} from './own'
import {createLinkNode} from './forward'
import {generateErrorTitle} from './naming'
const sampleConfigFields = ['source', 'clock', 'target']
const fieldErrorMessage = (method: string, field: string) =>
method + `: ${field} should be defined`
export function validateSampleConfig(config: any, method: string) {
let atLeastOneFieldExists = false
forEach(sampleConfigFields, field => {
if (field in config) {
assert(config[field] != null, fieldErrorMessage(method, field))
atLeastOneFieldExists = true
}
})
return atLeastOneFieldExists
}
export function sample(...args: any[]) {
let target
let name
let [[source, clock, fn], metadata] = processArgsToConfig(args)
let sid
let batch = true
let filter
const errorTitle = generateErrorTitle('sample', metadata)
/** config case */
if (
isVoid(clock) &&
isObject(source) &&
validateSampleConfig(source, errorTitle)
) {
clock = source.clock
fn = source.fn
if ('batch' in source) {
batch = source.batch
} else {
deprecate(!('greedy' in source), 'greedy in sample', 'batch', errorTitle)
batch = !source.greedy
}
filter = source.filter
/** optional target & name accepted only from config */
target = source.target
name = source.name
sid = source.sid
source = source.source
}
return createSampling(
'sample',
clock,
source,
filter,
target,
fn,
name,
metadata,
batch,
true,
false,
sid,
)
}
export const createSampling = (
method: string,
clock: DataCarrier | DataCarrier[] | void,
source: DataCarrier | Array<Store<any>> | Record<string, Store<any>> | void,
filter: any,
target: DataCarrier | DataCarrier[] | void,
fn: any,
name: string | undefined,
metadata: object | void,
batch: boolean,
targetMayBeStore: boolean,
filterRequired: boolean,
sid?: string | undefined,
) => {
const errorTitle = generateErrorTitle(method, metadata)
const isUpward = !!target
assert(
!isVoid(source) || !isVoid(clock),
fieldErrorMessage(errorTitle, 'either source or clock'),
)
let sourceIsClock = false
if (isVoid(source)) {
sourceIsClock = true
} else if (!is.unit(source)) {
source = combine(source)
}
if (isVoid(clock)) {
/** still undefined! */
clock = source
} else {
assertNodeSet(clock, errorTitle, 'clock')
if (Array.isArray(clock)) {
clock = createLinkNode(clock as CommonUnit[], [], [], method)
}
}
if (sourceIsClock) {
source = clock
}
if (!metadata && !name) {
/**
* When there is no metadata and name, assign source name as a fallback.
* This is very misleading behavior (sample unit is not a source unit)
* introduced a long time ago, so we keep it only for backward compatibility
* for cases which were covered at the time.
*
* Therefore, this name will not be used as a fallback for newer (23.4.0) cases
* (a.k.a. sample support for patronum debug traces)
* and metadata will not be created
*/
name = (source as any).shortName
} else if (metadata && name) {
/** name field from sample config (from user) has highest priority */
;(metadata as any).name = name
} else if (!metadata && name) {
/**
* metadata comes from plugin, so when name is present and metadata is missing,
* we need to create fresh metadata with name
*/
metadata = {name}
}
let filterType: 'none' | 'unit' | 'fn' = 'none'
if (filterRequired || filter) {
if (is.unit(filter)) {
filterType = 'unit'
} else {
assert(isFunction(filter), '`filter` should be function or unit')
filterType = 'fn'
}
}
if (target) {
assertNodeSet(target, errorTitle, 'target')
assertTarget(errorTitle, target)
} else {
if (
filterType === 'none' &&
targetMayBeStore &&
is.store(source) &&
is.store(clock)
) {
const initialState = fn
? fn(readRef(getStoreState(source)), readRef(getStoreState(clock)))
: readRef(getStoreState(source))
// @ts-expect-error
target = createStore(initialState, {name, sid, or: metadata})
} else {
target = createEvent({name, derived: true, or: metadata})
applyTemplate('sampleTarget', getGraph(target))
}
}
// const targetTemplate =
// isUpward && is.unit(target) && getGraph(target).meta.nativeTemplate
const clockState = createStateRef()
let filterNodes: Cmd[] = []
const syncNodes: Node[] = []
if (filterType === 'unit') {
const [filterRef, hasFilter, isFilterStore, filterSyncNode] =
syncSourceState(
filter as DataCarrier,
target,
// @ts-expect-error
clock,
clockState,
method,
)
filterSyncNode && add(syncNodes, filterSyncNode)
if (!isFilterStore) {
filterNodes.push(...readAndFilter(hasFilter))
}
filterNodes.push(...readAndFilter(filterRef))
}
const jointNodeSeq: Cmd[] = []
if (sourceIsClock) {
if (batch) {
add(jointNodeSeq, read(clockState, true, true))
}
} else {
const [sourceRef, hasSource, isSourceStore, sourceSyncNode] =
syncSourceState(
// @ts-expect-error
source,
target,
clock,
clockState,
method,
)
sourceSyncNode && add(syncNodes, sourceSyncNode)
if (!isSourceStore) {
jointNodeSeq.push(...readAndFilter(hasSource))
}
add(jointNodeSeq, read(sourceRef, true, batch))
}
const jointNode = createLinkNode(
// @ts-expect-error
clock,
target,
[
applyTemplate('sampleSourceLoader'),
mov({from: STACK, target: clockState}),
...jointNodeSeq,
...filterNodes,
read(clockState),
filterType === 'fn' && userFnCall((src, _, {a}) => filter(src, a), true),
fn && userFnCall(callStackAReg),
applyTemplate('sampleSourceUpward', isUpward),
],
method,
fn,
)
// @ts-expect-error
own(source, [jointNode])
own(jointNode, syncNodes)
Object.assign(jointNode.meta, metadata, {joint: true, stateRef: clockState})
setUnitTrace(jointNode, getUnitTrace(sample))
return target
}
const readAndFilter = (state: StateRef) => [
read(state),
calc((upd, scope, {a}) => a, true),
]
const syncSourceState = (
source: DataCarrier,
target: DataCarrier | DataCarrier[],
clock: DataCarrier | DataCarrier[],
clockState: StateRef,
method: string,
) => {
const isSourceStore = is.store(source)
const sourceRef = isSourceStore ? getStoreState(source) : createStateRef()
const hasSource = createStateRef(isSourceStore)
let syncNode: Node | undefined
if (!isSourceStore) {
syncNode = createNode({
parent: source,
node: [
mov({from: STACK, target: sourceRef}),
mov({from: VALUE, store: true, target: hasSource}),
],
family: {
owners: [...new Set([source, target, clock].flat())],
links: target,
},
meta: {op: method},
regional: true,
})
}
applyTemplate('sampleSource', hasSource, sourceRef, clockState)
return [sourceRef, hasSource, isSourceStore, syncNode] as const
}