|
4 | 4 | import logging |
5 | 5 | import json |
6 | 6 | from authentication import AppRestrictedAuth |
7 | | -from models.errors import UnhandledResponseError |
| 7 | +from models.errors import ( |
| 8 | + UnhandledResponseError, |
| 9 | + ResourceFoundError, |
| 10 | + UnauthorizedError, |
| 11 | + ServerError, |
| 12 | + TokenValidationError |
| 13 | +) |
8 | 14 |
|
9 | 15 | SQS_ARN = os.getenv("SQS_ARN") |
10 | 16 | MNS_URL = "https://int.api.service.nhs.uk/multicast-notification-service/subscriptions" |
|
13 | 19 | class MnsService: |
14 | 20 | def __init__(self, authenticator: AppRestrictedAuth): |
15 | 21 | self.authenticator = authenticator |
16 | | - |
17 | | - logging.info(f"Using SQS ARN for subscription: {SQS_ARN}") |
18 | | - |
19 | | - def subscribe_notification(self) -> dict | None: |
20 | | - access_token = self.authenticator.get_access_token() |
21 | | - request_headers = { |
| 22 | + self.access_token = self.authenticator.get_access_token() |
| 23 | + self.request_headers = { |
22 | 24 | 'Content-Type': 'application/fhir+json', |
23 | | - 'Authorization': f'Bearer {access_token}', |
| 25 | + 'Authorization': f'Bearer {self.access_token}', |
24 | 26 | 'X-Correlation-ID': str(uuid.uuid4()) |
25 | 27 | } |
26 | | - |
27 | | - subscription_payload = { |
| 28 | + self.subscription_payload = { |
28 | 29 | "resourceType": "Subscription", |
29 | 30 | "status": "requested", |
30 | | - "reason": "Subscribe SQS to MNS test-signal", |
| 31 | + "reason": "Subscribe SQS to NHS Number Change Events", |
31 | 32 | "criteria": "eventType=nhs-number-change-2", |
32 | 33 | "channel": { |
33 | 34 | "type": "message", |
34 | 35 | "endpoint": SQS_ARN, |
35 | 36 | "payload": "application/json" |
36 | 37 | } |
37 | 38 | } |
38 | | - response = requests.post(MNS_URL, headers=request_headers, data=json.dumps(subscription_payload)) |
39 | 39 |
|
40 | | - print(f"Access Token: {access_token}") |
| 40 | + logging.info(f"Using SQS ARN for subscription: {SQS_ARN}") |
| 41 | + |
| 42 | + def subscribe_notification(self) -> dict | None: |
| 43 | + |
| 44 | + response = requests.post(MNS_URL, headers=self.request_headers, data=json.dumps(self.subscription_payload)) |
| 45 | + |
| 46 | + print(f"Access Token: {self.access_token}") |
41 | 47 | print(f"SQS ARN: {SQS_ARN}") |
42 | | - print(f"Headers: {request_headers}") |
43 | | - print(f"Payload: {json.dumps(subscription_payload, indent=2)}") |
| 48 | + print(f"Headers: {self.request_headers}") |
| 49 | + print(f"Payload: {json.dumps(self.subscription_payload, indent=2)}") |
44 | 50 |
|
45 | | - if response.status_code == 201: |
| 51 | + if response.status_code == 200: |
46 | 52 | return response.json() |
| 53 | + elif response.status_code == 409: |
| 54 | + msg = "SQS Queue Already Subscribed, can't re-subscribe" |
| 55 | + raise UnhandledResponseError(response=response.json(), message=msg) |
| 56 | + elif response.status_code == 401: |
| 57 | + msg = "SQS Queue Already Subscribed, can't re-subscribe" |
| 58 | + raise TokenValidationError(response=response.json(), message=msg) |
| 59 | + elif response.status_code == 400: |
| 60 | + msg = "Resource Type provided for this is not correct" |
| 61 | + raise ResourceFoundError(response=response.json(), message=msg) |
| 62 | + elif response.status_code == 403: |
| 63 | + msg = "You don't have the right permissions for this request" |
| 64 | + raise UnauthorizedError(response=response.json(), message=msg) |
| 65 | + elif response.status_code == 500: |
| 66 | + msg = "Internal Server Error" |
| 67 | + raise ServerError(response=response.json(), message=msg) |
| 68 | + else: |
| 69 | + msg = f"Unhandled error: {response.status_code} - {response.text}" |
| 70 | + raise UnhandledResponseError(response=response.json(), message=msg) |
| 71 | + |
| 72 | + def get_subscription(self) -> dict | None: |
| 73 | + response = requests.get(MNS_URL, headers=self.request_headers) |
| 74 | + logging.info(f"GET {MNS_URL}") |
| 75 | + logging.debug(f"Headers: {self.request_headers}") |
| 76 | + |
| 77 | + if response.status_code == 200: |
| 78 | + bundle = response.json() |
| 79 | + # Assume a FHIR Bundle with 'entry' list |
| 80 | + for entry in bundle.get("entry", []): |
| 81 | + resource = entry.get("channel", {}) |
| 82 | + channel = resource.get("channel", {}) |
| 83 | + if channel.get("endpoint") == SQS_ARN: |
| 84 | + return resource # Found a matching subscription |
| 85 | + return None # No subscription for this SQS ARN |
47 | 86 | elif response.status_code == 404: |
48 | 87 | return None |
| 88 | + elif response.status_code == 401: |
| 89 | + msg = "Token validation failed for the request" |
| 90 | + raise TokenValidationError(response=response.json(), message=msg) |
| 91 | + elif response.status_code == 400: |
| 92 | + msg = "Bad request: Resource type or parameters incorrect" |
| 93 | + raise ResourceFoundError(response=response.json(), message=msg) |
| 94 | + elif response.status_code == 403: |
| 95 | + msg = "You don't have the right permissions for this request" |
| 96 | + raise UnauthorizedError(response=response.json(), message=msg) |
| 97 | + elif response.status_code == 500: |
| 98 | + msg = "Internal Server Error" |
| 99 | + raise ServerError(response=response.json(), message=msg) |
49 | 100 | else: |
50 | | - msg = "MNS subscription failed" |
| 101 | + msg = f"Unhandled error: {response.status_code} - {response.text}" |
51 | 102 | raise UnhandledResponseError(response=response.json(), message=msg) |
| 103 | + |
| 104 | + def check_subscription(self) -> dict: |
| 105 | + """ |
| 106 | + Ensures that a subscription exists for this SQS_ARN. |
| 107 | + If not found, creates one. |
| 108 | + Returns the subscription. |
| 109 | + """ |
| 110 | + try: |
| 111 | + existing = self.get_subscription() |
| 112 | + if existing: |
| 113 | + logging.info("Subscription for this SQS ARN already exists.") |
| 114 | + return existing |
| 115 | + else: |
| 116 | + logging.info("No subscription found for this SQS ARN. Creating new subscription...") |
| 117 | + return self.subscribe_notification() |
| 118 | + except Exception as e: |
| 119 | + logging.error(f"Error ensuring subscription: {e}") |
| 120 | + raise |
0 commit comments