We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Edition Editing: language autocomplete is slow
### Problem

According to [this](https://internetarchive.slack.com/archives/C0119PRDV46/p1713446825373169?thread_ts=1713436300.354359&cid=C0119PRDV46) thread, it is very slow:

<img width="455" alt="Screenshot 2024-04-22 at 5 32 04 AM" src="https://github.com/internetarchive/openlibrary/assets/978325/54575542-e9a8-4452-a12a-5ed262897196">

#### Evidence / Screenshot

#### Relevant URL(s)
https://openlibrary.org/books/OL24938286M/Pacific_Vortex!/edit

### Reproducing the bug

1. Go to a work edit page
2. Try to add a language

* Expected behavior: Fast
* Actual behavior: Slow


### Context

Other keywords: dropdown, pulldown

### Notes from this Issue's Lead

#### Proposal & constraints
<!-- What is the proposed solution / implementation? Is there a precedent of this approach succeeding elsewhere? -->

#### Related files
<!-- Files related to this issue; this is super useful for new contributors who might want to help! If you're not sure, leave this blank; a maintainer will add them. -->

#### Stakeholders
<!-- @ tag stakeholders of this bug -->


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `openlibrary/plugins/worksearch/autocomplete.py`
Content:
```
1 import itertools
2 import web
3 import json
4 
5 
6 from infogami.utils import delegate
7 from infogami.utils.view import safeint
8 from openlibrary.core.models import Thing
9 from openlibrary.plugins.upstream import utils
10 from openlibrary.plugins.worksearch.search import get_solr
11 from openlibrary.utils import (
12     find_olid_in_string,
13     olid_to_key,
14 )
15 
16 
17 def to_json(d):
18     web.header('Content-Type', 'application/json')
19     return delegate.RawText(json.dumps(d))
20 
21 
22 class autocomplete(delegate.page):
23     path = "/_autocomplete"
24     fq = ['-type:edition']
25     fl = 'key,type,name,title,score'
26     olid_suffix: str | None = None
27     sort: str | None = None
28     query = 'title:"{q}"^2 OR title:({q}*) OR name:"{q}"^2 OR name:({q}*)'
29 
30     def db_fetch(self, key: str) -> Thing | None:
31         if thing := web.ctx.site.get(key):
32             return thing.as_fake_solr_record()
33         else:
34             return None
35 
36     def doc_wrap(self, doc: dict):
37         """Modify the returned solr document in place."""
38         if 'name' not in doc:
39             doc['name'] = doc.get('title')
40 
41     def doc_filter(self, doc: dict) -> bool:
42         """Exclude certain documents"""
43         return True
44 
45     def GET(self):
46         return self.direct_get()
47 
48     def direct_get(self, fq: list[str] | None = None):
49         i = web.input(q="", limit=5)
50         i.limit = safeint(i.limit, 5)
51 
52         solr = get_solr()
53 
54         # look for ID in query string here
55         q = solr.escape(i.q).strip()
56         embedded_olid = None
57         if self.olid_suffix:
58             embedded_olid = find_olid_in_string(q, self.olid_suffix)
59 
60         if embedded_olid:
61             solr_q = f'key:"{olid_to_key(embedded_olid)}"'
62         else:
63             solr_q = self.query.format(q=q)
64 
65         fq = fq or self.fq
66         params = {
67             'q_op': 'AND',
68             'rows': i.limit,
69             **({'fq': fq} if fq else {}),
70             # limit the fields returned for better performance
71             'fl': self.fl,
72             **({'sort': self.sort} if self.sort else {}),
73         }
74 
75         data = solr.select(solr_q, **params)
76         docs = data['docs']
77 
78         if embedded_olid and not docs:
79             # Grumble! Work not in solr yet. Create a dummy.
80             fake_doc = self.db_fetch(olid_to_key(embedded_olid))
81             if fake_doc:
82                 docs = [fake_doc]
83 
84         result_docs = []
85         for d in docs:
86             if self.doc_filter(d):
87                 self.doc_wrap(d)
88                 result_docs.append(d)
89 
90         return to_json(result_docs)
91 
92 
93 class languages_autocomplete(delegate.page):
94     path = "/languages/_autocomplete"
95 
96     def GET(self):
97         i = web.input(q="", limit=5)
98         i.limit = safeint(i.limit, 5)
99         return to_json(
100             list(itertools.islice(utils.autocomplete_languages(i.q), i.limit))
101         )
102 
103 
104 class works_autocomplete(autocomplete):
105     path = "/works/_autocomplete"
106     fq = ['type:work']
107     fl = 'key,title,subtitle,cover_i,first_publish_year,author_name,edition_count'
108     olid_suffix = 'W'
109     query = 'title:"{q}"^2 OR title:({q}*)'
110 
111     def doc_filter(self, doc: dict) -> bool:
112         # Exclude orphaned editions from autocomplete results
113         # Note: Do this here instead of with an `fq=key:*W` for performance
114         # reasons.
115         return doc['key'][-1] == 'W'
116 
117     def doc_wrap(self, doc: dict):
118         doc['full_title'] = doc['title']
119         if 'subtitle' in doc:
120             doc['full_title'] += ": " + doc['subtitle']
121         doc['name'] = doc.get('title')
122 
123 
124 class authors_autocomplete(autocomplete):
125     path = "/authors/_autocomplete"
126     fq = ['type:author']
127     fl = 'key,name,alternate_names,birth_date,death_date,work_count,top_work,top_subjects'
128     olid_suffix = 'A'
129     query = 'name:({q}*) OR alternate_names:({q}*) OR name:"{q}"^2 OR alternate_names:"{q}"^2'
130 
131     def doc_wrap(self, doc: dict):
132         if 'top_work' in doc:
133             doc['works'] = [doc.pop('top_work')]
134         else:
135             doc['works'] = []
136         doc['subjects'] = doc.pop('top_subjects', [])
137 
138 
139 class subjects_autocomplete(autocomplete):
140     # can't use /subjects/_autocomplete because the subjects endpoint = /subjects/[^/]+
141     path = "/subjects_autocomplete"
142     fq = ['type:subject']
143     fl = 'key,name,work_count'
144     query = 'name:({q}*)'
145     sort = 'work_count desc'
146 
147     def GET(self):
148         i = web.input(type="")
149         fq = self.fq
150         if i.type:
151             fq = fq + [f'subject_type:{i.type}']
152 
153         return super().direct_get(fq=fq)
154 
155 
156 def setup():
157     """Do required setup."""
158     pass
159
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/openlibrary/plugins/worksearch/autocomplete.py b/openlibrary/plugins/worksearch/autocomplete.py
--- a/openlibrary/plugins/worksearch/autocomplete.py
+++ b/openlibrary/plugins/worksearch/autocomplete.py
@@ -96,6 +96,7 @@
     def GET(self):
         i = web.input(q="", limit=5)
         i.limit = safeint(i.limit, 5)
+        web.header("Cache-Control", "max-age=%d" % (24 * 3600))
         return to_json(
             list(itertools.islice(utils.autocomplete_languages(i.q), i.limit))
         )

{"golden_diff": "diff --git a/openlibrary/plugins/worksearch/autocomplete.py b/openlibrary/plugins/worksearch/autocomplete.py\n--- a/openlibrary/plugins/worksearch/autocomplete.py\n+++ b/openlibrary/plugins/worksearch/autocomplete.py\n@@ -96,6 +96,7 @@\n     def GET(self):\n         i = web.input(q=\"\", limit=5)\n         i.limit = safeint(i.limit, 5)\n+        web.header(\"Cache-Control\", \"max-age=%d\" % (24 * 3600))\n         return to_json(\n             list(itertools.islice(utils.autocomplete_languages(i.q), i.limit))\n         )\n", "issue": "Edition Editing: language autocomplete is slow\n### Problem\r\n\r\nAccording to [this](https://internetarchive.slack.com/archives/C0119PRDV46/p1713446825373169?thread_ts=1713436300.354359&cid=C0119PRDV46) thread, it is very slow:\r\n\r\n<img width=\"455\" alt=\"Screenshot 2024-04-22 at 5 32 04 AM\" src=\"https://github.com/internetarchive/openlibrary/assets/978325/54575542-e9a8-4452-a12a-5ed262897196\">\r\n\r\n#### Evidence / Screenshot\r\n\r\n#### Relevant URL(s)\r\nhttps://openlibrary.org/books/OL24938286M/Pacific_Vortex!/edit\r\n\r\n### Reproducing the bug\r\n\r\n1. Go to a work edit page\r\n2. Try to add a language\r\n\r\n* Expected behavior: Fast\r\n* Actual behavior: Slow\r\n\r\n\r\n### Context\r\n\r\nOther keywords: dropdown, pulldown\r\n\r\n### Notes from this Issue's Lead\r\n\r\n#### Proposal & constraints\r\n<!-- What is the proposed solution / implementation? Is there a precedent of this approach succeeding elsewhere? -->\r\n\r\n#### Related files\r\n<!-- Files related to this issue; this is super useful for new contributors who might want to help! If you're not sure, leave this blank; a maintainer will add them. -->\r\n\r\n#### Stakeholders\r\n<!-- @ tag stakeholders of this bug -->\r\n\n", "before_files": [{"content": "import itertools\nimport web\nimport json\n\n\nfrom infogami.utils import delegate\nfrom infogami.utils.view import safeint\nfrom openlibrary.core.models import Thing\nfrom openlibrary.plugins.upstream import utils\nfrom openlibrary.plugins.worksearch.search import get_solr\nfrom openlibrary.utils import (\n    find_olid_in_string,\n    olid_to_key,\n)\n\n\ndef to_json(d):\n    web.header('Content-Type', 'application/json')\n    return delegate.RawText(json.dumps(d))\n\n\nclass autocomplete(delegate.page):\n    path = \"/_autocomplete\"\n    fq = ['-type:edition']\n    fl = 'key,type,name,title,score'\n    olid_suffix: str | None = None\n    sort: str | None = None\n    query = 'title:\"{q}\"^2 OR title:({q}*) OR name:\"{q}\"^2 OR name:({q}*)'\n\n    def db_fetch(self, key: str) -> Thing | None:\n        if thing := web.ctx.site.get(key):\n            return thing.as_fake_solr_record()\n        else:\n            return None\n\n    def doc_wrap(self, doc: dict):\n        \"\"\"Modify the returned solr document in place.\"\"\"\n        if 'name' not in doc:\n            doc['name'] = doc.get('title')\n\n    def doc_filter(self, doc: dict) -> bool:\n        \"\"\"Exclude certain documents\"\"\"\n        return True\n\n    def GET(self):\n        return self.direct_get()\n\n    def direct_get(self, fq: list[str] | None = None):\n        i = web.input(q=\"\", limit=5)\n        i.limit = safeint(i.limit, 5)\n\n        solr = get_solr()\n\n        # look for ID in query string here\n        q = solr.escape(i.q).strip()\n        embedded_olid = None\n        if self.olid_suffix:\n            embedded_olid = find_olid_in_string(q, self.olid_suffix)\n\n        if embedded_olid:\n            solr_q = f'key:\"{olid_to_key(embedded_olid)}\"'\n        else:\n            solr_q = self.query.format(q=q)\n\n        fq = fq or self.fq\n        params = {\n            'q_op': 'AND',\n            'rows': i.limit,\n            **({'fq': fq} if fq else {}),\n            # limit the fields returned for better performance\n            'fl': self.fl,\n            **({'sort': self.sort} if self.sort else {}),\n        }\n\n        data = solr.select(solr_q, **params)\n        docs = data['docs']\n\n        if embedded_olid and not docs:\n            # Grumble! Work not in solr yet. Create a dummy.\n            fake_doc = self.db_fetch(olid_to_key(embedded_olid))\n            if fake_doc:\n                docs = [fake_doc]\n\n        result_docs = []\n        for d in docs:\n            if self.doc_filter(d):\n                self.doc_wrap(d)\n                result_docs.append(d)\n\n        return to_json(result_docs)\n\n\nclass languages_autocomplete(delegate.page):\n    path = \"/languages/_autocomplete\"\n\n    def GET(self):\n        i = web.input(q=\"\", limit=5)\n        i.limit = safeint(i.limit, 5)\n        return to_json(\n            list(itertools.islice(utils.autocomplete_languages(i.q), i.limit))\n        )\n\n\nclass works_autocomplete(autocomplete):\n    path = \"/works/_autocomplete\"\n    fq = ['type:work']\n    fl = 'key,title,subtitle,cover_i,first_publish_year,author_name,edition_count'\n    olid_suffix = 'W'\n    query = 'title:\"{q}\"^2 OR title:({q}*)'\n\n    def doc_filter(self, doc: dict) -> bool:\n        # Exclude orphaned editions from autocomplete results\n        # Note: Do this here instead of with an `fq=key:*W` for performance\n        # reasons.\n        return doc['key'][-1] == 'W'\n\n    def doc_wrap(self, doc: dict):\n        doc['full_title'] = doc['title']\n        if 'subtitle' in doc:\n            doc['full_title'] += \": \" + doc['subtitle']\n        doc['name'] = doc.get('title')\n\n\nclass authors_autocomplete(autocomplete):\n    path = \"/authors/_autocomplete\"\n    fq = ['type:author']\n    fl = 'key,name,alternate_names,birth_date,death_date,work_count,top_work,top_subjects'\n    olid_suffix = 'A'\n    query = 'name:({q}*) OR alternate_names:({q}*) OR name:\"{q}\"^2 OR alternate_names:\"{q}\"^2'\n\n    def doc_wrap(self, doc: dict):\n        if 'top_work' in doc:\n            doc['works'] = [doc.pop('top_work')]\n        else:\n            doc['works'] = []\n        doc['subjects'] = doc.pop('top_subjects', [])\n\n\nclass subjects_autocomplete(autocomplete):\n    # can't use /subjects/_autocomplete because the subjects endpoint = /subjects/[^/]+\n    path = \"/subjects_autocomplete\"\n    fq = ['type:subject']\n    fl = 'key,name,work_count'\n    query = 'name:({q}*)'\n    sort = 'work_count desc'\n\n    def GET(self):\n        i = web.input(type=\"\")\n        fq = self.fq\n        if i.type:\n            fq = fq + [f'subject_type:{i.type}']\n\n        return super().direct_get(fq=fq)\n\n\ndef setup():\n    \"\"\"Do required setup.\"\"\"\n    pass\n", "path": "openlibrary/plugins/worksearch/autocomplete.py"}], "after_files": [{"content": "import itertools\nimport web\nimport json\n\n\nfrom infogami.utils import delegate\nfrom infogami.utils.view import safeint\nfrom openlibrary.core.models import Thing\nfrom openlibrary.plugins.upstream import utils\nfrom openlibrary.plugins.worksearch.search import get_solr\nfrom openlibrary.utils import (\n    find_olid_in_string,\n    olid_to_key,\n)\n\n\ndef to_json(d):\n    web.header('Content-Type', 'application/json')\n    return delegate.RawText(json.dumps(d))\n\n\nclass autocomplete(delegate.page):\n    path = \"/_autocomplete\"\n    fq = ['-type:edition']\n    fl = 'key,type,name,title,score'\n    olid_suffix: str | None = None\n    sort: str | None = None\n    query = 'title:\"{q}\"^2 OR title:({q}*) OR name:\"{q}\"^2 OR name:({q}*)'\n\n    def db_fetch(self, key: str) -> Thing | None:\n        if thing := web.ctx.site.get(key):\n            return thing.as_fake_solr_record()\n        else:\n            return None\n\n    def doc_wrap(self, doc: dict):\n        \"\"\"Modify the returned solr document in place.\"\"\"\n        if 'name' not in doc:\n            doc['name'] = doc.get('title')\n\n    def doc_filter(self, doc: dict) -> bool:\n        \"\"\"Exclude certain documents\"\"\"\n        return True\n\n    def GET(self):\n        return self.direct_get()\n\n    def direct_get(self, fq: list[str] | None = None):\n        i = web.input(q=\"\", limit=5)\n        i.limit = safeint(i.limit, 5)\n\n        solr = get_solr()\n\n        # look for ID in query string here\n        q = solr.escape(i.q).strip()\n        embedded_olid = None\n        if self.olid_suffix:\n            embedded_olid = find_olid_in_string(q, self.olid_suffix)\n\n        if embedded_olid:\n            solr_q = f'key:\"{olid_to_key(embedded_olid)}\"'\n        else:\n            solr_q = self.query.format(q=q)\n\n        fq = fq or self.fq\n        params = {\n            'q_op': 'AND',\n            'rows': i.limit,\n            **({'fq': fq} if fq else {}),\n            # limit the fields returned for better performance\n            'fl': self.fl,\n            **({'sort': self.sort} if self.sort else {}),\n        }\n\n        data = solr.select(solr_q, **params)\n        docs = data['docs']\n\n        if embedded_olid and not docs:\n            # Grumble! Work not in solr yet. Create a dummy.\n            fake_doc = self.db_fetch(olid_to_key(embedded_olid))\n            if fake_doc:\n                docs = [fake_doc]\n\n        result_docs = []\n        for d in docs:\n            if self.doc_filter(d):\n                self.doc_wrap(d)\n                result_docs.append(d)\n\n        return to_json(result_docs)\n\n\nclass languages_autocomplete(delegate.page):\n    path = \"/languages/_autocomplete\"\n\n    def GET(self):\n        i = web.input(q=\"\", limit=5)\n        i.limit = safeint(i.limit, 5)\n        web.header(\"Cache-Control\", \"max-age=%d\" % (24 * 3600))\n        return to_json(\n            list(itertools.islice(utils.autocomplete_languages(i.q), i.limit))\n        )\n\n\nclass works_autocomplete(autocomplete):\n    path = \"/works/_autocomplete\"\n    fq = ['type:work']\n    fl = 'key,title,subtitle,cover_i,first_publish_year,author_name,edition_count'\n    olid_suffix = 'W'\n    query = 'title:\"{q}\"^2 OR title:({q}*)'\n\n    def doc_filter(self, doc: dict) -> bool:\n        # Exclude orphaned editions from autocomplete results\n        # Note: Do this here instead of with an `fq=key:*W` for performance\n        # reasons.\n        return doc['key'][-1] == 'W'\n\n    def doc_wrap(self, doc: dict):\n        doc['full_title'] = doc['title']\n        if 'subtitle' in doc:\n            doc['full_title'] += \": \" + doc['subtitle']\n        doc['name'] = doc.get('title')\n\n\nclass authors_autocomplete(autocomplete):\n    path = \"/authors/_autocomplete\"\n    fq = ['type:author']\n    fl = 'key,name,alternate_names,birth_date,death_date,work_count,top_work,top_subjects'\n    olid_suffix = 'A'\n    query = 'name:({q}*) OR alternate_names:({q}*) OR name:\"{q}\"^2 OR alternate_names:\"{q}\"^2'\n\n    def doc_wrap(self, doc: dict):\n        if 'top_work' in doc:\n            doc['works'] = [doc.pop('top_work')]\n        else:\n            doc['works'] = []\n        doc['subjects'] = doc.pop('top_subjects', [])\n\n\nclass subjects_autocomplete(autocomplete):\n    # can't use /subjects/_autocomplete because the subjects endpoint = /subjects/[^/]+\n    path = \"/subjects_autocomplete\"\n    fq = ['type:subject']\n    fl = 'key,name,work_count'\n    query = 'name:({q}*)'\n    sort = 'work_count desc'\n\n    def GET(self):\n        i = web.input(type=\"\")\n        fq = self.fq\n        if i.type:\n            fq = fq + [f'subject_type:{i.type}']\n\n        return super().direct_get(fq=fq)\n\n\ndef setup():\n    \"\"\"Do required setup.\"\"\"\n    pass\n", "path": "openlibrary/plugins/worksearch/autocomplete.py"}]}