From d5810a530f72be93678c27f2c3007ce728f871bf Mon Sep 17 00:00:00 2001
From: Reid 'arrdem' McKenzie <me@arrdem.com>
Date: Mon, 19 Jun 2023 23:24:10 -0600
Subject: [PATCH] Cache API clients to reduce 500 risk(s)

---
 projects/tentacles/src/python/tentacles/workers.py | 14 ++++++++++----
 1 file changed, 10 insertions(+), 4 deletions(-)

diff --git a/projects/tentacles/src/python/tentacles/workers.py b/projects/tentacles/src/python/tentacles/workers.py
index 03cd5e9..ec0024d 100644
--- a/projects/tentacles/src/python/tentacles/workers.py
+++ b/projects/tentacles/src/python/tentacles/workers.py
@@ -8,6 +8,7 @@ Mostly related to monitoring and managing Printer state.
 """
 
 from contextlib import closing
+from functools import cache
 import logging
 from pathlib import Path
 from pprint import pformat
@@ -49,6 +50,11 @@ class OctoRest(_OR):
                 raise e
 
 
+@cache
+def get_client(url, key):
+    return OctoRest(url=url, apikey=key)
+
+
 log = logging.getLogger(__name__)
 
 
@@ -65,7 +71,7 @@ def poll_printers(app: App, db: Db) -> None:
 
         printer_job = {}
         try:
-            client = OctoRest(url=printer.url, apikey=printer.api_key)
+            client = get_client(printer.url, printer.api_key)
             printer_job: dict = client.job_info()
             try:
                 printer_state: dict = client.printer().get("state").get("flags", {})
@@ -136,7 +142,7 @@ def push_jobs(app: App, db: Db) -> None:
             db.delete_job(job.user_id, job.id)
 
         try:
-            client = OctoRest(url=printer.url, apikey=printer.api_key)
+            client = get_client(printer.url, printer.api_key)
             printer_job = client.job_info()
             try:
                 printer_state = client.printer().get("state").get("flags", {})
@@ -182,7 +188,7 @@ def revoke_jobs(app: App, db: Db) -> None:
 
             try:
                 log.info(f"Cancelling running job {job.id}")
-                client = OctoRest(url=printer.url, apikey=printer.api_key)
+                client = get_client(printer.url, printer.api_key)
                 try:
                     client.cancel()
                 except HTTPError as e:
@@ -211,7 +217,7 @@ def pull_jobs(app: App, db: Db) -> None:
     for job in db.list_running_jobs():
         printer = db.fetch_printer(pid=job.printer_id)
         try:
-            client = OctoRest(url=printer.url, apikey=printer.api_key)
+            client = get_client(printer.url, printer.api_key)
             job_state = client.job_info()
             try:
                 printer_state = client.printer().get("state").get("flags", {})