#!/usr/bin/env python3 """Time-aware declaration matching over the FIAM query index.""" from __future__ import annotations import json ALLOWED_RELATIONS={ 'rpc':{'fiam.relation.uses','fiam.relation.client-of','fiam.relation.targets'}, 'http':{'fiam.relation.uses','fiam.relation.client-of','fiam.relation.targets'}, 'messaging':{'fiam.relation.uses','fiam.relation.targets','fiam.relation.appends-to','fiam.relation.watches'}, 'database':{'fiam.relation.uses','fiam.relation.reads-from','fiam.relation.writes-to','fiam.relation.targets','fiam.relation.appends-to','fiam.relation.watches'}, } def canonical(conn,ref,at): if not ref:return ref r=conn.execute('SELECT preferred_ref FROM working_identity WHERE observed_ref=? AND snapshot_time<=? ORDER BY snapshot_time DESC LIMIT 1',(ref,at)).fetchone() return r[0] if r else ref def latest_declared_exchanges(conn,population_id,at): rows=conn.execute("SELECT source_id,exchange_id,population_id,snapshot_time FROM exchange_documents WHERE mode='declared-snapshot' AND snapshot_time<=? AND (population_id IS NULL OR population_id=? ) ORDER BY source_id,snapshot_time DESC",(at,population_id)).fetchall() out={} for r in rows: if r['source_id'] not in out:out[r['source_id']]=r['exchange_id'] return set(out.values()) def match_edge(conn,row,population_id,at): exchanges=latest_declared_exchanges(conn,population_id,at) if not exchanges:return {'declared':False,'matches':[],'reason':'no-effective-declaration-snapshot'} fr=canonical(conn,row['from_ref'],at) targets={canonical(conn,row['target_ref'],at)} if row['channel_ref']:targets.add(canonical(conn,row['channel_ref'],at)) if 'intended_target' in row.keys() and row['intended_target']:targets.add(canonical(conn,row['intended_target'],at)) rels=ALLOWED_RELATIONS.get(row['domain'],set().union(*ALLOWED_RELATIONS.values())) marks=','.join('?'*len(exchanges));params=list(exchanges) ds=conn.execute(f'SELECT * FROM declarations WHERE exchange_id IN ({marks})',params).fetchall() hits=[] for d in ds: if d['predicate'] not in rels:continue ds_from=canonical(conn,d['subject_owner'] or d['subject_ref'],at) if ds_from!=fr:continue cands={canonical(conn,d['object_ref'],at),canonical(conn,d['object_owner'],at)} common=targets & {x for x in cands if x} if not common:continue via='channel' if row['channel_ref'] and canonical(conn,row['channel_ref'],at) in common else 'intended-target' if ('intended_target' in row.keys() and row['intended_target'] and canonical(conn,row['intended_target'],at) in common) else 'target' hits.append({'declaration_id':d['declaration_id'],'predicate':d['predicate'],'matched_via':via,'matched_ref':sorted(common)[0],'source_id':d['source_id']}) return {'declared':bool(hits),'matches':hits,'reason':'matched' if hits else 'no-matching-declaration'}