-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathapi.py
More file actions
8555 lines (7596 loc) · 287 KB
/
Copy pathapi.py
File metadata and controls
8555 lines (7596 loc) · 287 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""FastAPI dashboard + ingest API for enqueuing background jobs."""
from __future__ import annotations
import asyncio
import contextlib
import hashlib
import logging
import os
import re
import secrets
import smtplib
import json
import threading
import time
from collections.abc import Callable
from contextlib import asynccontextmanager
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from typing import Any, Literal, cast
from urllib.parse import quote, unquote, urlencode, urlparse
from uuid import UUID, uuid4
import httpx
import uvicorn
from fastapi import FastAPI, Query, Request
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse, Response
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel, Field, ValidationError
from psycopg import Connection
from psycopg.rows import dict_row
from five08.audit import (
ActorProvider,
AuditEventInput,
AuditResult,
AuditSource,
insert_audit_event,
)
from five08.agent import (
AgentIdentityContext,
AgentModelConfig,
AgentOrchestrator,
AgentPlan,
AgentRequest,
AgentResponse,
InMemoryTaskStore,
OpenAICompatibleIntentNormalizer,
PolicyEngine,
ToolRegistry,
ToolRuntimeConfig,
)
from five08.clients.espo import EspoAPIError, EspoClient
from five08.logging import configure_observability
from five08.queue import (
EnqueuedJob,
JobRecord,
QueueClient,
JobStatus,
list_jobs,
enqueue_job,
get_job,
get_postgres_connection,
get_redis_connection,
is_postgres_healthy,
)
from five08.backend.auth import (
AuthSession,
DASHBOARD_ADMIN_PERMISSIONS,
DASHBOARD_PERMISSION_AUDIT_READ,
DASHBOARD_PERMISSION_CONFIGURATION_READ,
DASHBOARD_PERMISSION_CONFIGURATION_WRITE,
DASHBOARD_PERMISSION_GIGS_READ,
DASHBOARD_PERMISSION_GIGS_WRITE,
DASHBOARD_PERMISSION_JOBS_READ,
DASHBOARD_PERMISSION_JOBS_WRITE,
DASHBOARD_PERMISSION_ONBOARDING_READ,
DASHBOARD_PERMISSION_ONBOARDING_WRITE,
DASHBOARD_PERMISSION_PEOPLE_READ,
DASHBOARD_PERMISSION_PEOPLE_SYNC,
DASHBOARD_PERMISSION_PROJECTS_READ,
DASHBOARD_PERMISSION_PROJECTS_SYNC,
DASHBOARD_PERMISSION_PROJECTS_SYNC_DRY_RUN,
DASHBOARD_PERMISSION_PROJECTS_WRITE,
DASHBOARD_PERMISSION_JOBS_WRITE_DRY_RUN,
DASHBOARD_PERMISSION_PEOPLE_SYNC_DRY_RUN,
DASHBOARD_SENSITIVE_PERMISSIONS,
DASHBOARD_WORKFLOWS_ENGINEER_SENSITIVE_PERMISSIONS,
ConsumedDiscordLinkGrant,
DiscordAdminVerifier,
DiscordAdminIdentity,
DiscordLinkGrant,
OIDCProviderClient,
PendingOIDCState,
RedisAuthStore,
build_authorization_url,
build_redirect_uri,
dashboard_permissions_for_roles,
extract_groups,
has_dashboard_discord_role,
has_workflows_engineer_role,
is_admin_from_groups,
make_pkce_pair,
normalize_next_path,
)
from five08.clients.erpnext import ERPNextAPIError, ERPNextClient
from five08.backend.dashboard import (
dashboard_assets_dir,
dashboard_html,
discord_link_continue_html,
discord_link_unavailable_html,
login_required_html,
oidc_not_configured_html,
)
from five08.engagements import (
EngagementApplicationStatus,
EngagementStatus,
add_crm_application_to_engagement,
list_dashboard_engagements,
list_dashboard_notifications,
normalize_engagement_status,
update_engagement_application_status,
update_engagement_status,
viewer_can_update_engagement,
)
from five08.engineer_onboarding import (
ActivityCostRequest,
EngineerOnboardingDuplicateNameError,
EngineerOnboardingError,
EngineerSetupRequest,
add_engineer_to_project,
setup_engineer,
)
from five08.onboarding_email import (
OnboardingEmailRequest,
OnboardingEmailSmtpConfig,
build_onboarding_email,
build_onboarding_email_message,
markdown_body_to_html,
markdown_body_to_text,
onboarding_email_smtp_ready,
send_onboarding_email_message,
validate_plain_email,
)
from five08.projects import (
DEFAULT_WIKI_PROJECT_DOC_ID,
PROJECT_ROSTER_KIND_HISTORICAL,
PROJECT_SOURCE_MANUAL,
PROJECT_WIKI_MATCH_CONFIRMED,
PROJECT_WIKI_MATCH_NO_ROW,
add_project_roster_member,
erpnext_project_to_input,
fetch_outline_document,
list_dashboard_projects,
parse_project_wiki_tables,
project_cache_summary,
remove_project_roster_member,
set_project_wiki_match,
upsert_project,
wiki_project_match_preview,
wiki_row_by_key,
)
from five08.runtime_config import (
delete_runtime_config_value,
list_runtime_config,
runtime_config_definition_for_key,
set_runtime_config_value,
)
from five08.worker.config import settings
from five08.worker.db_migrations import run_job_migrations
from five08.worker.dispatcher import build_queue_client
from five08.worker.masking import mask_email
from five08.worker.jobs import (
JOB_FUNCTIONS,
)
from five08.worker.mailbox_resume_ingest import ResumeMailboxProcessor
from five08.worker.models import (
AuditEventPayload,
DocusealWebhookPayload,
EspoCRMWebhookPayload,
GoogleFormsIntakePayload,
)
logger = logging.getLogger(__name__)
_ULID_ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
_PROJECT_ROSTER_USER_CANDIDATE_CACHE_TTL_SECONDS = 60.0
_DISCORD_LINK_REPLAY_TTL_SECONDS = 10
_PROJECT_ROSTER_USER_CANDIDATE_CACHE_MAX_SIZE = 128
_PROJECT_ROSTER_USER_CANDIDATE_CACHE_LOCK = threading.RLock()
_PROJECT_ROSTER_USER_CANDIDATE_CACHE: dict[str, tuple[float, list[dict[str, Any]]]] = {}
class ResumeExtractRequest(BaseModel):
"""Request schema for queued resume extraction."""
contact_id: str
attachment_id: str
filename: str
refresh_token: str | None = None
class ResumeApplyRequest(BaseModel):
"""Request schema for queued resume apply updates."""
contact_id: str
updates: dict[str, Any]
link_discord: dict[str, str] | None = None
class DiscordLinkCreateRequest(BaseModel):
"""Payload for creating one-time admin deep links from Discord commands."""
discord_user_id: str
next_path: str | None = None
discord_display_name: str | None = None
discord_roles: list[str] = Field(default_factory=list)
class AgentConfirmationRequest(BaseModel):
"""Payload for confirming or canceling a frozen agent plan."""
context: AgentIdentityContext
confirm: bool = True
class DashboardAssignOnboarderRequest(BaseModel):
"""Payload for assigning an onboarder from the dashboard."""
onboarder: str
class DashboardOnboardingStatusRequest(BaseModel):
"""Payload for updating one dashboard onboarding status."""
status: str
class DashboardOnboardingEmailDraftRequest(BaseModel):
"""Payload for drafting one dashboard onboarding email."""
has_contributed: bool = False
discord_joined: Literal["yes", "no", "unknown"] = "unknown"
agreement_signed: Literal["yes", "no", "unknown"] = "unknown"
class DashboardOnboardingEmailSendRequest(BaseModel):
"""Payload for sending one reviewed dashboard onboarding email."""
markdown_body: str
has_contributed: bool = False
discord_joined: Literal["yes", "no", "unknown"] = "unknown"
agreement_signed: Literal["yes", "no", "unknown"] = "unknown"
class DashboardGigStatusRequest(BaseModel):
"""Payload for updating one dashboard gig status."""
status: str
class DashboardProjectStatusRequest(BaseModel):
"""Payload for updating one ERPNext Project status."""
status: str
class DashboardBulkProjectUpdateRequest(BaseModel):
"""Payload for bulk ERPNext Project field updates."""
project_ids: list[str]
status: str | None = None
project_type: str | None = None
class DashboardProjectUserRequest(BaseModel):
"""Payload for adding one ERPNext User to a Project roster."""
user: str
candidate_id: str | None = None
activity_type: str | None = None
billing_rate: float | None = None
costing_rate: float | None = None
class DashboardEngineerSetupRequest(BaseModel):
"""Payload for setting up one ERPNext engineer account."""
email: str
first_name: str
middle_name: str | None = None
last_name: str | None = None
country: str | None = None
gender: str | None = None
date_of_birth: str | None = None
date_of_joining: str | None = None
personal_email: str | None = None
prefered_email: str | None = None
class DashboardProjectUserRemoveRequest(BaseModel):
"""Payload for removing one ERPNext User from a Project roster."""
user: str
class DashboardProjectHistoricalMemberRequest(BaseModel):
"""Payload for adding one local historical Project roster member."""
person: str
candidate_id: str | None = None
class DashboardProjectHistoricalMemberRemoveRequest(BaseModel):
"""Payload for removing one local historical Project roster member."""
source_user_id: str
class DashboardProjectWikiMatchRequest(BaseModel):
"""Payload for saving a manual project-to-wiki match decision."""
status: str
row_key: str | None = None
class DashboardProjectCreateRequest(BaseModel):
"""Payload for creating a Customer-backed ERPNext Project."""
project_name: str
customer_mode: Literal["new", "existing"] = "new"
customer_name: str | None = None
customer: str | None = None
account_manager: str | None = None
default_billing_currency: str | None = "USD"
default_cost_center: str | None = "Projects - 5"
activity_type: str | None = None
customer_details: str | None = None
customer_website: str | None = None
address_line1: str | None = None
address_line2: str | None = None
address_city: str | None = None
address_state: str | None = None
address_country: str | None = None
address_postal_code: str | None = None
contact: str | None = None
contact_first_name: str | None = None
contact_last_name: str | None = None
contact_email: str | None = None
contact_phone: str | None = None
contact_mobile: str | None = None
class DashboardGigApplicationStatusRequest(BaseModel):
"""Payload for updating one dashboard gig candidate/application status."""
status: str
class DashboardGigApplicationCreateRequest(BaseModel):
"""Payload for adding one CRM-verified gig candidate/application."""
crm_profile: str = Field(min_length=1, max_length=500)
class DashboardConfigurationUpdateRequest(BaseModel):
"""Payload for updating one admin-managed configuration value."""
value: str | bool | int | float | None = None
clear: bool = False
@dataclass(frozen=True)
class JobsQueryFilters:
"""Normalized query filters for job-list endpoints."""
created_after: datetime
status: JobStatus | None
job_type: str | None
_JOB_FUNCTIONS = JOB_FUNCTIONS
_ONBOARDING_STATUS_FIELD = "cOnboardingState"
_ONBOARDER_FIELD = "cOnboarder"
_GENERIC_UNSUPPORTED_AGENT_MESSAGE = (
"I could not turn that into a supported task action."
)
_SENSITIVE_PAYLOAD_KEY_MARKERS = (
"api_key",
"apikey",
"authorization",
"password",
"refresh_token",
"secret",
"token",
)
_ONBOARDER_USERNAME_CHARS = frozenset("abcdefghijklmnopqrstuvwxyz0123456789._-")
class DashboardOnboarderAssignmentError(Exception):
"""Expected dashboard onboarder assignment validation error."""
def __init__(self, error: str, *, status_code: int = 400) -> None:
super().__init__(error)
self.error = error
self.status_code = status_code
class DashboardOnboardingEmailError(Exception):
"""Expected dashboard onboarding email validation/delivery error."""
def __init__(self, error: str, *, status_code: int = 400) -> None:
super().__init__(error)
self.error = error
self.status_code = status_code
# Backward-compatible direct handler exports expected by existing call sites/tests.
process_webhook_event = JOB_FUNCTIONS["process_webhook_event"]
process_contact_skills_job = JOB_FUNCTIONS["process_contact_skills_job"]
extract_resume_profile_job = JOB_FUNCTIONS["extract_resume_profile_job"]
apply_resume_profile_job = JOB_FUNCTIONS["apply_resume_profile_job"]
process_intake_form_job = JOB_FUNCTIONS["process_intake_form_job"]
process_mailbox_message_job = JOB_FUNCTIONS["process_mailbox_message_job"]
sync_people_from_crm_job = JOB_FUNCTIONS["sync_people_from_crm_job"]
sync_person_from_crm_job = JOB_FUNCTIONS["sync_person_from_crm_job"]
sync_projects_from_erpnext_job = JOB_FUNCTIONS["sync_projects_from_erpnext_job"]
process_docuseal_agreement_job = JOB_FUNCTIONS["process_docuseal_agreement_job"]
# Process-local MVP agent tools stay synchronous for Discord button UX. Both the
# task store and pending plans are non-durable; production task workflows should
# swap this registry for a persistent task service before multi-worker use.
_AGENT_TASK_STORE = InMemoryTaskStore()
_AGENT_ORCHESTRATOR: AgentOrchestrator | None = None
_AGENT_ORCHESTRATOR_LOCK = threading.RLock()
_PENDING_AGENT_PLANS: dict[str, tuple[AgentPlan, AgentIdentityContext]] = {}
_PENDING_AGENT_PLANS_LOCK: asyncio.Lock | None = None
_PENDING_AGENT_PLANS_LOCK_LOOP: asyncio.AbstractEventLoop | None = None
_MAX_PENDING_AGENT_PLANS = 1000
_MAX_PENDING_AGENT_PLANS_PER_ACTOR = 25
_AGENT_REQUEST_RATE_LIMIT_WINDOW_SECONDS = 60.0
_AGENT_REQUEST_RATE_LIMIT_MAX_REQUESTS = 10
_AGENT_REQUEST_TIMESTAMPS: dict[str, list[float]] = {}
_AGENT_REQUEST_RATE_LIMIT_LOCK = threading.RLock()
_AGENT_AUDIT_TASKS: set[asyncio.Task[None]] = set()
def _get_agent_orchestrator() -> AgentOrchestrator:
"""Lazily construct the agent orchestrator so config errors isolate /agent."""
global _AGENT_ORCHESTRATOR
if _AGENT_ORCHESTRATOR is not None:
return _AGENT_ORCHESTRATOR
with _AGENT_ORCHESTRATOR_LOCK:
if _AGENT_ORCHESTRATOR is None:
_AGENT_ORCHESTRATOR = AgentOrchestrator(
registry=ToolRegistry(
_AGENT_TASK_STORE,
runtime_config_factory=lambda: ToolRuntimeConfig.from_settings(
settings
),
),
model_config=AgentModelConfig.from_settings(settings),
intent_normalizer=OpenAICompatibleIntentNormalizer.from_settings(
settings
),
)
return _AGENT_ORCHESTRATOR
def _is_authorized_with_secret(
request: Request,
*,
configured_secret: str | None,
setting_name: str,
) -> bool:
"""Validate an X-API-Secret header against one configured secret."""
secret = (configured_secret or "").strip()
if not secret:
logger.error("Rejecting request: %s is not configured", setting_name)
return False
provided_secret = request.headers.get("X-API-Secret", "")
if secrets.compare_digest(provided_secret, secret):
return True
logger.warning("Rejecting request: invalid X-API-Secret for %s", setting_name)
return False
def _is_authorized(request: Request) -> bool:
"""Validate the internal shared API secret."""
return _is_authorized_with_secret(
request,
configured_secret=settings.api_shared_secret,
setting_name="API_SHARED_SECRET",
)
def _is_webhook_authorized(request: Request) -> bool:
"""Validate the external webhook secret, with legacy API secret fallback."""
webhook_secret = (settings.webhook_shared_secret or "").strip()
if webhook_secret:
return _is_authorized_with_secret(
request,
configured_secret=webhook_secret,
setting_name="WEBHOOK_SHARED_SECRET",
)
return _is_authorized_with_secret(
request,
configured_secret=settings.api_shared_secret,
setting_name="API_SHARED_SECRET",
)
def _agent_request_rate_limited(discord_user_id: str) -> bool:
now = time.monotonic()
window_start = now - _AGENT_REQUEST_RATE_LIMIT_WINDOW_SECONDS
with _AGENT_REQUEST_RATE_LIMIT_LOCK:
for stored_user_id, stored_timestamps in list(
_AGENT_REQUEST_TIMESTAMPS.items()
):
active_timestamps = [
timestamp
for timestamp in stored_timestamps
if timestamp >= window_start
]
if active_timestamps:
_AGENT_REQUEST_TIMESTAMPS[stored_user_id] = active_timestamps
else:
del _AGENT_REQUEST_TIMESTAMPS[stored_user_id]
timestamps = _AGENT_REQUEST_TIMESTAMPS.get(discord_user_id, [])
if len(timestamps) >= _AGENT_REQUEST_RATE_LIMIT_MAX_REQUESTS:
_AGENT_REQUEST_TIMESTAMPS[discord_user_id] = timestamps
return True
timestamps.append(now)
_AGENT_REQUEST_TIMESTAMPS[discord_user_id] = timestamps
return False
def _encode_ulid_base32(value: int, length: int) -> str:
encoded = ["0"] * length
for index in range(length - 1, -1, -1):
encoded[index] = _ULID_ALPHABET[value & 0x1F]
value >>= 5
return "".join(encoded)
def _generate_ulid() -> str:
"""Generate a sortable ULID string without external dependencies."""
timestamp_ms = int(time.time() * 1000)
random_value = int.from_bytes(os.urandom(10), "big")
return f"{_encode_ulid_base32(timestamp_ms, 10)}{_encode_ulid_base32(random_value, 16)}"
def _extract_idempotency_key(value: object) -> str | None:
if isinstance(value, str) and value.strip():
return value.strip()
return None
def _resume_extract_model_name() -> str:
attempts = settings.resolved_resume_ai_provider_attempts
if attempts:
provider = attempts[0]
if provider.label == "primary":
return provider.model
return f"{provider.label}/{provider.model}"
return "heuristic"
def _coerce_docuseal_completed_at_to_utc(value: str) -> str:
"""Normalize Docuseal completion timestamps for queue/job payload contract."""
parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
if parsed.tzinfo is None:
parsed = parsed.replace(tzinfo=timezone.utc)
utc_value = parsed.astimezone(timezone.utc)
return utc_value.strftime("%Y-%m-%d %H:%M:%S")
def _crm_sync_idempotency_key(*, now: datetime) -> str:
interval_seconds = max(1, settings.crm_sync_interval_seconds)
bucket = int(now.timestamp()) // interval_seconds
return f"crm-sync:{bucket}"
def _newsletter_sync_idempotency_key(*, now: datetime) -> str:
interval_seconds = max(1, settings.newsletter_sync_interval_seconds)
bucket = int(now.timestamp()) // interval_seconds
return f"newsletter-sync:508-members:{bucket}"
def _normalize_google_forms_input(value: str | None) -> str | None:
if not isinstance(value, str):
return None
stripped = value.strip()
return stripped or None
def _google_forms_intake_idempotency_key(
*,
email: str,
submission_id: str | None,
submitted_at: str | None,
payload: dict[str, Any],
) -> str:
token = _normalize_google_forms_input(submission_id) or ""
if not token:
token = _normalize_google_forms_input(submitted_at) or ""
if not token:
normalized_payload = json.dumps(
payload,
sort_keys=True,
separators=(",", ":"),
)
token = hashlib.sha256(normalized_payload.encode("utf-8")).hexdigest()
return f"intake:{email}:{token}"
def _validate_google_forms_submission(
payload: GoogleFormsIntakePayload,
) -> JSONResponse | None:
allowed_form_ids = settings.google_forms_allowed_form_ids_set
if not allowed_form_ids:
return None
form_id = (payload.form_id or "").strip()
if form_id and form_id in allowed_form_ids:
return None
return JSONResponse({"error": "invalid_form_id"}, status_code=403)
async def _enqueue_full_crm_sync_job(queue: QueueClient, *, reason: str) -> EnqueuedJob:
now = datetime.now(tz=timezone.utc)
job: EnqueuedJob = await asyncio.to_thread(
enqueue_job,
queue=queue,
fn=JOB_FUNCTIONS["sync_people_from_crm_job"],
args=(),
settings=settings,
idempotency_key=_crm_sync_idempotency_key(now=now),
)
logger.info(
"Enqueued CRM people full-sync job id=%s created=%s reason=%s",
job.id,
job.created,
reason,
)
return job
async def _enqueue_erpnext_project_sync_job(
queue: QueueClient,
*,
reason: str,
) -> EnqueuedJob:
now = datetime.now(tz=timezone.utc)
job: EnqueuedJob = await asyncio.to_thread(
enqueue_job,
queue=queue,
fn=JOB_FUNCTIONS["sync_projects_from_erpnext_job"],
args=(),
settings=settings,
idempotency_key=f"erpnext-project-sync:{now.strftime('%Y%m%d%H%M')}",
)
logger.info(
"Enqueued ERPNext project sync job id=%s created=%s reason=%s",
job.id,
job.created,
reason,
)
return job
async def _enqueue_newsletter_sync_job(
queue: QueueClient,
*,
reason: str,
) -> EnqueuedJob:
now = datetime.now(tz=timezone.utc)
idempotency_key = (
_newsletter_sync_idempotency_key(now=now)
if reason == "scheduler"
else (
f"newsletter-sync:508-members:{reason}:"
f"{now.strftime('%Y%m%d%H%M%S%f')}:{uuid4().hex}"
)
)
job: EnqueuedJob = await asyncio.to_thread(
enqueue_job,
queue=queue,
fn=JOB_FUNCTIONS["sync_508_members_newsletters_job"],
args=(),
settings=settings,
idempotency_key=idempotency_key,
)
logger.info(
"Enqueued 508 members newsletter sync job id=%s created=%s reason=%s",
job.id,
job.created,
reason,
)
return job
async def _crm_sync_scheduler(app: FastAPI) -> None:
queue = app.state.queue
interval_seconds = max(1, settings.crm_sync_interval_seconds)
while True:
try:
await _enqueue_full_crm_sync_job(queue, reason="scheduler")
except Exception:
logger.exception("Failed scheduling CRM full-sync job")
await asyncio.sleep(interval_seconds)
async def _newsletter_sync_scheduler(app: FastAPI) -> None:
queue = app.state.queue
interval_seconds = max(1, settings.newsletter_sync_interval_seconds)
while True:
try:
await _enqueue_newsletter_sync_job(queue, reason="scheduler")
except Exception:
logger.exception("Failed scheduling 508 members newsletter sync job")
await asyncio.sleep(interval_seconds)
async def _email_resume_scheduler() -> None:
"""Run periodic mailbox polling for resume ingestion."""
poller = ResumeMailboxProcessor(settings)
queue = build_queue_client()
interval_seconds = max(1, settings.check_email_wait) * 60
while True:
try:
messages = await asyncio.to_thread(poller.poll_unprocessed_messages)
enqueued = 0
for message in messages:
idempotency_key = (
message.message_id if message.message_id else message.message_num
)
job = await asyncio.to_thread(
enqueue_job,
queue=queue,
fn=JOB_FUNCTIONS["process_mailbox_message_job"],
args=(message.raw_message_b64,),
settings=settings,
idempotency_key=f"mailbox-inbox:{idempotency_key}",
)
if job.created:
enqueued += 1
logger.debug(
"Completed mailbox resume poll discovered_messages=%s queued_jobs=%s",
len(messages),
enqueued,
)
except Exception:
logger.exception("Failed mailbox resume poll iteration")
await asyncio.sleep(interval_seconds)
def _check_postgres_connection(connection: Connection) -> bool:
try:
with connection.cursor() as cursor:
cursor.execute("SELECT 1")
return True
except Exception:
return False
async def _is_postgres_connection_healthy(app: FastAPI) -> bool:
lock = app.state.postgres_conn_lock
async with lock:
connection = app.state.postgres_conn
healthy = await asyncio.to_thread(_check_postgres_connection, connection)
if healthy:
return True
with contextlib.suppress(Exception):
await asyncio.to_thread(connection.close)
try:
refreshed = await asyncio.to_thread(get_postgres_connection, settings)
except Exception:
return False
app.state.postgres_conn = refreshed
return await asyncio.to_thread(_check_postgres_connection, refreshed)
def _enqueue_espocrm_batch_sync(queue: QueueClient, event_ids: list[str]) -> None:
for event_id in event_ids:
enqueue_job(
queue=queue,
fn=JOB_FUNCTIONS["process_contact_skills_job"],
args=(event_id,),
settings=settings,
idempotency_key=f"espocrm:{event_id}",
)
async def _enqueue_espocrm_batch(queue: QueueClient, event_ids: list[str]) -> None:
await asyncio.to_thread(_enqueue_espocrm_batch_sync, queue, event_ids)
def _enqueue_espocrm_people_sync_batch_sync(
queue: QueueClient, event_ids: list[str], *, bucket: str
) -> None:
for event_id in event_ids:
enqueue_job(
queue=queue,
fn=JOB_FUNCTIONS["sync_person_from_crm_job"],
args=(event_id,),
settings=settings,
idempotency_key=f"crm-contact-sync:{event_id}:{bucket}",
)
async def _enqueue_espocrm_people_sync_batch(
queue: QueueClient, event_ids: list[str], *, bucket: str
) -> None:
await asyncio.to_thread(
_enqueue_espocrm_people_sync_batch_sync, queue, event_ids, bucket=bucket
)
def _auth_store_from_app(app: FastAPI) -> RedisAuthStore | None:
store = getattr(app.state, "auth_store", None)
if isinstance(store, RedisAuthStore):
return store
return None
def _oidc_client_from_app(app: FastAPI) -> OIDCProviderClient:
client = getattr(app.state, "oidc_client", None)
if isinstance(client, OIDCProviderClient):
return client
raise RuntimeError("OIDC client not configured")
def _discord_admin_verifier_from_app(app: FastAPI) -> DiscordAdminVerifier:
verifier = getattr(app.state, "discord_admin_verifier", None)
if isinstance(verifier, DiscordAdminVerifier):
return verifier
raise RuntimeError("Discord verifier not configured")
def _http_client_from_app(app: FastAPI) -> httpx.AsyncClient:
client = getattr(app.state, "http_client", None)
if isinstance(client, httpx.AsyncClient):
return client
raise RuntimeError("HTTP client not configured")
def _valid_uuid_or_none(value: str) -> str | None:
try:
return str(UUID(str(value)))
except (TypeError, ValueError, AttributeError):
return None
async def _sync_discord_gig_thread_status(
request: Request,
*,
thread_id: str | None,
status: EngagementStatus,
) -> dict[str, Any]:
"""Best-effort mirror of dashboard gig status to Discord thread title."""
normalized_thread_id = str(thread_id or "").strip()
if not normalized_thread_id:
return {"status": "skipped", "reason": "missing_thread_id"}
base_url = settings.discord_bot_internal_base_url.strip()
if not base_url:
return {"status": "skipped", "reason": "bot_endpoint_not_configured"}
api_secret = str(settings.api_shared_secret or "").strip()
if not api_secret:
return {"status": "skipped", "reason": "api_secret_not_configured"}
try:
response = await _http_client_from_app(request.app).post(
f"{base_url.rstrip('/')}/internal/jobs/thread-status",
headers={"X-API-Secret": api_secret},
json={"thread_id": normalized_thread_id, "status": status.value},
timeout=8.0,
)
except httpx.HTTPError as exc:
logger.warning(
"Failed syncing Discord gig thread status thread_id=%s: %s",
normalized_thread_id,
exc,
)
return {"status": "error", "reason": "bot_request_failed"}
try:
payload = response.json()
except ValueError:
payload = {}
if response.status_code >= 400:
logger.warning(
"Discord gig thread status sync failed thread_id=%s status=%s payload=%s",
normalized_thread_id,
response.status_code,
payload,
)
return {
"status": "error",
"reason": "bot_rejected_request",
"status_code": response.status_code,
}
return cast(dict[str, Any], payload)
MAX_SESSION_COOKIE_CANDIDATES = 5
async def _current_session(request: Request) -> tuple[str | None, AuthSession | None]:
store = _auth_store_from_app(request.app)
if store is None:
return None, None
session_ids = _session_cookie_values(request)
if not session_ids:
return None, None
for session_id in session_ids:
session = await store.get_session(session_id)
if session is not None:
return session_id, session
return session_ids[0], None
def _session_cookie_values(request: Request) -> list[str]:
"""Return bounded, de-duplicated session cookie values in browser order."""
cookie_name = settings.auth_session_cookie_name
values: list[str] = []
def append_candidate(value: str | None) -> None:
if (
value
and value not in values
and len(values) < MAX_SESSION_COOKIE_CANDIDATES
):
values.append(value)
raw_cookie = request.headers.get("cookie", "")
for item in raw_cookie.split(";"):
name, separator, value = item.strip().partition("=")
if separator and name == cookie_name:
append_candidate(value)
append_candidate(request.cookies.get(cookie_name))
return values
def _has_sso_validated_session(session: AuthSession) -> bool:
return bool(session.id_token.strip()) or _dashboard_dev_sensitive_access_enabled()
def _dashboard_dev_sensitive_access_enabled() -> bool:
return settings.environment.strip().lower() in {
"local",
"dev",
"development",
"test",
}
def _dev_discord_link_identity_from_roles(
*,
discord_user_id: str,
discord_roles: list[str],
discord_display_name: str | None,
required_role: str = "Member",
) -> DiscordAdminIdentity | None:
"""Allow trusted bot role context as a local/dev fallback without CRM sync."""
if not _dashboard_dev_sensitive_access_enabled():
return None
if not has_dashboard_discord_role(
discord_roles,
required_role,
admin_role_names=settings.discord_admin_role_names,
):
return None
return DiscordAdminIdentity(
discord_user_id=discord_user_id,
crm_contact_id="",
email=None,
display_name=discord_display_name,
discord_roles=discord_roles,
)
def _request_prefers_json(request: Request) -> bool:
accept = request.headers.get("accept", "")
if not accept.strip():
return False
return _accept_quality(accept, "application/json") > _accept_quality(
accept, "text/html"
)