rust-kgdb 0.6.81 → 0.6.83

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.
@@ -0,0 +1,268 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * ================================================================================
4
+ * RpcFederationProxy: Virtual Tables Demo
5
+ * Session-Bound Query Result Materialization
6
+ * ================================================================================
7
+ *
8
+ * Virtual Tables in HyperFederate:
9
+ * - Session-bound materialization of federation query results
10
+ * - Stored as RDF triples in KGDB (self-describing)
11
+ * - Access control via shared_with and shared_with_groups
12
+ * - Refresh policies: on_demand, ttl, on_source_change
13
+ * - No ETL required - real-time query materialization
14
+ *
15
+ * Architecture:
16
+ * - Heavy lifting in Rust core (DataFusion, Arrow, KGDB storage)
17
+ * - TypeScript SDK provides thin RPC proxy layer
18
+ *
19
+ * Run: node examples/rpc-virtual-tables-demo.js
20
+ *
21
+ * @requires HyperFederate server running at http://localhost:30180
22
+ */
23
+
24
+ const {
25
+ RpcFederationProxy,
26
+ WasmSandbox,
27
+ ProofDAG
28
+ } = require('../index.js')
29
+
30
+ // ================================================================================
31
+ // DEMO: Virtual Tables
32
+ // ================================================================================
33
+
34
+ async function runDemo() {
35
+ console.log('╔══════════════════════════════════════════════════════════════════════╗')
36
+ console.log('║ RpcFederationProxy: Virtual Tables Demo ║')
37
+ console.log('║ Session-Bound Query Result Materialization ║')
38
+ console.log('╚══════════════════════════════════════════════════════════════════════╝\n')
39
+
40
+ // Create RpcFederationProxy
41
+ const federation = new RpcFederationProxy({
42
+ endpoint: process.env.HYPERFEDERATE_URL || 'http://localhost:30180',
43
+ identityId: 'risk-analyst-001'
44
+ })
45
+
46
+ console.log(`Federation Endpoint: ${federation.endpoint}`)
47
+ console.log(`Session ID: ${federation.sessionId}`)
48
+ console.log(`Identity ID: ${federation.identityId}`)
49
+ console.log()
50
+
51
+ // ============================================================================
52
+ // 1. Create Virtual Table from Federation Query
53
+ // ============================================================================
54
+ console.log('1. Create Virtual Table from Federation Query')
55
+ console.log('═'.repeat(70))
56
+
57
+ const createVtQuery = `
58
+ -- High-risk customers: KGDB risk scores + Snowflake account data
59
+ SELECT
60
+ kg.person AS kg_entity,
61
+ kg.riskScore AS risk_level,
62
+ entity_type(kg.person) AS entity_types,
63
+ sf.C_NAME AS customer_name,
64
+ sf.C_ACCTBAL AS account_balance,
65
+ sf.C_MKTSEGMENT AS market_segment
66
+ FROM graph_search('
67
+ PREFIX finance: <https://gonnect.ai/domains/finance#>
68
+ PREFIX tpch: <https://gonnect.ai/tpch#>
69
+ SELECT ?person ?riskScore ?custKey WHERE {
70
+ ?risk finance:assessedFor ?person ;
71
+ finance:riskScore ?riskScore .
72
+ ?person tpch:custKey ?custKey .
73
+ FILTER(?riskScore > 0.7)
74
+ }
75
+ ') kg
76
+ JOIN snowflake_tpch.CUSTOMER sf
77
+ ON CAST(kg.custKey AS INTEGER) = sf.C_CUSTKEY
78
+ WHERE sf.C_ACCTBAL > 50000
79
+ `
80
+
81
+ console.log(' SQL Query:')
82
+ console.log(createVtQuery.trim().split('\n').map(l => ' ' + l).join('\n'))
83
+ console.log()
84
+
85
+ try {
86
+ const vt = await federation.createVirtualTable('high_risk_customers', createVtQuery, {
87
+ refreshPolicy: 'on_demand',
88
+ ttlSeconds: 3600,
89
+ sharedWith: ['risk-analyst-002', 'compliance-officer-001'],
90
+ sharedWithGroups: ['team-risk-analytics', 'team-compliance']
91
+ })
92
+
93
+ console.log(' Virtual Table Created:')
94
+ console.log(` ID: ${vt.id}`)
95
+ console.log(` Name: ${vt.name}`)
96
+ console.log(` URI: ${vt.uri}`)
97
+ console.log(` Columns: ${vt.columns.join(', ')}`)
98
+ console.log(` Row Count: ${vt.rowCount}`)
99
+ console.log(` Refresh Policy: ${vt.refreshPolicy}`)
100
+ console.log(` Created At: ${vt.createdAt}`)
101
+ console.log()
102
+ } catch (error) {
103
+ console.log(` [Demo mode - Server not running]`)
104
+ console.log(` Virtual table would be created with:`)
105
+ console.log(` Name: high_risk_customers`)
106
+ console.log(` Refresh Policy: on_demand`)
107
+ console.log(` TTL: 3600 seconds`)
108
+ console.log(` Shared With: risk-analyst-002, compliance-officer-001`)
109
+ console.log(` Shared Groups: team-risk-analytics, team-compliance`)
110
+ console.log()
111
+ }
112
+
113
+ // ============================================================================
114
+ // 2. Query Virtual Table (No Re-execution)
115
+ // ============================================================================
116
+ console.log('2. Query Virtual Table (Materialized Results)')
117
+ console.log('═'.repeat(70))
118
+ console.log(' Virtual tables are materialized - no query re-execution needed.')
119
+ console.log()
120
+ console.log(' Query: SELECT * FROM virtual.high_risk_customers WHERE account_balance > 100000')
121
+ console.log()
122
+
123
+ try {
124
+ const result = await federation.queryVirtualTable('high_risk_customers', 'account_balance > 100000')
125
+ console.log(` Result: ${result.rowCount} rows in ${result.duration}ms`)
126
+ console.log(` (Materialized data, not re-executed)`)
127
+ console.log()
128
+ } catch (error) {
129
+ console.log(` [Demo mode - Would query materialized virtual table]`)
130
+ console.log()
131
+ }
132
+
133
+ // ============================================================================
134
+ // 3. Virtual Table Use Cases
135
+ // ============================================================================
136
+ console.log('3. Virtual Table Use Cases')
137
+ console.log('═'.repeat(70))
138
+ const useCases = [
139
+ {
140
+ name: 'Risk Dashboard',
141
+ query: `CREATE VIRTUAL TABLE risk_dashboard AS
142
+ SELECT entity, risk_score, neighbors(entity, 1) AS network
143
+ FROM high_risk_customers`,
144
+ refresh: 'ttl (5 min)',
145
+ shared: 'team-risk-analytics'
146
+ },
147
+ {
148
+ name: 'Compliance Audit',
149
+ query: `CREATE VIRTUAL TABLE compliance_audit AS
150
+ SELECT entity, risk_score, entity_properties(entity) AS all_props
151
+ FROM high_risk_customers WHERE risk_score > 0.9`,
152
+ refresh: 'on_source_change',
153
+ shared: 'compliance-officers'
154
+ },
155
+ {
156
+ name: 'Customer 360',
157
+ query: `CREATE VIRTUAL TABLE customer_360 AS
158
+ SELECT kg.*, sf.*, bq.name_popularity
159
+ FROM graph_search(...) kg
160
+ JOIN snowflake.CUSTOMER sf ON ...
161
+ LEFT JOIN bigquery.usa_names bq ON ...`,
162
+ refresh: 'on_demand',
163
+ shared: 'team-customer-success'
164
+ }
165
+ ]
166
+
167
+ for (const useCase of useCases) {
168
+ console.log(` ${useCase.name}`)
169
+ console.log(` Refresh: ${useCase.refresh}`)
170
+ console.log(` Shared With: ${useCase.shared}`)
171
+ console.log()
172
+ }
173
+
174
+ // ============================================================================
175
+ // 4. Access Control Model
176
+ // ============================================================================
177
+ console.log('4. Access Control Model')
178
+ console.log('═'.repeat(70))
179
+ console.log(`
180
+ Virtual tables support fine-grained access control:
181
+
182
+ ┌─────────────────────────────────────────────────────────────────────┐
183
+ │ Virtual Table: high_risk_customers │
184
+ │ Owner: risk-analyst-001 (creator) │
185
+ ├─────────────────────────────────────────────────────────────────────┤
186
+ │ shared_with (individuals): │
187
+ │ - risk-analyst-002 [Full access] │
188
+ │ - compliance-officer-001 [Full access] │
189
+ │ │
190
+ │ shared_with_groups (teams): │
191
+ │ - team-risk-analytics [All members have access] │
192
+ │ - team-compliance [All members have access] │
193
+ └─────────────────────────────────────────────────────────────────────┘
194
+
195
+ Access check: has_access(identity_id, groups) → boolean
196
+ `)
197
+
198
+ // ============================================================================
199
+ // 5. RDF Storage (Self-Describing)
200
+ // ============================================================================
201
+ console.log('5. Virtual Table RDF Storage (Self-Describing)')
202
+ console.log('═'.repeat(70))
203
+ console.log(`
204
+ Virtual tables are stored as RDF triples in KGDB:
205
+
206
+ <urn:hyperfederate:vt:${federation.sessionId}:high_risk_customers>
207
+ a hf:VirtualTable ;
208
+ hf:name "high_risk_customers" ;
209
+ hf:sessionId "${federation.sessionId}" ;
210
+ hf:ownerId "${federation.identityId}" ;
211
+ hf:query "SELECT kg.person, kg.riskScore..." ;
212
+ hf:refreshPolicy "on_demand" ;
213
+ hf:rowCount "42"^^xsd:integer ;
214
+ hf:createdAt "2024-12-21T12:00:00Z"^^xsd:dateTime ;
215
+ hf:sourceLineage "kgdb", "snowflake" ;
216
+ hf:sharedWith "risk-analyst-002", "compliance-officer-001" ;
217
+ hf:sharedWithGroups "team-risk-analytics", "team-compliance" .
218
+
219
+ This makes virtual tables queryable via SPARQL!
220
+ `)
221
+
222
+ // ============================================================================
223
+ // 6. ProofDAG Integration
224
+ // ============================================================================
225
+ console.log('6. ProofDAG Integration (Provenance Tracking)')
226
+ console.log('═'.repeat(70))
227
+
228
+ const proof = new ProofDAG('Risk analysis for high-value customers')
229
+
230
+ // Add virtual table creation as evidence
231
+ const vtNode = proof.addVirtualTableEvidence(
232
+ proof.rootId,
233
+ 'high_risk_customers',
234
+ createVtQuery,
235
+ 42 // rowCount
236
+ )
237
+
238
+ console.log(` Root claim: ${proof.rootClaim}`)
239
+ console.log(` Evidence type: virtual_table`)
240
+ console.log(` Proof hash: ${proof.computeHash()}`)
241
+ console.log()
242
+
243
+ // ============================================================================
244
+ // Summary
245
+ // ============================================================================
246
+ console.log('╔══════════════════════════════════════════════════════════════════════╗')
247
+ console.log('║ Demo Complete! ║')
248
+ console.log('╚══════════════════════════════════════════════════════════════════════╝')
249
+ console.log(`
250
+ Virtual Table Benefits:
251
+ - No ETL Pipeline: Real-time query materialization
252
+ - Session Isolation: Each user sees only their tables
253
+ - Access Control: Fine-grained sharing via identities/groups
254
+ - Self-Describing: Stored as RDF, queryable via SPARQL
255
+ - Refresh Policies: on_demand, ttl, on_source_change
256
+ - Provenance: Full lineage tracking via ProofDAG
257
+
258
+ Architecture Principle:
259
+ - Materialization logic in Rust core (DataFusion + KGDB)
260
+ - TypeScript SDK provides thin RPC proxy layer
261
+ - Heavy computation happens server-side
262
+
263
+ Audit Log Entries: ${federation.getAuditLog().length}
264
+ `)
265
+ }
266
+
267
+ // Run the demo
268
+ runDemo().catch(console.error)