Repository navigation
Expand file tree
/
Copy pathpython_node_graph.rs
More file actions
327 lines (311 loc) · 12.1 KB
/
Copy pathpython_node_graph.rs
File metadata and controls
327 lines (311 loc) · 12.1 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
//! The executable Python-node graph built from discovered project inputs.
use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyModule, PyModuleMethods, PyResult, Python};
use pyo3::types::{PyDict, PyDictMethods, PyFrozenSet, PyString, PyTuple};
use pyo3::{pyfunction, wrap_pyfunction};
use sqlbuild_analysis::python_selection::main::python_node_graph_indexes::python_node_graph_indexes as graph_indexes;
use sqlbuild_analysis::python_selection::models::{InventoryIndexes, InventoryNode};
use sqlbuild_host::entries::models::UserCodeHost;
use crate::bindings::_helpers::boundary::keyword_request::Request;
use crate::bindings::_helpers::boundary::python_calls::call_with;
use crate::bindings::_helpers::discovery::imported_modules::provider_usages;
use crate::bindings::_helpers::discovery::imported_python_nodes::node_identity;
use crate::bindings::_helpers::graph::python_selection::resolve_python_sql_run_selection;
use crate::bindings::_helpers::graph::views::compiled_graph_keys;
use crate::bindings::_helpers::native_host::host;
use crate::bindings::_helpers::records::construct::{new_record_with, record_class};
use crate::bindings::_helpers::records::fields::field as native_field;
use crate::bindings::_helpers::records::ids::RecordId;
const NAME_KEY: &str = "name";
/// One discovered function collection, its node kind and whether it carries documentation.
const KINDS: [(&str, &str, bool); 4] = [
("loader_functions", "LOADER", false),
("task_functions", "TASK", true),
("asset_functions", "ASSET", true),
("check_functions", "CHECK", true),
];
/// Python classes and shims every node is built with.
struct Vocabulary<'py> {
node: Bound<'py, PyAny>,
kinds: Bound<'py, PyAny>,
sql_ref: Bound<'py, PyAny>,
providers: Bound<'py, PyDict>,
}
fn attribute_value<'py>(value: &Bound<'py, PyAny>, name: &str) -> PyResult<Bound<'py, PyAny>> {
native_field(value, name)
}
/// The kind's metadata field and record of one discovered function.
fn kind_metadata<'py>(
py: Python<'py>,
kind: &str,
discovered: &Bound<'py, PyAny>,
) -> PyResult<(&'static str, Bound<'py, PyAny>)> {
let get = |name: &str| attribute_value(discovered, name);
let metadata = |class: RecordId, fields: &[&str]| -> PyResult<Bound<'py, PyAny>> {
let pairs: Vec<(&str, Bound<'py, PyAny>)> = fields
.iter()
.map(|field| Ok((*field, get(field)?)))
.collect::<PyResult<_>>()?;
new_record_with(py, class, &pairs)
};
Ok(match kind {
"LOADER" => (
"loader",
metadata(
RecordId::DiscoveredPythonLoaderMetadata,
&[
"destination",
"write_strategy",
"cursor_column",
"unique_key",
"columns",
"contract",
"connection_mode",
],
)?,
),
"TASK" => (
"task",
metadata(RecordId::DiscoveredPythonTaskMetadata, &["retry"])?,
),
"ASSET" => (
"asset",
metadata(
RecordId::DiscoveredPythonAssetMetadata,
&["columns", "column_lineage", "retry"],
)?,
),
_ => (
"check",
metadata(RecordId::DiscoveredPythonCheckMetadata, &["severity"])?,
),
})
}
/// One `DiscoveredPythonNode` with its identity and provider usages read by the user shims.
fn python_node<'py>(
vocabulary: &Vocabulary<'py>,
(kind, documented): (&str, bool),
discovered: &Bound<'py, PyAny>,
) -> PyResult<Bound<'py, PyAny>> {
let py: Python<'py> = discovered.py();
let get = |name: &str| attribute_value(discovered, name);
let (metadata_field, metadata) = kind_metadata(py, kind, discovered)?;
let kind_member: Bound<'py, PyAny> = native_field(&vocabulary.kinds, kind)?;
let usages: Bound<'py, PyAny> = provider_usages(&get("function")?, &vocabulary.providers)?;
let mut identity: Bound<'py, PyAny> = get("identity")?;
if identity.is_none() {
identity = node_identity(py, (kind, documented), &get)?;
}
let depends_on: Bound<'py, PyAny> = get("depends_on")?;
let mut sql_deps: Vec<Bound<'py, PyAny>> = Vec::new();
for dependency in depends_on.try_iter()? {
let dependency: Bound<'py, PyAny> = dependency?;
if dependency.is_instance(&vocabulary.sql_ref)? {
sql_deps.push(dependency);
}
}
let mut pairs: Vec<(&str, Bound<'py, PyAny>)> = vec![
("kind", kind_member),
("file_path", get("file_path")?),
("relative_path", get("relative_path")?),
("name", get("name")?),
("function", get("function")?),
("depends_on", depends_on),
("sql_deps", PyTuple::new(py, sql_deps)?.into_any()),
("provider_usages", usages),
("identity", identity),
("description", get("description")?),
(metadata_field, metadata),
];
if documented {
for field in ["tags", "group", "meta"] {
pairs.push((field, get(field)?));
}
}
call_with(&vocabulary.node, &pairs)
}
/// Each node's upstream Python-node names, resolving decorated dependencies through the shim.
fn upstream_names(
py: Python<'_>,
nodes: &[Bound<'_, PyAny>],
sql_ref: &Bound<'_, PyAny>,
) -> PyResult<Vec<Vec<String>>> {
let by_key: Bound<'_, PyDict> = PyDict::new(py);
for node in nodes {
by_key.set_item(native_field(node, "function")?, native_field(node, "name")?)?;
}
for node in nodes {
let name: Bound<'_, PyAny> = native_field(node, "name")?;
by_key.set_item(
PyTuple::new(py, [PyString::new(py, NAME_KEY).into_any(), name.clone()])?,
name,
)?;
}
let dependency_key: Bound<'_, PyAny> = host::entry(py, UserCodeHost::PythonNodeDependencyKey)?;
nodes
.iter()
.map(|node| {
let mut names: Vec<String> = Vec::new();
for dependency in native_field(node, "depends_on")?.try_iter()? {
let dependency: Bound<'_, PyAny> = dependency?;
if dependency.is_instance(sql_ref)? {
continue;
}
let key: Bound<'_, PyAny> = dependency_key.call1((dependency,))?;
if let Some(upstream) = by_key.get_item(key)? {
names.push(upstream.extract()?);
}
}
Ok(names)
})
.collect()
}
fn inventory_node(node: &Bound<'_, PyAny>, upstream: Vec<String>) -> PyResult<InventoryNode> {
Ok(InventoryNode {
name: native_field(node, "name")?.extract()?,
tags: native_field(node, "tags")?.extract()?,
relative_path: native_field(node, "relative_path")?
.call_method0("as_posix")?
.extract()?,
upstream,
})
}
/// The internal executable Python-node graph of discovered project inputs.
pub(crate) fn python_node_graph<'py>(
discovered_inputs: &Bound<'py, PyAny>,
) -> PyResult<Bound<'py, PyAny>> {
let py: Python<'py> = discovered_inputs.py();
let providers: Bound<'py, PyDict> = PyDict::new(py);
for provider in native_field(discovered_inputs, "providers")?.try_iter()? {
let provider: Bound<'py, PyAny> = provider?;
providers.set_item(native_field(&provider, "name")?, provider)?;
}
let vocabulary: Vocabulary<'py> = Vocabulary {
node: record_class(py, RecordId::DiscoveredPythonNode)?,
kinds: host::entry(py, UserCodeHost::PythonNodeKind)?,
sql_ref: host::entry(py, UserCodeHost::SqlResourceRef)?,
providers,
};
let mut nodes: Vec<Bound<'py, PyAny>> = Vec::new();
host::within_identity_pass(py, || {
for (collection, kind, documented) in KINDS {
for discovered in native_field(discovered_inputs, collection)?.try_iter()? {
nodes.push(python_node(&vocabulary, (kind, documented), &discovered?)?);
}
}
Ok(())
})?;
let inventory: Vec<InventoryNode> = nodes
.iter()
.zip(upstream_names(py, &nodes, &vocabulary.sql_ref)?)
.map(|(node, upstream)| inventory_node(node, upstream))
.collect::<PyResult<_>>()?;
graph_record(py, &nodes, graph_indexes(&inventory))
}
type NameRows = Vec<(String, Vec<String>)>;
fn graph_record<'py>(
py: Python<'py>,
nodes: &[Bound<'py, PyAny>],
indexes: InventoryIndexes,
) -> PyResult<Bound<'py, PyAny>> {
let InventoryIndexes {
edges,
upstream,
downstream,
tags,
paths,
} = indexes;
let dependency_edges: Vec<Bound<'py, PyAny>> = edges
.into_iter()
.map(|(upstream_name, downstream_name)| {
new_record_with(
py,
RecordId::PythonNodeDependencyEdge,
&[
(
"upstream_name",
PyString::new(py, &upstream_name).into_any(),
),
(
"downstream_name",
PyString::new(py, &downstream_name).into_any(),
),
],
)
})
.collect::<PyResult<_>>()?;
let adjacency = |rows: NameRows| -> PyResult<Bound<'py, PyDict>> {
let mapping: Bound<'py, PyDict> = PyDict::new(py);
for (name, names) in rows {
mapping.set_item(name, PyTuple::new(py, names)?)?;
}
Ok(mapping)
};
let tag_index: Bound<'py, PyDict> = PyDict::new(py);
for (tag, names) in tags {
tag_index.set_item(tag, PyFrozenSet::new(py, names)?)?;
}
let path_index: Bound<'py, PyDict> = PyDict::new(py);
for (name, path) in paths {
path_index.set_item(name, path)?;
}
let by_name: Bound<'py, PyDict> = PyDict::new(py);
let by_selector: Bound<'py, PyDict> = PyDict::new(py);
for node in nodes {
let name: Bound<'py, PyAny> = native_field(node, "name")?;
let kind: String = native_field(node, "kind")?.getattr("value")?.extract()?;
by_name.set_item(&name, node)?;
by_selector.set_item(format!("{kind}:{}", name.str()?), node)?;
}
new_record_with(
py,
RecordId::PythonNodeGraph,
&[
("nodes", PyTuple::new(py, nodes)?.into_any()),
(
"dependency_edges",
PyTuple::new(py, dependency_edges)?.into_any(),
),
("upstream_deps", adjacency(upstream)?.into_any()),
("downstream_deps", adjacency(downstream)?.into_any()),
("tag_index", tag_index.into_any()),
("path_index", path_index.into_any()),
("nodes_by_name", by_name.into_any()),
("nodes_by_typed_selector", by_selector.into_any()),
],
)
}
/// `PythonSqlRunSelection` of run selectors over the project graph and discovered Python nodes.
pub(crate) fn run_selection_from_inputs<'py>(
(select, exclude): (Vec<String>, Vec<String>),
project_graph: &Bound<'py, PyAny>,
discovered_inputs: &Bound<'py, PyAny>,
) -> PyResult<Bound<'py, PyAny>> {
let py: Python<'py> = project_graph.py();
let python_graph: Bound<'py, PyAny> = python_node_graph(discovered_inputs)?;
let (sql_keys, python_node_names) =
resolve_python_sql_run_selection(project_graph, &python_graph, select, exclude)?;
new_record_with(
py,
RecordId::PythonSqlRunSelection,
&[
("sql_keys", compiled_graph_keys(py, sql_keys)?.into_any()),
(
"python_node_names",
PyFrozenSet::new(py, python_node_names)?.into_any(),
),
],
)
}
/// Build the internal executable Python-node graph from discovered project inputs.
#[pyfunction]
#[pyo3(signature = (**options))]
fn build_python_node_graph<'py>(
options: Option<&Bound<'py, PyDict>>,
) -> PyResult<Bound<'py, PyAny>> {
let request = Request::new("build_python_node_graph", options)?;
python_node_graph(&request.get("discovered_inputs")?)
}
pub(crate) fn register(module: &Bound<'_, PyModule>) -> PyResult<()> {
module.add_function(wrap_pyfunction!(build_python_node_graph, module)?)?;
Ok(())
}