relay-knowledge 1.1.17

Graph-database-based knowledge graph project.
Documentation
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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
use std::collections::BTreeMap;

use rusqlite::{Connection, params};

use crate::{
    domain::{
        SoftwareAssertionMode, SoftwareEntityKind, SoftwarePredicate, SoftwareSourceKind,
        SoftwareStatementResolution,
    },
    storage::StorageError,
};

use super::{OntologyBuilder, OntologyEntityCandidate, resolution_state, source_kind_for};

pub(super) fn collect_build_targets(
    connection: &Connection,
    builder: &mut OntologyBuilder,
) -> Result<(), StorageError> {
    let mut statement = connection.prepare(
        "
        SELECT target_id, ecosystem, language_id, name, kind, command, output_hint,
               source_kind, evidence_path, evidence_line_start, evidence_line_end,
               confidence_basis_points
        FROM software_build_targets
        WHERE source_scope = ?1
        ORDER BY evidence_path ASC, evidence_line_start ASC, target_id ASC
        ",
    )?;
    let rows = statement.query_map(params![builder.source_scope], |row| {
        Ok(BuildRow {
            projection_id: row.get(0)?,
            ecosystem: row.get(1)?,
            language_id: row.get(2)?,
            name: row.get(3)?,
            kind: row.get(4)?,
            command: row.get(5)?,
            output_hint: row.get(6)?,
            source_kind: row.get(7)?,
            path: row.get(8)?,
            line_start: row.get(9)?,
            line_end: row.get(10)?,
            confidence: row.get(11)?,
        })
    })?;
    for row in rows {
        let row = row?;
        let evidence = builder.evidence(&row.path, row.line_start, row.line_end)?;
        let source_kind = source_kind_for(&row.source_kind, &row.path);
        let entity_kind = if row.kind == "job" {
            SoftwareEntityKind::BuildJob
        } else {
            SoftwareEntityKind::BuildDefinition
        };
        let mut attributes = BTreeMap::new();
        attributes.insert("ecosystem".to_owned(), row.ecosystem.clone());
        attributes.insert("language_id".to_owned(), row.language_id);
        attributes.insert("build_kind".to_owned(), row.kind.clone());
        if let Some(command) = row.command {
            attributes.insert("command".to_owned(), command);
        }
        if let Some(output_hint) = row.output_hint.as_ref() {
            attributes.insert("output_hint".to_owned(), output_hint.clone());
        }
        let build_key = builder.add_entity(OntologyEntityCandidate {
            projection_id: Some(&row.projection_id),
            kind: entity_kind,
            name: row.name,
            namespace: Some(row.ecosystem.clone()),
            source_kind,
            evidence: evidence.clone(),
            attributes,
        })?;
        let parent = if entity_kind == SoftwareEntityKind::BuildJob {
            let mut pipeline_attributes = BTreeMap::new();
            pipeline_attributes.insert("language_id".to_owned(), "yaml".to_owned());
            let pipeline_key = builder.add_entity(OntologyEntityCandidate {
                projection_id: None,
                kind: SoftwareEntityKind::Pipeline,
                name: row.path.clone(),
                namespace: Some(row.ecosystem.clone()),
                source_kind: SoftwareSourceKind::Ci,
                evidence: evidence.clone(),
                attributes: pipeline_attributes,
            })?;
            builder.add_statement(
                builder.snapshot_key.clone(),
                SoftwarePredicate::Contains,
                Some(pipeline_key.clone()),
                None,
                SoftwareSourceKind::Ci,
                evidence.clone(),
                SoftwareAssertionMode::Declared,
                SoftwareStatementResolution::Resolved,
                row.confidence,
            )?;
            pipeline_key
        } else {
            builder.snapshot_key.clone()
        };
        builder.add_statement(
            parent,
            SoftwarePredicate::Contains,
            Some(build_key.clone()),
            None,
            source_kind,
            evidence.clone(),
            SoftwareAssertionMode::Declared,
            SoftwareStatementResolution::Resolved,
            row.confidence,
        )?;
        if let Some(output_hint) = row.output_hint {
            let mut artifact_attributes = BTreeMap::new();
            artifact_attributes.insert("ecosystem".to_owned(), row.ecosystem.clone());
            let artifact_key = builder.add_entity(OntologyEntityCandidate {
                projection_id: None,
                kind: SoftwareEntityKind::ReleaseArtifact,
                name: output_hint,
                namespace: Some(row.ecosystem),
                source_kind,
                evidence: evidence.clone(),
                attributes: artifact_attributes,
            })?;
            builder.add_statement(
                build_key,
                SoftwarePredicate::Builds,
                Some(artifact_key),
                None,
                source_kind,
                evidence,
                SoftwareAssertionMode::Declared,
                SoftwareStatementResolution::Resolved,
                row.confidence,
            )?;
        }
    }
    Ok(())
}

pub(super) fn collect_iac_resources(
    connection: &Connection,
    builder: &mut OntologyBuilder,
) -> Result<(), StorageError> {
    let mut statement = connection.prepare(
        "
        SELECT resource_id, language_id, provider, resource_kind, name, scope_hint,
               target_hint, resolution_state, source_kind, evidence_path,
               evidence_line_start, evidence_line_end, confidence_basis_points
        FROM software_iac_resources
        WHERE source_scope = ?1
        ORDER BY evidence_path ASC, evidence_line_start ASC, resource_id ASC
        ",
    )?;
    let rows = statement.query_map(params![builder.source_scope], |row| {
        Ok(IacRow {
            projection_id: row.get(0)?,
            language_id: row.get(1)?,
            provider: row.get(2)?,
            resource_kind: row.get(3)?,
            name: row.get(4)?,
            scope_hint: row.get(5)?,
            target_hint: row.get(6)?,
            resolution_state: row.get(7)?,
            source_kind: row.get(8)?,
            path: row.get(9)?,
            line_start: row.get(10)?,
            line_end: row.get(11)?,
            confidence: row.get(12)?,
        })
    })?;
    for row in rows {
        collect_iac_row(builder, row?)?;
    }
    Ok(())
}

fn collect_iac_row(builder: &mut OntologyBuilder, row: IacRow) -> Result<(), StorageError> {
    let evidence = builder.evidence(&row.path, row.line_start, row.line_end)?;
    let source_kind = source_kind_for(&row.source_kind, &row.path);
    let resolution = resolution_state(&row.resolution_state);
    if matches!(row.provider.as_str(), "systemd" | "launchd") {
        let deployment_key = deployment_unit(builder, &row, source_kind, &evidence)?;
        let mut service_attributes = common_iac_attributes(&row);
        if let Some(target_hint) = row.target_hint.as_ref() {
            service_attributes.insert("target_hint".to_owned(), target_hint.clone());
        }
        let service_key = builder.add_entity(OntologyEntityCandidate {
            projection_id: Some(&row.projection_id),
            kind: SoftwareEntityKind::RuntimeService,
            name: row.name,
            namespace: Some(row.provider),
            source_kind,
            evidence: evidence.clone(),
            attributes: service_attributes,
        })?;
        builder.add_statement(
            deployment_key,
            SoftwarePredicate::RunsAs,
            Some(service_key),
            None,
            source_kind,
            evidence,
            SoftwareAssertionMode::Declared,
            resolution,
            row.confidence,
        )?;
        return Ok(());
    }

    let deployment_key = deployment_unit(builder, &row, source_kind, &evidence)?;
    let resource_key = builder.add_entity(OntologyEntityCandidate {
        projection_id: Some(&row.projection_id),
        kind: SoftwareEntityKind::Resource,
        name: row.name.clone(),
        namespace: Some(row.provider.clone()),
        source_kind,
        evidence: evidence.clone(),
        attributes: common_iac_attributes(&row),
    })?;
    builder.add_statement(
        deployment_key.clone(),
        SoftwarePredicate::Contains,
        Some(resource_key),
        None,
        source_kind,
        evidence.clone(),
        SoftwareAssertionMode::Declared,
        resolution,
        row.confidence,
    )?;
    if matches!(row.resource_kind.as_str(), "image" | "container_image")
        && let Some(target_hint) = row.target_hint
    {
        let artifact_key = builder.add_entity(OntologyEntityCandidate {
            projection_id: None,
            kind: SoftwareEntityKind::ReleaseArtifact,
            name: target_hint,
            namespace: Some("container".to_owned()),
            source_kind,
            evidence: evidence.clone(),
            attributes: BTreeMap::new(),
        })?;
        builder.add_statement(
            deployment_key,
            SoftwarePredicate::Deploys,
            Some(artifact_key),
            None,
            source_kind,
            evidence,
            SoftwareAssertionMode::Declared,
            resolution,
            row.confidence,
        )?;
    }
    Ok(())
}

fn deployment_unit(
    builder: &mut OntologyBuilder,
    row: &IacRow,
    source_kind: SoftwareSourceKind,
    evidence: &crate::domain::SoftwareEvidenceRef,
) -> Result<String, StorageError> {
    if let Some(key) = builder.deployment_by_path.get(&row.path) {
        return Ok(key.clone());
    }
    let mut attributes = BTreeMap::new();
    attributes.insert("provider".to_owned(), row.provider.clone());
    attributes.insert("language_id".to_owned(), row.language_id.clone());
    let key = builder.add_entity(OntologyEntityCandidate {
        projection_id: None,
        kind: SoftwareEntityKind::DeploymentUnit,
        name: row.path.clone(),
        namespace: Some(row.provider.clone()),
        source_kind,
        evidence: evidence.clone(),
        attributes,
    })?;
    builder
        .deployment_by_path
        .insert(row.path.clone(), key.clone());
    builder.add_statement(
        builder.snapshot_key.clone(),
        SoftwarePredicate::Contains,
        Some(key.clone()),
        None,
        source_kind,
        evidence.clone(),
        SoftwareAssertionMode::Declared,
        SoftwareStatementResolution::Resolved,
        row.confidence,
    )?;
    Ok(key)
}

fn common_iac_attributes(row: &IacRow) -> BTreeMap<String, String> {
    let mut attributes = BTreeMap::new();
    attributes.insert("provider".to_owned(), row.provider.clone());
    attributes.insert("resource_kind".to_owned(), row.resource_kind.clone());
    attributes.insert("language_id".to_owned(), row.language_id.clone());
    attributes.insert("resolution_state".to_owned(), row.resolution_state.clone());
    if let Some(scope_hint) = row.scope_hint.as_ref() {
        attributes.insert("scope_hint".to_owned(), scope_hint.clone());
    }
    if let Some(target_hint) = row.target_hint.as_ref() {
        attributes.insert("target_hint".to_owned(), target_hint.clone());
    }
    attributes
}

pub(super) fn collect_design_elements(
    connection: &Connection,
    builder: &mut OntologyBuilder,
) -> Result<(), StorageError> {
    let mut statement = connection.prepare(
        "
        SELECT element_id, language_id, element_kind, name, parent, summary,
               source_kind, evidence_path, evidence_line_start, evidence_line_end,
               confidence_basis_points
        FROM software_design_elements
        WHERE source_scope = ?1
        ORDER BY evidence_path ASC, evidence_line_start ASC, element_id ASC
        ",
    )?;
    let rows = statement.query_map(params![builder.source_scope], |row| {
        Ok(DesignRow {
            projection_id: row.get(0)?,
            language_id: row.get(1)?,
            element_kind: row.get(2)?,
            name: row.get(3)?,
            parent: row.get(4)?,
            summary: row.get(5)?,
            source_kind: row.get(6)?,
            path: row.get(7)?,
            line_start: row.get(8)?,
            line_end: row.get(9)?,
            confidence: row.get(10)?,
        })
    })?;
    for row in rows {
        let row = row?;
        let evidence = builder.evidence(&row.path, row.line_start, row.line_end)?;
        let source_kind = source_kind_for(&row.source_kind, &row.path);
        let entity_kind = design_entity_kind(&row);
        let mut attributes = BTreeMap::new();
        attributes.insert("language_id".to_owned(), row.language_id);
        attributes.insert("design_kind".to_owned(), row.element_kind);
        if let Some(parent) = row.parent {
            attributes.insert("parent".to_owned(), parent);
        }
        if let Some(summary) = row.summary {
            attributes.insert("summary".to_owned(), summary);
        }
        let namespace = if entity_kind == SoftwareEntityKind::DocumentationUnit {
            Some(row.path.clone())
        } else {
            Some(row.source_kind.clone())
        };
        let entity_key = builder.add_entity(OntologyEntityCandidate {
            projection_id: Some(&row.projection_id),
            kind: entity_kind,
            name: row.name,
            namespace,
            source_kind,
            evidence: evidence.clone(),
            attributes,
        })?;
        let predicate = if entity_kind == SoftwareEntityKind::DocumentationUnit {
            SoftwarePredicate::Documents
        } else {
            SoftwarePredicate::Contains
        };
        let (subject, object) = if predicate == SoftwarePredicate::Documents {
            (entity_key, builder.snapshot_key.clone())
        } else {
            (builder.snapshot_key.clone(), entity_key)
        };
        builder.add_statement(
            subject,
            predicate,
            Some(object),
            None,
            source_kind,
            evidence,
            SoftwareAssertionMode::Declared,
            SoftwareStatementResolution::Resolved,
            row.confidence,
        )?;
    }
    Ok(())
}

fn design_entity_kind(row: &DesignRow) -> SoftwareEntityKind {
    if row.source_kind == "markdown-metadata" {
        return match row.element_kind.as_str() {
            "software_system" => SoftwareEntityKind::SoftwareSystem,
            "api" | "interface" => SoftwareEntityKind::Api,
            "component" | "module" => SoftwareEntityKind::Component,
            "resource" => SoftwareEntityKind::Resource,
            _ => SoftwareEntityKind::DocumentationUnit,
        };
    }
    if row.source_kind == "markdown" {
        SoftwareEntityKind::DocumentationUnit
    } else {
        SoftwareEntityKind::Component
    }
}

struct BuildRow {
    projection_id: String,
    ecosystem: String,
    language_id: String,
    name: String,
    kind: String,
    command: Option<String>,
    output_hint: Option<String>,
    source_kind: String,
    path: String,
    line_start: u32,
    line_end: u32,
    confidence: u16,
}

struct IacRow {
    projection_id: String,
    language_id: String,
    provider: String,
    resource_kind: String,
    name: String,
    scope_hint: Option<String>,
    target_hint: Option<String>,
    resolution_state: String,
    source_kind: String,
    path: String,
    line_start: u32,
    line_end: u32,
    confidence: u16,
}

struct DesignRow {
    projection_id: String,
    language_id: String,
    element_kind: String,
    name: String,
    parent: Option<String>,
    summary: Option<String>,
    source_kind: String,
    path: String,
    line_start: u32,
    line_end: u32,
    confidence: u16,
}