Skip to content

Commit 9fe198a

Browse files
committed
replace library.use_cache with library.cache_results
1 parent 3fd870f commit 9fe198a

File tree

8 files changed

+55
-59
lines changed

8 files changed

+55
-59
lines changed

plugin/handlers/lookup_handler.py

Lines changed: 25 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -22,31 +22,28 @@ async def callback(self, query: Query):
2222
try:
2323
library = self.plugin.libraries[keyword]
2424
except KeyError:
25-
yield Result(
25+
return Result(
2626
f"Library '{keyword}' not found in settings", icon="Images/error.png"
2727
)
28-
return
2928

30-
if not library.use_cache:
31-
log.debug(
32-
"Library %r not set to use cache, rebuilding for request", library.name
33-
)
34-
msg = await self.plugin.refresh_library_cache(
35-
library, send_noti=False, txt=query.text, wait=True
36-
)
37-
if msg is not None:
38-
yield Result(msg, icon=library.icon)
39-
return
29+
if library.cache_results and (
30+
cached_results := library.result_cache.get(query.text)
31+
):
32+
log.debug("Returning results from result cache")
33+
34+
return cached_results
4035

4136
if library.cache is None:
42-
log.debug("Cache is `None`, refreshing")
37+
log.debug("Refreshing cache for %r, cache or `None`", library.name)
4338
await self.plugin.refresh_library_cache(library)
4439
if library.cache is None:
45-
yield Result(
40+
return Result(
4641
f"Library '{library.name}' not found in cache, and I was unable to build the cache.",
4742
icon="Images/error.png",
4843
)
49-
return
44+
45+
if library.is_api:
46+
await library.make_request(self.plugin.session, query.text)
5047

5148
cache = list(library.cache.items())
5249
if library.is_api:
@@ -55,11 +52,18 @@ async def callback(self, query: Query):
5552
matches = fuzzy_finder(text, cache, key=lambda t: t[0])
5653

5754
if len(matches) == 0:
58-
yield Result("Could not find anything. Sorry.", icon=library.icon)
59-
return
55+
return Result("Could not find anything. Sorry.", icon=library.icon)
56+
57+
results = [
58+
OpenRtfmResult(
59+
library=library,
60+
entry=(entry if isinstance(entry, Entry) else Entry(name, entry)),
61+
score=idx,
62+
)
63+
for idx, (name, entry) in enumerate(reversed(matches))
64+
]
6065

61-
for idx, (name, entry) in enumerate(reversed(matches)):
62-
if isinstance(entry, str):
63-
entry = Entry(name, entry)
66+
if library.cache_results:
67+
library.result_cache[query.text] = results
6468

65-
yield OpenRtfmResult(library=library, entry=entry, score=idx)
69+
return results

plugin/libraries/doctypes/cidex.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,7 @@
2020
CidexResponse = CacheIndex | VariantManifest | ApiIndex
2121
msgpack = msgspec.msgpack.Decoder(type=CidexResponse)
2222
api_decoder = msgspec.json.Decoder(type=Cache)
23-
INDEX_URL = (
24-
"https://github.com/cibere/Rtfm-Indexes/raw/refs/heads/indexes-v2/indexes_v2/{}.cidex"
25-
)
23+
INDEX_URL = "https://github.com/cibere/Rtfm-Indexes/raw/refs/heads/indexes-v2/indexes_v2/{}.cidex"
2624

2725

2826
class CidexBase(Library):
@@ -79,6 +77,7 @@ async def build_cache(self, session: ClientSession, webserver_port: int) -> None
7977
if isinstance(index, ApiIndex):
8078
self.is_api = True
8179
self._api_info = index
80+
self.cache = {}
8281
else:
8382
self.cache = index.cache
8483

plugin/libraries/library.py

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,10 @@
1010
from ..icons import get_icon as _get_icon
1111

1212
if TYPE_CHECKING:
13-
from collections.abc import Mapping
13+
from collections.abc import Iterable, Mapping
1414

1515
from aiohttp import ClientSession
16+
from flogin import Result
1617

1718
from .entry import Entry
1819

@@ -23,15 +24,15 @@ class PartialLibrary(msgspec.Struct):
2324
name: str
2425
type: str
2526
loc: str
26-
use_cache: bool = False
27+
cache_results: bool = False
2728
is_api: bool = False
2829

2930
def to_dict(self):
3031
return {
3132
"name": self.name,
3233
"type": self.type,
3334
"loc": self.loc,
34-
"use_cache": self.use_cache,
35+
"cache_results": self.cache_results,
3536
"is_api": self.is_api,
3637
}
3738

@@ -53,13 +54,15 @@ class Library:
5354
is_api: bool = False
5455
cache: Mapping[str, Entry | str] | None
5556
supports_local: ClassVar[bool] = False
57+
result_cache: dict[str, Iterable[Result]]
5658

57-
def __init__(self, name: str, loc: URL | Path, *, use_cache: bool) -> None:
59+
def __init__(self, name: str, loc: URL | Path, *, cache_results: bool) -> None:
5860
self.name = name
5961
self.loc = loc
6062
self.icon: str | None = None
6163
self.cache = None
62-
self.use_cache = use_cache
64+
self.cache_results = cache_results
65+
self.result_cache = {}
6366

6467
@property
6568
def url(self) -> URL | None:
@@ -70,7 +73,7 @@ def path(self) -> Path | None:
7073
return self.loc if isinstance(self.loc, Path) else None
7174

7275
def __repr__(self) -> str:
73-
return f"<{self.__class__.__name__} {self.name=} {self.url=} {self.icon=} {self.use_cache=} {self.typename=} {self.is_api=}>"
76+
return f"<{self.__class__.__name__} {self.name=} {self.url=} {self.icon=} {self.cache_results=} {self.typename=} {self.is_api=}>"
7477

7578
async def fetch_icon(self) -> str | None:
7679
if self.favicon_url is None:
@@ -104,7 +107,7 @@ def _build_url(self, piece: str, port: int) -> str:
104107

105108
@classmethod
106109
def from_partial(cls: type[Self], data: PartialLibrary) -> Self:
107-
kwargs = {"name": data.name, "use_cache": data.use_cache}
110+
kwargs = {"name": data.name, "cache_results": data.cache_results}
108111

109112
loc: str = data.loc
110113

@@ -124,6 +127,6 @@ def to_partial(self) -> PartialLibrary:
124127
self.name,
125128
type=self.typename,
126129
loc=str(self.loc),
127-
use_cache=self.use_cache,
130+
cache_results=self.cache_results,
128131
is_api=self.is_api,
129132
)

plugin/plugin.py

Lines changed: 6 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -162,26 +162,18 @@ async def refresh_library_cache(
162162
library: Library,
163163
*,
164164
send_noti: bool = True,
165-
txt: str | None = None,
166165
wait: bool = False,
167166
) -> str | None:
168167
log.debug("Building cache for %r", library)
168+
library.result_cache = {}
169169

170170
async def run(coro: Coroutine[Any, Any, Any]):
171171
if wait:
172172
return await coro
173173
asyncio.create_task(coro)
174174

175-
if library.is_api is True:
176-
if txt is None:
177-
await run(library.fetch_icon())
178-
return
179-
coro = library.make_request(self.session, txt)
180-
else:
181-
coro = library.build_cache(self.session, self.webserver_port)
182-
183175
try:
184-
await coro
176+
await library.build_cache(self.session, self.webserver_port)
185177
except Exception as e:
186178
log.exception(
187179
"Sending could not be parsed notification for %r", library, exc_info=e
@@ -256,12 +248,12 @@ async def get_library_from_url(self, name: str, raw_url: str) -> Library | None:
256248
log.debug("Getting library from url: %r", loc)
257249
is_path: bool = isinstance(loc, Path)
258250

259-
for doctype in doc_types:
260-
if is_path is True and doctype.supports_local is False:
251+
for Doctype in doc_types:
252+
if is_path is True and Doctype.supports_local is False:
261253
continue
262-
lib = doctype(name, loc, use_cache=True)
254+
lib = Doctype(name, loc, cache_results=True)
263255
try:
264-
log.debug("Trying doctype: %r", doctype)
256+
log.debug("Trying doctype: %r", Doctype)
265257
await lib.build_cache(self.session, self.webserver_port)
266258
except Exception as e:
267259
log.exception("Failed to build cache for library: %r", name, exc_info=e)

plugin/server/index.html

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
</head>
1010
<body>
1111
<template id="docs-template">
12-
{{ doc(location="{{LOCATION}}", index="{{INDEX}}", type="{{TYPE}}", name="{{NAME}}", use_cache=False, is_api=False) }}
12+
{{ doc(location="{{LOCATION}}", index="{{INDEX}}", type="{{TYPE}}", name="{{NAME}}", cache_results=False, is_api=False) }}
1313
</template>
1414
<main>
1515
{% call card("Rtfm Plugin") %}
@@ -67,7 +67,7 @@
6767
</div>
6868

6969
{% for lib in libs %}
70-
{{ doc(location=lib.loc, index=loop.index, type=lib.typename, name=lib.name, use_cache=lib.use_cache, is_api=lib.is_api) }}
70+
{{ doc(location=lib.loc, index=loop.index, type=lib.typename, name=lib.name, cache_results=lib.cache_results, is_api=lib.is_api) }}
7171
{% endfor %}
7272
</form>
7373
</main>

plugin/server/macros.html

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
</div>
66
{% endmacro %}
77

8-
{% macro doc(location, index, type, name, use_cache, is_api) %}
8+
{% macro doc(location, index, type, name, cache_results, is_api) %}
99
<div class="card" data-index="{{ index }}">
1010
<input type="hidden" name="doc.{{ index }}.loc" value="{{ location }}">
1111
<input type="hidden" name="doc.{{ index }}.type" value="{{ type }}">
@@ -29,17 +29,16 @@
2929
>
3030
{% endcall %}
3131

32-
{% call checkbox(label="Use Cache", id="lib-cache-input-" ~ index, description="If checked, the plugin will cache the index. If not checked, the plugin will rebuild the index for each query.") %}
32+
{% call checkbox(label="Cache Results", id="lib-cache-input-" ~ index, description="If checked, the plugin will cache the results that you get for each query, for faster lookup times on duplicate queries.") %}
3333
<input
3434
id="lib-cache-input-{{ index }}"
3535
type="checkbox"
36-
name="doc.{{ index }}.use_cache"
37-
{% if use_cache %}checked{% endif %}
38-
{% if is_api %}disabled{% endif %}
36+
name="doc.{{ index }}.cache_results"
37+
{% if cache_results %}checked{% endif %}
3938
>
4039
{% endcall %}
4140

42-
{% call checkbox(label="Is API", id="lib-api-input-" ~ index, description="If checked, this means that the plugin must make a web request for each query, and that caching is not supported.") %}
41+
{% call checkbox(label="Is API", id="lib-api-input-" ~ index, description="If checked, this means that the plugin must make a web request for each query, and the API determines the ordering of the results, and which results get shown.") %}
4342
<input type="checkbox" id="lib-api-input-{{ index }}" name="doc.{{ index }}.is_api" disabled {% if is_api %}checked{% endif %}>
4443
{% endcall %}
4544
</div>

plugin/server/payloads/settings.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ def parse_form_data(cls, data: dict[str, str]) -> PluginSettings:
3939
case "doc":
4040
idx = int(parts[1])
4141
match parts[2]:
42-
case "use_cache":
42+
case "cache_results":
4343
value = True
4444
case "keyword":
4545
parts[2] = "name"

plugin/server/script.js

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
* @property {string} name
2222
* @property {string} type
2323
* @property {string} loc
24-
* @property {boolean} use_cache
24+
* @property {boolean} cache_results
2525
* @property {boolean} is_api
2626
*/
2727

@@ -65,9 +65,8 @@ function addNewDoc(data) {
6565
.replaceAll("{{NAME}}", data.name)
6666
.replaceAll("{{TYPE}}", data.type);
6767

68-
const useCacheInput = card.querySelector('input[name$="use_cache"]');
69-
useCacheInput.checked = data.use_cache;
70-
useCacheInput.disabled = data.is_api;
68+
const useCacheInput = card.querySelector('input[name$="cache_results"]');
69+
useCacheInput.checked = data.cache_results;
7170

7271
const isApiInput = card.querySelector('input[name$="is_api"]');
7372
isApiInput.checked = data.is_api;

0 commit comments

Comments
 (0)