Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 35 additions & 20 deletions src/keria/db/basing.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,42 @@

"""

import json
from dataclasses import dataclass
from ordered_set import OrderedSet as oset

from keri.core import coring
from keri.db import dbing, subing, koming

SCALAR_TYPES = ("string", "number")
SCALAR_TYPES = ("string", "number", "integer", "boolean")

ISSUER_FIELD = coring.Pather(path=["i"])
ISSUEE_FIELD = coring.Pather(path=["a", "i"])
SCHEMA_FIELD = coring.Pather(path=["s"])
REGISTRY_FIELD = coring.Pather(path=["ri"])


def indexValue(value):
if isinstance(value, str):
return value
# JSON gives 21.0 and 21 the same value, so they must share an index key
if isinstance(value, float) and value.is_integer():
value = int(value)
return json.dumps(value)


def indexKey(paths, sad):
"""Returns the index key for the values at paths in sad, or None if any path is missing"""
values = []
for path in paths:
try:
values.append(indexValue(coring.Pather(qb64=path).resolve(sad)))
except KeyError:
return None

return "".join(values)


@dataclass
class IndexRecord:
"""Registry Key keyed by Registry name"""
Expand Down Expand Up @@ -220,15 +242,9 @@ def index(self, said):
indexes = self.generateIndexes(schemaSaid)

for index in indexes:
db = self.indexes[index]
idx = self.dynIdx.get(keys=(index,))
values = []
for path in idx.paths:
pather = coring.Pather(qb64=path)
values.append(pather.resolve(creder.sad))

value = "".join(values)
db.add(keys=(value,), val=saider)
if (value := indexKey(idx.paths, creder.sad)) is not None:
self.indexes[index].add(keys=(value,), val=saider)

def unindex(self, said):
if (saider := self.reger.saved.get(keys=(said,))) is None:
Expand All @@ -240,15 +256,9 @@ def unindex(self, said):
raise ValueError(f"No known indexes for schema {creder.schema}")

for index in indexes:
db = self.indexes[index]
idx = self.dynIdx.get(keys=(index,))
values = []
for path in idx.paths:
pather = coring.Pather(qb64=path)
values.append(pather.resolve(creder.sad))

value = "".join(values)
db.rem(keys=(value,), val=saider)
if (value := indexKey(idx.paths, creder.sad)) is not None:
self.indexes[index].rem(keys=(value,), val=saider)

def generateIndexes(self, said):
"""Parse schema of said, create schIdx entry keyed to said of schema and the subkey indexes in
Expand Down Expand Up @@ -311,7 +321,9 @@ def generateIndexes(self, said):
self.dynIdx.pin(keys=(subkey,), val=idx)
self.schIdx.add(keys=(said,), val=subkey)

for field in (ISSUER_FIELD, ISSUEE_FIELD):
for field in (
(ISSUER_FIELD,) if attestation else (ISSUER_FIELD, ISSUEE_FIELD)
):
subkey = f"{field.qb64}.{pather.qb64}"
if subkey not in self.indexes:
self.indexes[subkey] = subing.CesrDupSuber(
Expand Down Expand Up @@ -525,7 +537,7 @@ def indexSearch(self):
return None

idx = self.seeker.indexes[index]
val = "".join(self.values)
val = "".join(indexValue(value) for value in self.values)
return [val.qb64 for val in idx.getIter(keys=(val,))]

def indexScan(self):
Expand Down Expand Up @@ -662,14 +674,17 @@ def __call__(self, *args, **kwargs):
)

val = self.pather.resolve(args[0])
# python treats True == 1, JSON does not
if isinstance(val, bool) != isinstance(self.value, bool):
return False
return val == self.value

@property
def name(self) -> str:
return self.pather.qb64

def index(self, idx):
return [val.qb64 for val in idx.getIter(keys=(self.value,))]
return [val.qb64 for val in idx.getIter(keys=(indexValue(self.value),))]


class Begins:
Expand Down
208 changes: 204 additions & 4 deletions tests/app/test_basing.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,10 @@

import pytest
from keri.app import habbing, signing
from keri.core import parsing
from keri.core import coring, parsing, scheming
from keri.peer import exchanging
from keri.vc import protocoling
from keri.vc import proving, protocoling
from keri.vdr import viring

from keria.db import basing

Expand Down Expand Up @@ -71,10 +72,16 @@ def test_seeker(helpers, seeder, mockHelpingNowUTC):
"5AABAA-i.5AABAA-s.5AACAA-a-LEI",
"4AAB-a-i.5AACAA-a-LEI",
"4AAB-a-i.5AABAA-s.5AACAA-a-LEI",
"5AAEAA-a-gracePeriod",
"5AABAA-s.5AAEAA-a-gracePeriod",
"5AABAA-i.5AAEAA-a-gracePeriod",
"5AABAA-i.5AABAA-s.5AAEAA-a-gracePeriod",
"4AAB-a-i.5AAEAA-a-gracePeriod",
"4AAB-a-i.5AABAA-s.5AAEAA-a-gracePeriod",
]

# Test that the index tables were correctly created
assert len(seeker.indexes) == 29
assert len(seeker.indexes) == 35

indexes = seeker.generateIndexes(LE_SAID)

Expand Down Expand Up @@ -112,7 +119,7 @@ def test_seeker(helpers, seeder, mockHelpingNowUTC):
]

# Assure that no new index tables needed to be created
assert len(seeker.indexes) == 29
assert len(seeker.indexes) == 35

# Test with a bad credential SAID
with pytest.raises(ValueError):
Expand Down Expand Up @@ -387,3 +394,196 @@ def test_exnseeker(helpers, seeder, mockHelpingNowUTC):

saids = seeker.find({"-a-i": {"$eq": issueeHab.pre}})
assert list(saids) == [grant.said, apply.said]


DT = "2026-02-01T00:00:00.000000+00:00"


def makeSchema(props, required):
sed = {
"$id": "",
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"v": {"type": "string"},
"d": {"type": "string"},
"i": {"type": "string"},
"ri": {"type": "string"},
"s": {"type": "string"},
"a": {
"type": "object",
"properties": dict(d={"type": "string"}, **props),
"required": required,
},
},
}
_, sed = coring.Saider.saidify(sed, label="$id")
return scheming.Schemer(sed=sed)


@pytest.fixture
def seekerEnv():
with habbing.openHab(name="seek", salt=b"0123456789abcdef", temp=True) as (
hby,
hab,
):
reger = viring.Reger(temp=True)
seeker = basing.Seeker(db=hby.db, reger=reger, reopen=True, temp=True)

# skip issuance: Seeker only reads the schema, the saved SAID and the credential
def save(props, required, data, issuee=True):
schemer = makeSchema(props, required)
hby.db.schema.pin(keys=(schemer.said,), val=schemer)
creder = proving.credential(
schema=schemer.said,
issuer=hab.pre,
data=data,
recipient=hab.pre if issuee else None,
status="EBfdlu8R27Fbx-ehrqwImnK-8Cm79sqbAQ4MmvEAYqao",
)
reger.creds.put(keys=(creder.said,), val=creder)
reger.saved.pin(keys=(creder.said,), val=coring.Saider(qb64=creder.said))
return creder, schemer

yield hab, seeker, save
seeker.close(clear=True)
reger.close(clear=True)


def indexedIn(seeker, said):
return [
name
for name, db in seeker.indexes.items()
if any(s.qb64 == said for _, s in db.getItemIter())
]


def scanned(seeker, filtr, said):
cursor = seeker.find(filtr)
return cursor.tableScan([said], cursor.operators)


@pytest.mark.parametrize(
"kind,value",
[
("number", 21),
("number", 0),
("number", -7),
("integer", 21),
("integer", 0),
("integer", -7),
("boolean", True),
("boolean", False),
],
)
def test_seeker_non_string_scalars(seekerEnv, kind, value):
hab, seeker, save = seekerEnv
creder, _ = save(
{"i": {"type": "string"}, "x": {"type": kind}, "dt": {"type": "string"}},
["i", "x", "dt"],
dict(i=hab.pre, x=value, dt=DT),
)
seeker.index(creder.said)

filtr = {"-a-x": value}
assert list(seeker.find({}).sort(["-a-dt"])) == [creder.said]
assert list(seeker.find(filtr)) == [creder.said]
assert list(seeker.find({"-s": creder.schema, **filtr})) == [creder.said]
assert list(seeker.find({"-i": hab.pre, "-s": creder.schema, **filtr})) == [
creder.said
]
assert scanned(seeker, filtr, creder.said) == [creder.said]

seeker.unindex(creder.said)
assert indexedIn(seeker, creder.said) == []


def test_seeker_missing_optional_field(seekerEnv):
hab, seeker, save = seekerEnv
creder, _ = save(
{"i": {"type": "string"}, "x": {"type": "string"}, "dt": {"type": "string"}},
["i", "dt"],
dict(i=hab.pre, dt=DT),
)
seeker.index(creder.said)

xPath = coring.Pather(path=["a", "x"]).qb64
assert not [name for name in indexedIn(seeker, creder.said) if xPath in name]
assert indexedIn(seeker, creder.said)
assert list(seeker.find({"-a-i": hab.pre})) == [creder.said]
assert list(seeker.find({"-a-x": "v"})) == []

seeker.unindex(creder.said)
assert indexedIn(seeker, creder.said) == []


def test_seeker_attestation_without_issuee(seekerEnv):
hab, seeker, save = seekerEnv
creder, schemer = save(
{"dt": {"type": "string"}, "x": {"type": "string"}},
["dt", "x"],
dict(dt=DT, x="v"),
issuee=False,
)
seeker.index(creder.said)

issuee = basing.ISSUEE_FIELD.qb64
assert not [name for name in seeker.generateIndexes(schemer.said) if issuee in name]
assert not [name for name in indexedIn(seeker, creder.said) if issuee in name]
assert list(seeker.find({"-a-x": "v"})) == [creder.said]
assert list(seeker.find({"-i": hab.pre, "-a-x": "v"})) == [creder.said]

seeker.unindex(creder.said)
assert indexedIn(seeker, creder.said) == []


@pytest.mark.parametrize(
"kind,stored,queried",
[
("boolean", True, 1),
("boolean", False, 0),
("integer", 1, True),
("integer", 0, False),
],
)
def test_seeker_booleans_and_numbers_never_match(seekerEnv, kind, stored, queried):
hab, seeker, save = seekerEnv
creder, _ = save(
{"i": {"type": "string"}, "x": {"type": kind}},
["i", "x"],
dict(i=hab.pre, x=stored),
)
seeker.index(creder.said)

filtr = {"-a-x": queried}
assert list(seeker.find(filtr)) == []
assert scanned(seeker, filtr, creder.said) == []


@pytest.mark.parametrize("stored,queried", [(21.0, 21), (21, 21.0)])
def test_seeker_integral_float_matches_int(seekerEnv, stored, queried):
hab, seeker, save = seekerEnv
creder, _ = save(
{"i": {"type": "string"}, "x": {"type": "number"}},
["i", "x"],
dict(i=hab.pre, x=stored),
)
seeker.index(creder.said)

filtr = {"-a-x": queried}
assert list(seeker.find(filtr)) == [creder.said]
assert scanned(seeker, filtr, creder.said) == [creder.said]


def test_seeker_fractional_number(seekerEnv):
hab, seeker, save = seekerEnv
creder, _ = save(
{"i": {"type": "string"}, "x": {"type": "number"}},
["i", "x"],
dict(i=hab.pre, x=21.5),
)
seeker.index(creder.said)

filtr = {"-a-x": 21.5}
assert list(seeker.find(filtr)) == [creder.said]
assert scanned(seeker, filtr, creder.said) == [creder.said]
Loading